From 5887396150b2b5b8276cd56797ed930b39c6ec05 Mon Sep 17 00:00:00 2001 From: "ishell@chromium.org" Date: Fri, 2 Dec 2016 16:09:19 +0100 Subject: [PATCH 001/291] deps: cherry-pick a814b8a from upstream V8 Original commit message: Merged: [heap] Clear recorded slots for inobject properties when migrating fast object to slow mode. Revision: a814b8aeaf2b56635054c96435972dce90576f62 BUG=chromium:666046 LOG=N NOTRY=true NOPRESUBMIT=true NOTREECHECKS=true R=ulan@chromium.org Review URL: https://codereview.chromium.org/2549803002 . Cr-Commit-Position: refs/branch-heads/5.5@{#60} Cr-Branched-From: 3cbd5838bd8376103daa45d69dade929ee4e0092-refs/heads/5.5.372@{#1} Cr-Branched-From: b3c8b0ce2c9af0528837d8309625118d4096553b-refs/heads/master@{#40015} PR-URL: https://github.com/nodejs/node/pull/10733 Reviewed-By: Reviewed-By: jasnell - James M Snell Reviewed-By: mhdawson - Michael Dawson --- deps/v8/include/v8-version.h | 2 +- deps/v8/src/objects.cc | 13 ++++- .../v8/test/mjsunit/regress/regress-666046.js | 57 +++++++++++++++++++ 3 files changed, 68 insertions(+), 4 deletions(-) create mode 100644 deps/v8/test/mjsunit/regress/regress-666046.js diff --git a/deps/v8/include/v8-version.h b/deps/v8/include/v8-version.h index 009a3b10425ee4..a39676e3779c60 100644 --- a/deps/v8/include/v8-version.h +++ b/deps/v8/include/v8-version.h @@ -11,7 +11,7 @@ #define V8_MAJOR_VERSION 5 #define V8_MINOR_VERSION 4 #define V8_BUILD_NUMBER 500 -#define V8_PATCH_LEVEL 45 +#define V8_PATCH_LEVEL 46 // Use 1 for candidates and 0 otherwise. // (Boolean macro values are not supported by all preprocessors.) diff --git a/deps/v8/src/objects.cc b/deps/v8/src/objects.cc index 00721c2d1bbe1b..2931bd14a9b8de 100644 --- a/deps/v8/src/objects.cc +++ b/deps/v8/src/objects.cc @@ -3449,9 +3449,16 @@ void MigrateFastToSlow(Handle object, Handle new_map, // Ensure that in-object space of slow-mode object does not contain random // garbage. int inobject_properties = new_map->GetInObjectProperties(); - for (int i = 0; i < inobject_properties; i++) { - FieldIndex index = FieldIndex::ForPropertyIndex(*new_map, i); - object->RawFastPropertyAtPut(index, Smi::FromInt(0)); + if (inobject_properties) { + Heap* heap = isolate->heap(); + heap->ClearRecordedSlotRange( + object->address() + map->GetInObjectPropertyOffset(0), + object->address() + new_instance_size); + + for (int i = 0; i < inobject_properties; i++) { + FieldIndex index = FieldIndex::ForPropertyIndex(*new_map, i); + object->RawFastPropertyAtPut(index, Smi::FromInt(0)); + } } isolate->counters()->props_to_dictionary()->Increment(); diff --git a/deps/v8/test/mjsunit/regress/regress-666046.js b/deps/v8/test/mjsunit/regress/regress-666046.js new file mode 100644 index 00000000000000..b4615383e0bdae --- /dev/null +++ b/deps/v8/test/mjsunit/regress/regress-666046.js @@ -0,0 +1,57 @@ +// Copyright 2016 the V8 project authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// Flags: --allow-natives-syntax --expose-gc + +function P() { + this.a0 = {}; + this.a1 = {}; + this.a2 = {}; + this.a3 = {}; + this.a4 = {}; +} + +function A() { +} + +var proto = new P(); +A.prototype = proto; + +function foo(o) { + return o.a0; +} + +// Ensure |proto| is in old space. +gc(); +gc(); +gc(); + +// Ensure |proto| is marked as "should be fast". +var o = new A(); +foo(o); +foo(o); +foo(o); +assertTrue(%HasFastProperties(proto)); + +// Contruct a double value that looks like a tagged pointer. +var buffer = new ArrayBuffer(8); +var int32view = new Int32Array(buffer); +var float64view = new Float64Array(buffer); +int32view[0] = int32view[1] = 0x40000001; +var boom = float64view[0]; + + +// Write new space object. +proto.a4 = {a: 0}; +// Immediately delete the field. +delete proto.a4; + +// |proto| must sill be fast. +assertTrue(%HasFastProperties(proto)); + +// Add a double field instead of deleted a4 that looks like a tagged pointer. +proto.boom = boom; + +// Boom! +gc(); From 61f6f1260d29bd91af9f09b6ddc0d01ef95f1577 Mon Sep 17 00:00:00 2001 From: Roman Reiss Date: Wed, 11 Jan 2017 00:55:07 +0100 Subject: [PATCH 002/291] src/doc: improve man page and --help - add missing environment variables to --help - add missing flags to man page - sort environment variables alphabetically - add some highlighting to the man page - remove stops from descriptions in --help for consistency - few other minor tweaks to --help PR-URL: https://github.com/nodejs/node/pull/10157 Reviewed-By: James M Snell Reviewed-By: Colin Ihrig Reviewed-By: Italo A. Casas Reviewed-By: Jeremiah Senkpiel --- doc/node.1 | 24 ++++++++++++++++-------- src/node.cc | 31 ++++++++++++++++--------------- 2 files changed, 32 insertions(+), 23 deletions(-) diff --git a/doc/node.1 b/doc/node.1 index ec41a44c7598c3..e7f6d256ae850e 100644 --- a/doc/node.1 +++ b/doc/node.1 @@ -182,28 +182,36 @@ Specify ICU data load path. (overrides \fBNODE_ICU_DATA\fR) \',\'\-separated list of core modules that should print debug information. .TP -.BR NODE_PATH =\fIpath\fR[:\fI...\fR] -\':\'\-separated list of directories prefixed to the module search path. +.BR NODE_DISABLE_COLORS =\fI1\fR +When set to \fI1\fR, colors will not be used in the REPL. .TP -.BR NODE_DISABLE_COLORS=1 -When set to 1 colors will not be used in the REPL. +.BR NODE_EXTRA_CA_CERTS =\fIfile\fR +When set, the well known "root" CAs (like VeriSign) will be extended with the +extra certificates in \fIfile\fR. The file should consist of one or more +trusted certificates in PEM format. A message will be emitted (once) with +\fBprocess.emitWarning()\fR if the file is missing or misformatted, but any +errors are otherwise ignored. .TP .BR NODE_ICU_DATA =\fIfile\fR Data path for ICU (Intl object) data. Will extend linked-in data when compiled with small\-icu support. +.TP +.BR NODE_PATH =\fIpath\fR[:\fI...\fR] +\':\'\-separated list of directories prefixed to the module search path. + .TP .BR NODE_REPL_HISTORY =\fIfile\fR Path to the file used to store the persistent REPL history. The default path -is ~/.node_repl_history, which is overridden by this variable. Setting the +is \fB~/.node_repl_history\fR, which is overridden by this variable. Setting the value to an empty string ("" or " ") disables persistent REPL history. .TP -.BR NODE_TTY_UNSAFE_ASYNC=1 -When set to 1, writes to stdout and stderr will be non-blocking and asynchronous -when outputting to a TTY on platforms which support async stdio. +.BR NODE_TTY_UNSAFE_ASYNC =\fI1\fR +When set to \fI1\fR, writes to stdout and stderr will be non-blocking and +asynchronous when outputting to a TTY on platforms which support async stdio. Setting this will void any guarantee that stdio will not be interleaved or dropped at program exit. \fBAvoid use.\fR diff --git a/src/node.cc b/src/node.cc index bd8248b2e3c9b4..0280eb696c1b84 100644 --- a/src/node.cc +++ b/src/node.cc @@ -3569,8 +3569,7 @@ static void PrintHelp() { " -r, --require module to preload (option can be repeated)\n" " --no-deprecation silence deprecation warnings\n" " --trace-deprecation show stack traces on deprecations\n" - " --throw-deprecation throw an exception anytime a deprecated " - "function is used\n" + " --throw-deprecation throw an exception on deprecations\n" " --no-warnings silence all process warnings\n" " --trace-warnings show stack traces on process warnings\n" " --trace-sync-io show stack trace when use of sync IO\n" @@ -3596,28 +3595,30 @@ static void PrintHelp() { " --icu-data-dir=dir set ICU data load path to dir\n" " (overrides NODE_ICU_DATA)\n" #if !defined(NODE_HAVE_SMALL_ICU) - " note: linked-in ICU data is\n" - " present.\n" + " note: linked-in ICU data is present\n" #endif " --preserve-symlinks preserve symbolic links when resolving\n" - " and caching modules.\n" + " and caching modules\n" #endif "\n" "Environment variables:\n" -#ifdef _WIN32 - "NODE_PATH ';'-separated list of directories\n" -#else - "NODE_PATH ':'-separated list of directories\n" -#endif - " prefixed to the module search path.\n" - "NODE_DISABLE_COLORS set to 1 to disable colors in the REPL\n" + "NODE_DEBUG ','-separated list of core modules that\n" + " should print debug information\n" + "NODE_DISABLE_COLORS set to 1 to disable colors in the REPL\n" + "NODE_EXTRA_CA_CERTS path to additional CA certificates file\n" #if defined(NODE_HAVE_I18N_SUPPORT) - "NODE_ICU_DATA data path for ICU (Intl object) data\n" + "NODE_ICU_DATA data path for ICU (Intl object) data\n" #if !defined(NODE_HAVE_SMALL_ICU) - " (will extend linked-in data)\n" + " (will extend linked-in data)\n" #endif #endif - "NODE_REPL_HISTORY path to the persistent REPL history file\n" +#ifdef _WIN32 + "NODE_PATH ';'-separated list of directories\n" +#else + "NODE_PATH ':'-separated list of directories\n" +#endif + " prefixed to the module search path\n" + "NODE_REPL_HISTORY path to the persistent REPL history file\n" "\n" "Documentation can be found at https://nodejs.org/\n"); } From aa6b9f979ee55ac4e39662d2a0e9ff963ba43767 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C3=ABl=20Zasso?= Date: Sun, 8 Jan 2017 21:11:24 +0100 Subject: [PATCH 003/291] deps: cherry-pick baba152 from V8 upstream Original commit message: fix stepping out of across throwing. R=jgruber@chromium.org BUG=v8:5559 Review-Url: https://codereview.chromium.org/2445233004 Cr-Commit-Position: refs/heads/master@{#40549} PR-URL: https://github.com/nodejs/node/pull/10688 Fixes: https://github.com/nodejs/node/issues/9175 Reviewed-By: James M Snell Reviewed-By: Ali Ijaz Sheikh --- deps/v8/include/v8-version.h | 2 +- deps/v8/src/debug/debug.cc | 2 +- deps/v8/test/mjsunit/regress/regress-5559.js | 38 ++++++++++++++++++++ 3 files changed, 40 insertions(+), 2 deletions(-) create mode 100644 deps/v8/test/mjsunit/regress/regress-5559.js diff --git a/deps/v8/include/v8-version.h b/deps/v8/include/v8-version.h index a39676e3779c60..b383f39b6a766e 100644 --- a/deps/v8/include/v8-version.h +++ b/deps/v8/include/v8-version.h @@ -11,7 +11,7 @@ #define V8_MAJOR_VERSION 5 #define V8_MINOR_VERSION 4 #define V8_BUILD_NUMBER 500 -#define V8_PATCH_LEVEL 46 +#define V8_PATCH_LEVEL 47 // Use 1 for candidates and 0 otherwise. // (Boolean macro values are not supported by all preprocessors.) diff --git a/deps/v8/src/debug/debug.cc b/deps/v8/src/debug/debug.cc index cce167f942934f..ad6cfa02887b02 100644 --- a/deps/v8/src/debug/debug.cc +++ b/deps/v8/src/debug/debug.cc @@ -935,7 +935,7 @@ void Debug::PrepareStepOnThrow() { it.Advance(); } - if (last_step_action() == StepNext) { + if (last_step_action() == StepNext || last_step_action() == StepOut) { while (!it.done()) { Address current_fp = it.frame()->UnpaddedFP(); if (current_fp >= thread_local_.target_fp_) break; diff --git a/deps/v8/test/mjsunit/regress/regress-5559.js b/deps/v8/test/mjsunit/regress/regress-5559.js new file mode 100644 index 00000000000000..c6f32575f55b9b --- /dev/null +++ b/deps/v8/test/mjsunit/regress/regress-5559.js @@ -0,0 +1,38 @@ +// Copyright 2016 the V8 project authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// Flags: --expose-debug-as debug + +Debug = debug.Debug + +var exception = null; +var break_count = 0; + +function listener(event, exec_state, event_data, data) { + if (event != Debug.DebugEvent.Break) return; + try { + print(event_data.sourceLineText()); + assertTrue( + event_data.sourceLineText().indexOf(`Break ${break_count++}.`) > 0); + exec_state.prepareStep(Debug.StepAction.StepOut); + } catch (e) { + exception = e; + } +}; + +function thrower() { + try { + debugger; // Break 0. + throw 'error'; + } catch (err) { + } +} + + +Debug.setListener(listener); +thrower(); +Debug.setListener(null); // Break 1. + +assertNull(exception); +assertEquals(2, break_count); From c9bff043c7ff942b4d050ec2fa25703bec3a5fec Mon Sep 17 00:00:00 2001 From: Brian White Date: Fri, 6 Jan 2017 03:11:38 -0500 Subject: [PATCH 004/291] http: optimize short path validation PR-URL: https://github.com/nodejs/node/pull/10654 Reviewed-By: James M Snell Reviewed-By: Fedor Indutny --- lib/_http_client.js | 50 +++++++++++++++++++++++++++++++++++++-------- 1 file changed, 42 insertions(+), 8 deletions(-) diff --git a/lib/_http_client.js b/lib/_http_client.js index 1846e36e12bf88..ed4c57f124fc14 100644 --- a/lib/_http_client.js +++ b/lib/_http_client.js @@ -15,6 +15,34 @@ const Agent = require('_http_agent'); const Buffer = require('buffer').Buffer; +// The actual list of disallowed characters in regexp form is more like: +// /[^A-Za-z0-9\-._~!$&'()*+,;=/:@]/ +// with an additional rule for ignoring percentage-escaped characters, but +// that's a) hard to capture in a regular expression that performs well, and +// b) possibly too restrictive for real-world usage. So instead we restrict the +// filter to just control characters and spaces. +// +// This function is used in the case of small paths, where manual character code +// checks can greatly outperform the equivalent regexp (tested in V8 5.4). +function isInvalidPath(s) { + var i = 0; + if (s.charCodeAt(0) <= 32) return true; + if (++i >= s.length) return false; + if (s.charCodeAt(1) <= 32) return true; + if (++i >= s.length) return false; + if (s.charCodeAt(2) <= 32) return true; + if (++i >= s.length) return false; + if (s.charCodeAt(3) <= 32) return true; + if (++i >= s.length) return false; + if (s.charCodeAt(4) <= 32) return true; + if (++i >= s.length) return false; + if (s.charCodeAt(5) <= 32) return true; + ++i; + for (; i < s.length; ++i) + if (s.charCodeAt(i) <= 32) return true; + return false; +} + function ClientRequest(options, cb) { var self = this; OutgoingMessage.call(self); @@ -43,14 +71,20 @@ function ClientRequest(options, cb) { if (self.agent && self.agent.protocol) expectedProtocol = self.agent.protocol; - if (options.path && /[\u0000-\u0020]/.test(options.path)) { - // The actual regex is more like /[^A-Za-z0-9\-._~!$&'()*+,;=/:@]/ - // with an additional rule for ignoring percentage-escaped characters - // but that's a) hard to capture in a regular expression that performs - // well, and b) possibly too restrictive for real-world usage. - // Restrict the filter to control characters and spaces. - throw new TypeError('Request path contains unescaped characters'); - } else if (protocol !== expectedProtocol) { + var path; + if (options.path) { + path = '' + options.path; + var invalidPath; + if (path.length <= 39) { // Determined experimentally in V8 5.4 + invalidPath = isInvalidPath(path); + } else { + invalidPath = /[\u0000-\u0020]/.test(path); + } + if (invalidPath) + throw new TypeError('Request path contains unescaped characters'); + } + + if (protocol !== expectedProtocol) { throw new Error('Protocol "' + protocol + '" not supported. ' + 'Expected "' + expectedProtocol + '"'); } From e7859c217f69ee0270b5cde2c5553ae9369b47fb Mon Sep 17 00:00:00 2001 From: Brian White Date: Fri, 6 Jan 2017 03:12:59 -0500 Subject: [PATCH 005/291] http: optimize default method case PR-URL: https://github.com/nodejs/node/pull/10654 Reviewed-By: James M Snell Reviewed-By: Fedor Indutny --- lib/_http_client.js | 17 ++++++++++++++--- lib/_http_common.js | 2 -- lib/_http_outgoing.js | 28 ++++++++++++++-------------- 3 files changed, 28 insertions(+), 19 deletions(-) diff --git a/lib/_http_client.js b/lib/_http_client.js index ed4c57f124fc14..bf77e7e0ce964e 100644 --- a/lib/_http_client.js +++ b/lib/_http_client.js @@ -102,10 +102,21 @@ function ClientRequest(options, cb) { self.socketPath = options.socketPath; self.timeout = options.timeout; - var method = self.method = (options.method || 'GET').toUpperCase(); - if (!common._checkIsHttpToken(method)) { - throw new TypeError('Method must be a valid HTTP token'); + var method = options.method; + var methodIsString = (typeof method === 'string'); + if (method != null && !methodIsString) { + throw new TypeError('Method must be a string'); } + + if (methodIsString && method) { + if (!common._checkIsHttpToken(method)) { + throw new TypeError('Method must be a valid HTTP token'); + } + method = self.method = method.toUpperCase(); + } else { + method = self.method = 'GET'; + } + self.path = options.path || '/'; if (cb) { self.once('response', cb); diff --git a/lib/_http_common.js b/lib/_http_common.js index 2ce523fe6298bd..df21a7526b2e71 100644 --- a/lib/_http_common.js +++ b/lib/_http_common.js @@ -265,8 +265,6 @@ var validTokens = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 // ... 255 ]; function checkIsHttpToken(val) { - if (typeof val !== 'string' || val.length === 0) - return false; if (!validTokens[val.charCodeAt(0)]) return false; if (val.length < 2) diff --git a/lib/_http_outgoing.js b/lib/_http_outgoing.js index 67a8d6f8bb8233..163a00ff9878f4 100644 --- a/lib/_http_outgoing.js +++ b/lib/_http_outgoing.js @@ -319,18 +319,18 @@ function _storeHeader(firstLine, headers) { if (state.sentExpect) this._send(''); } -function storeHeader(self, state, field, value) { - if (!checkIsHttpToken(field)) { +function storeHeader(self, state, key, value) { + if (typeof key !== 'string' || !key || !checkIsHttpToken(key)) { throw new TypeError( - 'Header name must be a valid HTTP Token ["' + field + '"]'); + 'Header name must be a valid HTTP Token ["' + key + '"]'); } if (checkInvalidHeaderChar(value)) { - debug('Header "%s" contains invalid characters', field); + debug('Header "%s" contains invalid characters', key); throw new TypeError('The header content contains invalid characters'); } - state.messageHeader += field + ': ' + escapeHeaderValue(value) + CRLF; + state.messageHeader += key + ': ' + escapeHeaderValue(value) + CRLF; - if (connectionExpression.test(field)) { + if (connectionExpression.test(key)) { state.sentConnectionHeader = true; if (connCloseExpression.test(value)) { self._last = true; @@ -339,26 +339,26 @@ function storeHeader(self, state, field, value) { } if (connUpgradeExpression.test(value)) state.sentConnectionUpgrade = true; - } else if (transferEncodingExpression.test(field)) { + } else if (transferEncodingExpression.test(key)) { state.sentTransferEncodingHeader = true; if (trfrEncChunkExpression.test(value)) self.chunkedEncoding = true; - } else if (contentLengthExpression.test(field)) { + } else if (contentLengthExpression.test(key)) { state.sentContentLengthHeader = true; - } else if (dateExpression.test(field)) { + } else if (dateExpression.test(key)) { state.sentDateHeader = true; - } else if (expectExpression.test(field)) { + } else if (expectExpression.test(key)) { state.sentExpect = true; - } else if (trailerExpression.test(field)) { + } else if (trailerExpression.test(key)) { state.sentTrailer = true; - } else if (upgradeExpression.test(field)) { + } else if (upgradeExpression.test(key)) { state.sentUpgrade = true; } } OutgoingMessage.prototype.setHeader = function setHeader(name, value) { - if (!checkIsHttpToken(name)) + if (typeof name !== 'string' || !name || !checkIsHttpToken(name)) throw new TypeError( 'Header name must be a valid HTTP Token ["' + name + '"]'); if (value === undefined) @@ -538,7 +538,7 @@ OutgoingMessage.prototype.addTrailers = function addTrailers(headers) { field = key; value = headers[key]; } - if (!checkIsHttpToken(field)) { + if (typeof field !== 'string' || !field || !checkIsHttpToken(field)) { throw new TypeError( 'Trailer name must be a valid HTTP Token ["' + field + '"]'); } From 44c0e4f1ad694301efe0f323625bf56c7d15efc8 Mon Sep 17 00:00:00 2001 From: Brian White Date: Fri, 6 Jan 2017 03:13:33 -0500 Subject: [PATCH 006/291] http: avoid duplicate isArray() PR-URL: https://github.com/nodejs/node/pull/10654 Reviewed-By: James M Snell Reviewed-By: Fedor Indutny --- lib/_http_client.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/lib/_http_client.js b/lib/_http_client.js index bf77e7e0ce964e..1e054821d3a48c 100644 --- a/lib/_http_client.js +++ b/lib/_http_client.js @@ -122,7 +122,8 @@ function ClientRequest(options, cb) { self.once('response', cb); } - if (!Array.isArray(options.headers)) { + var headersArray = Array.isArray(options.headers); + if (!headersArray) { if (options.headers) { var keys = Object.keys(options.headers); for (var i = 0, l = keys.length; i < l; i++) { @@ -166,7 +167,7 @@ function ClientRequest(options, cb) { self.useChunkedEncodingByDefault = true; } - if (Array.isArray(options.headers)) { + if (headersArray) { self._storeHeader(self.method + ' ' + self.path + ' HTTP/1.1\r\n', options.headers); } else if (self.getHeader('expect')) { From 5059b76cbcc4c9ad417e07cacbb7876afefe2caf Mon Sep 17 00:00:00 2001 From: Brian White Date: Fri, 6 Jan 2017 03:13:57 -0500 Subject: [PATCH 007/291] http: misc ClientRequest cleanup PR-URL: https://github.com/nodejs/node/pull/10654 Reviewed-By: James M Snell Reviewed-By: Fedor Indutny --- lib/_http_client.js | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/lib/_http_client.js b/lib/_http_client.js index 1e054821d3a48c..b52d3caf63f92c 100644 --- a/lib/_http_client.js +++ b/lib/_http_client.js @@ -95,9 +95,7 @@ function ClientRequest(options, cb) { var port = options.port = options.port || defaultPort || 80; var host = options.host = options.hostname || options.host || 'localhost'; - if (options.setHost === undefined) { - var setHost = true; - } + var setHost = (options.setHost === undefined); self.socketPath = options.socketPath; self.timeout = options.timeout; @@ -126,7 +124,7 @@ function ClientRequest(options, cb) { if (!headersArray) { if (options.headers) { var keys = Object.keys(options.headers); - for (var i = 0, l = keys.length; i < l; i++) { + for (var i = 0; i < keys.length; i++) { var key = keys[i]; self.setHeader(key, options.headers[key]); } @@ -152,7 +150,6 @@ function ClientRequest(options, cb) { } if (options.auth && !this.getHeader('Authorization')) { - //basic auth this.setHeader('Authorization', 'Basic ' + Buffer.from(options.auth).toString('base64')); } From be24cc01874c82fb241dfa0d6592e3f52aadcdb5 Mon Sep 17 00:00:00 2001 From: Brian White Date: Fri, 6 Jan 2017 03:14:30 -0500 Subject: [PATCH 008/291] benchmark: add ClientRequest creation benchmark PR-URL: https://github.com/nodejs/node/pull/10654 Reviewed-By: James M Snell Reviewed-By: Fedor Indutny --- benchmark/http/create-clientrequest.js | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 benchmark/http/create-clientrequest.js diff --git a/benchmark/http/create-clientrequest.js b/benchmark/http/create-clientrequest.js new file mode 100644 index 00000000000000..76134663d00a79 --- /dev/null +++ b/benchmark/http/create-clientrequest.js @@ -0,0 +1,23 @@ +'use strict'; + +var common = require('../common.js'); +var ClientRequest = require('http').ClientRequest; + +var bench = common.createBenchmark(main, { + pathlen: [1, 8, 16, 32, 64, 128], + n: [1e6] +}); + +function main(conf) { + var pathlen = +conf.pathlen; + var n = +conf.n; + + var path = '/'.repeat(pathlen); + var opts = { path: path, createConnection: function() {} }; + + bench.start(); + for (var i = 0; i < n; i++) { + new ClientRequest(opts); + } + bench.end(n); +} From 4ff1d3107fcd998b2d6a26d92f6bfa6407410862 Mon Sep 17 00:00:00 2001 From: Brian White Date: Fri, 6 Jan 2017 04:46:12 -0500 Subject: [PATCH 009/291] test: add http.ClientRequest defaults test PR-URL: https://github.com/nodejs/node/pull/10654 Reviewed-By: James M Snell Reviewed-By: Fedor Indutny --- test/parallel/test-http-client-defaults.js | 24 ++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 test/parallel/test-http-client-defaults.js diff --git a/test/parallel/test-http-client-defaults.js b/test/parallel/test-http-client-defaults.js new file mode 100644 index 00000000000000..d277a60e3df55e --- /dev/null +++ b/test/parallel/test-http-client-defaults.js @@ -0,0 +1,24 @@ +'use strict'; +require('../common'); +const assert = require('assert'); +const ClientRequest = require('http').ClientRequest; + +function noop() {} + +{ + const req = new ClientRequest({ createConnection: noop }); + assert.strictEqual(req.path, '/'); + assert.strictEqual(req.method, 'GET'); +} + +{ + const req = new ClientRequest({ method: '', createConnection: noop }); + assert.strictEqual(req.path, '/'); + assert.strictEqual(req.method, 'GET'); +} + +{ + const req = new ClientRequest({ path: '', createConnection: noop }); + assert.strictEqual(req.path, '/'); + assert.strictEqual(req.method, 'GET'); +} From 3270d4c89bc5ed31ef2ebcda36f2b7fd83ee79ad Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Thu, 22 Dec 2016 17:04:10 -0800 Subject: [PATCH 010/291] doc: clarify information about ABI version MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR-URL: https://github.com/nodejs/node/pull/10419 Reviewed-By: James M Snell Reviewed-By: Michaël Zasso Reviewed-By: Sakthipriyan Vairamani Refs: https://github.com/nodejs/node/pull/9901#discussion_r93575704 --- doc/api/process.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/doc/api/process.md b/doc/api/process.md index 3e0414e59effc4..a7c4414ff65dfa 100644 --- a/doc/api/process.md +++ b/doc/api/process.md @@ -1651,9 +1651,9 @@ added: v0.2.0 * {Object} The `process.versions` property returns an object listing the version strings of -Node.js and its dependencies. In addition, `process.versions.modules` indicates -the current ABI version, which is increased whenever a C++ API changes. Node.js -will refuse to load native modules built for an older `modules` value. +Node.js and its dependencies. `process.versions.modules` indicates the current +ABI version, which is increased whenever a C++ API changes. Node.js will refuse +to load modules that were compiled against a different module ABI version. ```js console.log(process.versions); From d3628d9e47ad3bfe7a9fa63640f8d414f0cd4d3b Mon Sep 17 00:00:00 2001 From: Vse Mozhet Byt Date: Sat, 3 Dec 2016 07:36:19 +0200 Subject: [PATCH 011/291] doc: modernize child_process example code 1. equal => strictEqual. 2. let => const for the variable that is not reassigned. 3. fix spaces. 4. stringify erroneous raw buffer outputs. 5. fix a typo. PR-URL: https://github.com/nodejs/node/pull/10102 Reviewed-By: Sam Roberts Reviewed-By: Sakthipriyan Vairamani --- doc/api/child_process.md | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/doc/api/child_process.md b/doc/api/child_process.md index 0147242c5583a0..f735376134025a 100644 --- a/doc/api/child_process.md +++ b/doc/api/child_process.md @@ -91,11 +91,11 @@ const spawn = require('child_process').spawn; const bat = spawn('cmd.exe', ['/c', 'my.bat']); bat.stdout.on('data', (data) => { - console.log(data); + console.log(data.toString()); }); bat.stderr.on('data', (data) => { - console.log(data); + console.log(data.toString()); }); bat.on('exit', (code) => { @@ -113,7 +113,7 @@ exec('my.bat', (err, stdout, stderr) => { }); // Script with spaces in the filename: -const bat = spawn('"my script.cmd"', ['a', 'b'], { shell:true }); +const bat = spawn('"my script.cmd"', ['a', 'b'], { shell: true }); // or: exec('"my script.cmd" a b', (err, stdout, stderr) => { // ... @@ -391,7 +391,7 @@ ps.on('close', (code) => { }); grep.stdout.on('data', (data) => { - console.log(`${data}`); + console.log(data.toString()); }); grep.stderr.on('data', (data) => { @@ -475,8 +475,8 @@ const out = fs.openSync('./out.log', 'a'); const err = fs.openSync('./out.log', 'a'); const child = spawn('prg', [], { - detached: true, - stdio: [ 'ignore', out, err ] + detached: true, + stdio: [ 'ignore', out, err ] }); child.unref(); @@ -876,7 +876,7 @@ as in this example: 'use strict'; const spawn = require('child_process').spawn; -let child = spawn('sh', ['-c', +const child = spawn('sh', ['-c', `node -e "setInterval(() => { console.log(process.pid, 'is alive') }, 500);"` @@ -1123,21 +1123,21 @@ const fs = require('fs'); const child_process = require('child_process'); const child = child_process.spawn('ls', { - stdio: [ - 0, // Use parents stdin for child - 'pipe', // Pipe child's stdout to parent - fs.openSync('err.out', 'w') // Direct child's stderr to a file - ] + stdio: [ + 0, // Use parent's stdin for child + 'pipe', // Pipe child's stdout to parent + fs.openSync('err.out', 'w') // Direct child's stderr to a file + ] }); -assert.equal(child.stdio[0], null); -assert.equal(child.stdio[0], child.stdin); +assert.strictEqual(child.stdio[0], null); +assert.strictEqual(child.stdio[0], child.stdin); assert(child.stdout); -assert.equal(child.stdio[1], child.stdout); +assert.strictEqual(child.stdio[1], child.stdout); -assert.equal(child.stdio[2], null); -assert.equal(child.stdio[2], child.stderr); +assert.strictEqual(child.stdio[2], null); +assert.strictEqual(child.stdio[2], child.stderr); ``` ### child.stdout From b70dde0050ad5742c21cdd6d8be9435153ee5d0a Mon Sep 17 00:00:00 2001 From: Sam Roberts Date: Fri, 30 Dec 2016 09:14:10 -0800 Subject: [PATCH 012/291] doc: new TLSSocket has no secure context options Unlike all the other tls APIs, if any secure context configuration is required, the caller is responsible for creating the context. Corrects a doc regression introduced in caa7fa982affddcc. PR-URL: https://github.com/nodejs/node/pull/10545 Reviewed-By: Benjamin Gruenbaum Reviewed-By: James M Snell Reviewed-By: Michael Dawson Reviewed-By: Fedor Indutny Reviewed-By: Anna Henningsen --- doc/api/tls.md | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/doc/api/tls.md b/doc/api/tls.md index c33174f250479a..377bfd3dd7bb0b 100644 --- a/doc/api/tls.md +++ b/doc/api/tls.md @@ -483,12 +483,8 @@ added: v0.11.4 will be emitted on the socket before establishing a secure communication * `secureContext`: Optional TLS context object created with [`tls.createSecureContext()`][]. If a `secureContext` is _not_ provided, one - will be created by passing the entire `options` object to - `tls.createSecureContext()`. *Note*: In effect, all - [`tls.createSecureContext()`][] options can be provided, but they will be - _completely ignored_ unless the `secureContext` option is missing. - * ...: Optional [`tls.createSecureContext()`][] options can be provided, see - the `secureContext` option for more information. + will be created by calling [`tls.createSecureContext()`][] with no options. + Construct a new `tls.TLSSocket` object from an existing TCP socket. ### Event: 'OCSPResponse' From f81bd48818dac8d0da2b183ca4aa9fef2cdc84c7 Mon Sep 17 00:00:00 2001 From: Gibson Fahnestock Date: Fri, 6 Jan 2017 22:46:39 +0000 Subject: [PATCH 013/291] doc: document use of Refs: for references Standardise on Refs: PR-URL: https://github.com/nodejs/node/pull/10670 Reviewed-By: James M Snell Reviewed-By: Yorkie Liu Reviewed-By: Luigi Pinca Reviewed-By: Joyee Cheung Reviewed-By: Sam Roberts --- COLLABORATOR_GUIDE.md | 1 + CONTRIBUTING.md | 5 ++++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/COLLABORATOR_GUIDE.md b/COLLABORATOR_GUIDE.md index 32533304fecc67..b80e1d5db02f7d 100644 --- a/COLLABORATOR_GUIDE.md +++ b/COLLABORATOR_GUIDE.md @@ -120,6 +120,7 @@ information regarding the change process: for an issue, and/or the hash and commit message if the commit fixes a bug in a previous commit. Multiple `Fixes:` lines may be added if appropriate. +- A `Refs:` line referencing a URL for any relevant background. - A `Reviewed-By: Name ` line for yourself and any other Collaborators who have reviewed the change. - Useful for @mentions / contact list if something goes wrong in the PR. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 6d419aa4954fde..c60eeb1c6e3040 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -136,10 +136,13 @@ Check the output of `git log --oneline files_that_you_changed` to find out what subsystem (or subsystems) your changes touch. If your patch fixes an open issue, you can add a reference to it at the end -of the log. Use the `Fixes:` prefix and the full issue URL. For example: +of the log. Use the `Fixes:` prefix and the full issue URL. For other references +use `Refs:`. For example: ```txt Fixes: https://github.com/nodejs/node/issues/1337 +Refs: http://eslint.org/docs/rules/space-in-parens.html +Refs: https://github.com/nodejs/node/pull/3615 ``` ### Step 4: Rebase From 736a7f3dd3e52591b15b4644508c1e8663d0ab07 Mon Sep 17 00:00:00 2001 From: Lukasz Gasior Date: Fri, 6 Jan 2017 22:02:16 +0100 Subject: [PATCH 014/291] doc: update BUILDING.md Added a note about Visual Studio 2015 feature which should be installed for building Node.js source code. PR-URL: https://github.com/nodejs/node/pull/10669 Reviewed-By: Gibson Fahnestock Reviewed-By: James M Snell Reviewed-By: Bartosz Sosnowski Reviewed-By: Myles Borins --- BUILDING.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/BUILDING.md b/BUILDING.md index b98bb75d79b656..03a18ef3baf9eb 100644 --- a/BUILDING.md +++ b/BUILDING.md @@ -109,7 +109,8 @@ Prerequisites: * One of: * [Visual C++ Build Tools](http://landinghub.visualstudio.com/visual-cpp-build-tools) * [Visual Studio 2015 Update 3](https://www.visualstudio.com/), all editions - including the Community edition. + including the Community edition (remember to select + "Common Tools for Visual C++ 2015" feature during installation). * Basic Unix tools required for some tests, [Git for Windows](http://git-scm.com/download/win) includes Git Bash and tools which can be included in the global `PATH`. From 8314d9ee73e6c66606e3f47dbedf7c07e0862b4c Mon Sep 17 00:00:00 2001 From: "Sakthipriyan Vairamani (thefourtheye)" Date: Fri, 23 Dec 2016 16:23:28 +0530 Subject: [PATCH 015/291] doc: killSignal option accepts integer values `killSignal` option accepts the signal name or signal number as well. PR-URL: https://github.com/nodejs/node/pull/10424 Reviewed-By: Julian Duque Reviewed-By: James M Snell Reviewed-By: Sam Roberts --- doc/api/child_process.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/doc/api/child_process.md b/doc/api/child_process.md index f735376134025a..c541837b91e302 100644 --- a/doc/api/child_process.md +++ b/doc/api/child_process.md @@ -137,7 +137,7 @@ added: v0.1.90 * `timeout` {Number} (Default: `0`) * [`maxBuffer`][] {Number} largest amount of data (in bytes) allowed on stdout or stderr - if exceeded child process is killed (Default: `200*1024`) - * `killSignal` {String} (Default: `'SIGTERM'`) + * `killSignal` {String|Integer} (Default: `'SIGTERM'`) * `uid` {Number} Sets the user identity of the process. (See setuid(2).) * `gid` {Number} Sets the group identity of the process. (See setgid(2).) * `callback` {Function} called with the output when process terminates @@ -214,7 +214,7 @@ added: v0.1.91 * `timeout` {Number} (Default: `0`) * [`maxBuffer`][] {Number} largest amount of data (in bytes) allowed on stdout or stderr - if exceeded child process is killed (Default: `200*1024`) - * `killSignal` {String} (Default: `'SIGTERM'`) + * `killSignal` {String|Integer} (Default: `'SIGTERM'`) * `uid` {Number} Sets the user identity of the process. (See setuid(2).) * `gid` {Number} Sets the group identity of the process. (See setgid(2).) * `callback` {Function} called with the output when process terminates @@ -591,8 +591,8 @@ added: v0.11.12 * `gid` {Number} Sets the group identity of the process. (See setgid(2).) * `timeout` {Number} In milliseconds the maximum amount of time the process is allowed to run. (Default: `undefined`) - * `killSignal` {String} The signal value to be used when the spawned process - will be killed. (Default: `'SIGTERM'`) + * `killSignal` {String|Integer} The signal value to be used when the spawned + process will be killed. (Default: `'SIGTERM'`) * [`maxBuffer`][] {Number} largest amount of data (in bytes) allowed on stdout or stderr - if exceeded child process is killed * `encoding` {String} The encoding used for all stdio inputs and outputs. (Default: `'buffer'`) @@ -633,8 +633,8 @@ added: v0.11.12 * `gid` {Number} Sets the group identity of the process. (See setgid(2).) * `timeout` {Number} In milliseconds the maximum amount of time the process is allowed to run. (Default: `undefined`) - * `killSignal` {String} The signal value to be used when the spawned process - will be killed. (Default: `'SIGTERM'`) + * `killSignal` {String|Integer} The signal value to be used when the spawned + process will be killed. (Default: `'SIGTERM'`) * [`maxBuffer`][] {Number} largest amount of data (in bytes) allowed on stdout or stderr - if exceeded child process is killed * `encoding` {String} The encoding used for all stdio inputs and outputs. @@ -675,8 +675,8 @@ added: v0.11.12 * `gid` {Number} Sets the group identity of the process. (See setgid(2).) * `timeout` {Number} In milliseconds the maximum amount of time the process is allowed to run. (Default: `undefined`) - * `killSignal` {String} The signal value to be used when the spawned process - will be killed. (Default: `'SIGTERM'`) + * `killSignal` {String|Integer} The signal value to be used when the spawned + process will be killed. (Default: `'SIGTERM'`) * [`maxBuffer`][] {Number} largest amount of data (in bytes) allowed on stdout or stderr - if exceeded child process is killed * `encoding` {String} The encoding used for all stdio inputs and outputs. From 3f1775707e669aa757c53e2aaaf8216b92e6ad63 Mon Sep 17 00:00:00 2001 From: Jonathan Boarman Date: Sun, 4 Dec 2016 06:43:43 -0600 Subject: [PATCH 016/291] doc: correct vcbuild options for windows testing Corrected parameter for running tests on Windows. Without the corrected parameters, Windows users encounter an error about failing to sign the build, "Failed to sign exe", which can be discouraging to new Windows community members. PR-URL: https://github.com/nodejs/node/pull/10686 Reviewed-By: James M Snell Reviewed-By: Bartosz Sosnowski --- BUILDING.md | 8 ++++---- CONTRIBUTING.md | 6 +++--- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/BUILDING.md b/BUILDING.md index 03a18ef3baf9eb..75ef93f8c73a13 100644 --- a/BUILDING.md +++ b/BUILDING.md @@ -122,7 +122,7 @@ Prerequisites: To run the tests: ```console -> .\vcbuild test +> .\vcbuild nosign test ``` To test if Node.js was built correctly: @@ -180,7 +180,7 @@ $ ./configure --with-intl=full-icu --download=all ##### Windows: ```console -> .\vcbuild full-icu download-all +> .\vcbuild nosign full-icu download-all ``` #### Building without Intl support @@ -197,7 +197,7 @@ $ ./configure --without-intl ##### Windows: ```console -> .\vcbuild without-intl +> .\vcbuild nosign without-intl ``` #### Use existing installed ICU (Unix / OS X only): @@ -240,7 +240,7 @@ First unpack latest ICU to `deps/icu` as `deps/icu` (You'll have: `deps/icu/source/...`) ```console -> .\vcbuild full-icu +> .\vcbuild nosign full-icu ``` ## Building Node.js with FIPS-compliant OpenSSL diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c60eeb1c6e3040..736a9542c42baf 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -170,7 +170,7 @@ $ ./configure && make -j4 test Windows: ```text -> vcbuild test + .\vcbuild nosign test ``` (See the [BUILDING.md](./BUILDING.md) for more details.) @@ -178,11 +178,11 @@ Windows: Make sure the linter is happy and that all tests pass. Please, do not submit patches that fail either check. -Running `make test`/`vcbuild test` will run the linter as well unless one or +Running `make test`/`.\vcbuild nosign test` will run the linter as well unless one or more tests fail. If you want to run the linter without running tests, use -`make lint`/`vcbuild jslint`. +`make lint`/`.\vcbuild nosign jslint`. If you are updating tests and just want to run a single test to check it, you can use this syntax to run it exactly as the test harness would: From 9c89b2f704022c41f208e5ef7da5321251ffe059 Mon Sep 17 00:00:00 2001 From: Evan Lucas Date: Tue, 10 Jan 2017 06:13:00 -0600 Subject: [PATCH 017/291] doc: update LTS info for current releases The COLLABORATOR_GUIDE was still listing v0.10 and v0.12 as LTS when they are EOL now. PR-URL: https://github.com/nodejs/node/pull/10720 Reviewed-By: Colin Ihrig Reviewed-By: Myles Borins Reviewed-By: James M Snell --- COLLABORATOR_GUIDE.md | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/COLLABORATOR_GUIDE.md b/COLLABORATOR_GUIDE.md index b80e1d5db02f7d..7ac8f49ee09ff0 100644 --- a/COLLABORATOR_GUIDE.md +++ b/COLLABORATOR_GUIDE.md @@ -319,9 +319,8 @@ CTC for further discussion. #### How are LTS Branches Managed? -There are currently three LTS branches: `v4.x`, `v0.10`, and `v0.12`. Each -of these is paired with a "staging" branch: `v4.x-staging`, `v0.10-staging`, -and `v0.12-staging`. +There are currently two LTS branches: `v6.x` and `v4.x`. Each of these is paired +with a "staging" branch: `v6.x-staging` and `v4.x-staging`. As commits land in `master`, they are cherry-picked back to each staging branch as appropriate. If the commit applies only to the LTS branch, the @@ -342,18 +341,14 @@ please feel free to include that information in the PR thread. Several LTS related issue and PR labels have been provided: +* `lts-watch-v6.x` - tells the LTS WG that the issue/PR needs to be considered + for landing in the `v6.x-staging` branch. * `lts-watch-v4.x` - tells the LTS WG that the issue/PR needs to be considered for landing in the `v4.x-staging` branch. -* `lts-watch-v0.10` - tells the LTS WG that the issue/PR needs to be considered - for landing in the `v0.10-staging` branch. -* `lts-watch-v0.12` - tells the LTS WG that the issue/PR needs to be considered - for landing in the `v0.12-staging` branch. +* `land-on-v6.x` - tells the release team that the commit should be landed + in a future v6.x release * `land-on-v4.x` - tells the release team that the commit should be landed in a future v4.x release -* `land-on-v0.10` - tells the release team that the commit should be landed - in a future v0.10 release -* `land-on-v0.12` - tells the release team that the commit should be landed - in a future v0.12 release Any collaborator can attach these labels to any PR/issue. As commits are landed into the staging branches, the `lts-watch-` label will be removed. From bf95b074cddf580d7269740a9c7c833a3b603a95 Mon Sep 17 00:00:00 2001 From: Myles Borins Date: Fri, 6 Jan 2017 14:06:45 -0500 Subject: [PATCH 018/291] doc: "s/git apply/git am -3" in V8 guide git apply does not preserve the original commit message. These updated instructions offer a simpler flow for backporting. PR-URL: https://github.com/nodejs/node/pull/10665 Reviewed-By: James M Snell Reviewed-By: Gibson Fahnestock Reviewed-By: Michal Zasso --- doc/guides/maintaining-V8.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc/guides/maintaining-V8.md b/doc/guides/maintaining-V8.md index 19ee61fe20c5d7..4bfed3790f5185 100644 --- a/doc/guides/maintaining-V8.md +++ b/doc/guides/maintaining-V8.md @@ -177,8 +177,8 @@ https://crbug.com/v8/5199. From the bug we can see that it was merged by V8 into `v6.x` uses V8 5.1, the fix needed to cherry-picked. To cherry-pick, here's an example workflow: -* Download and apply the commit linked-to in the issue (in this case a51f429). `curl -L https://github.com/v8/v8/commit/a51f429.patch | git apply --directory=deps/v8`. If the branches have diverged significantly, this may not apply cleanly. It may help to try to cherry-pick the merge to the oldest branch that was done upstream in V8. In this example, this would be the patch from the merge to 5.2. The hope is that this would be closer to the V8 5.1, and has a better chance of applying cleanly. If you're stuck, feel free to ping @ofrobots for help. -* Modify the commit message to match the format we use for V8 backports. You may want to add extra description if necessary to indicate the impact of the fix on Node.js. In this case the original issue was descriptive enough. Example: +* Download and apply the commit linked-to in the issue (in this case a51f429). `curl -L https://github.com/v8/v8/commit/a51f429.patch | git am -3 --directory=deps/v8`. If the branches have diverged significantly, this may not apply cleanly. It may help to try to cherry-pick the merge to the oldest branch that was done upstream in V8. In this example, this would be the patch from the merge to 5.2. The hope is that this would be closer to the V8 5.1, and has a better chance of applying cleanly. If you're stuck, feel free to ping @ofrobots for help. +* Modify the commit message to match the format we use for V8 backports and replace yourself as the author. `git commit --amend --reset-author`. You may want to add extra description if necessary to indicate the impact of the fix on Node.js. In this case the original issue was descriptive enough. Example: ``` deps: cherry-pick a51f429 from V8 upstream From b73e98bf48fa218e94113326965f7ad98ea38cc9 Mon Sep 17 00:00:00 2001 From: Johannes Rieken Date: Mon, 9 Jan 2017 16:54:07 +0100 Subject: [PATCH 019/291] doc: fix missing negation in stream.md Changing `..can result in expected` to `..can result in unexpected` Fixes: https://github.com/nodejs/node/issues/10710 PR-URL: https://github.com/nodejs/node/pull/10712 Reviewed-By: Colin Ihrig Reviewed-By: James M Snell Reviewed-By: Luigi Pinca --- doc/api/stream.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/api/stream.md b/doc/api/stream.md index 291cda735aee3d..98026f6a394eb2 100644 --- a/doc/api/stream.md +++ b/doc/api/stream.md @@ -1306,7 +1306,7 @@ It is recommended that errors occurring during the processing of the `writable._write()` and `writable._writev()` methods are reported by invoking the callback and passing the error as the first argument. This will cause an `'error'` event to be emitted by the Writable. Throwing an Error from within -`writable._write()` can result in expected and inconsistent behavior depending +`writable._write()` can result in unexpected and inconsistent behavior depending on how the stream is being used. Using the callback ensures consistent and predictable handling of errors. From ec226a2a3b8e4fa52ae8b2cc51fc17d3ae89b7a3 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Mon, 2 Jan 2017 20:00:59 -0800 Subject: [PATCH 020/291] doc: add test naming information to guide The guide for writing tests is missing information on how tests are named. This adds that information. There is also some copy-editing done on the first paragraph of the guide. PR-URL: https://github.com/nodejs/node/pull/10584 Reviewed-By: Gibson Fahnestock Reviewed-By: Italo A. Casas Reviewed-By: Colin Ihrig Reviewed-By: James M Snell Reviewed-By: Sakthipriyan Vairamani Reviewed-By: Sam Roberts --- doc/guides/writing-tests.md | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/doc/guides/writing-tests.md b/doc/guides/writing-tests.md index d628e3f6f5873c..6c2441fa0f012f 100644 --- a/doc/guides/writing-tests.md +++ b/doc/guides/writing-tests.md @@ -2,13 +2,12 @@ ## What is a test? -A test must be a node script that exercises a specific functionality provided -by node and checks that it behaves as expected. It should exit with code `0` on success, -otherwise it will fail. A test will fail if: +Most tests in Node.js core are JavaScript programs that exercise a functionality +provided by Node.js and check that it behaves as expected. Tests should exit +with code `0` on success. A test will fail if: - It exits by setting `process.exitCode` to a non-zero number. - - This is most often done by having an assertion throw an uncaught - Error. + - This is usually done by having an assertion throw an uncaught Error. - Occasionally, using `process.exit(code)` may be appropriate. - It never exits. In this case, the test runner will terminate the test because it sets a maximum time limit. @@ -205,3 +204,15 @@ require('../common'); const assert = require('assert'); const freelist = require('internal/freelist'); ``` + +## Naming Test Files + +Test files are named using kebab casing. The first component of the name is +`test`. The second is the module or subsystem being tested. The third is usually +the method or event name being tested. Subsequent components of the name add +more information about what is being tested. + +For example, a test for the `beforeExit` event on the `process` object might be +named `test-process-before-exit.js`. If the test specifically checked that arrow +functions worked correctly with the `beforeExit` event, then it might be named +`test-process-before-exit-arrow-functions.js`. From 238466bcf08f9771cc4f89905b05292e0844f252 Mon Sep 17 00:00:00 2001 From: Matteo Collina Date: Thu, 5 Jan 2017 11:28:46 +0100 Subject: [PATCH 021/291] doc: handle backpressure when write() return false The doc specified that writable.write() was advisory only. However, ignoring that value might lead to memory leaks. This PR specifies that behavior. Moreover, it adds an example on how to listen for the 'drain' event correctly. See: https://github.com/nodejs/node/commit/f347dad0b7b1787092cca88789b77eb3def2d319 PR-URL: https://github.com/nodejs/node/pull/10631 Reviewed-By: Colin Ihrig Reviewed-By: Sam Roberts Reviewed-By: Evan Lucas Reviewed-By: James M Snell Reviewed-By: Joyee Cheung --- doc/api/stream.md | 43 ++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 40 insertions(+), 3 deletions(-) diff --git a/doc/api/stream.md b/doc/api/stream.md index 98026f6a394eb2..6732435cb60e93 100644 --- a/doc/api/stream.md +++ b/doc/api/stream.md @@ -443,9 +443,46 @@ first argument. To reliably detect write errors, add a listener for the The return value is `true` if the internal buffer does not exceed `highWaterMark` configured when the stream was created after admitting `chunk`. If `false` is returned, further attempts to write data to the stream should -stop until the [`'drain'`][] event is emitted. However, the `false` return -value is only advisory and the writable stream will unconditionally accept and -buffer `chunk` even if it has not not been allowed to drain. +stop until the [`'drain'`][] event is emitted. + +While a stream is not draining, calls to `write()` will buffer `chunk`, and +return false. Once all currently buffered chunks are drained (accepted for +delivery by the operating system), the `'drain'` event will be emitted. +It is recommended that once write() returns false, no more chunks be written +until the `'drain'` event is emitted. While calling `write()` on a stream that +is not draining is allowed, Node.js will buffer all written chunks until +maximum memory usage occurs, at which point it will abort unconditionally. +Even before it aborts, high memory usage will cause poor garbage collector +performance and high RSS (which is not typically released back to the system, +even after the memory is no longer required). Since TCP sockets may never +drain if the remote peer does not read the data, writing a socket that is +not draining may lead to a remotely exploitable vulnerability. + +Writing data while the stream is not draining is particularly +problematic for a [Transform][], because the `Transform` streams are paused +by default until they are piped or an `'data'` or `'readable'` event handler +is added. + +If the data to be written can be generated or fetched on demand, it is +recommended to encapsulate the logic into a [Readable][] and use +[`stream.pipe()`][]. However, if calling `write()` is preferred, it is +possible to respect backpressure and avoid memory issues using the +the [`'drain'`][] event: + +```js +function write (data, cb) { + if (!stream.write(data)) { + stream.once('drain', cb) + } else { + process.nextTick(cb) + } +} + +// Wait for cb to be called before doing any other write. +write('hello', () => { + console.log('write completed, do more writes now') +}) +``` A Writable stream in object mode will always ignore the `encoding` argument. From 66b34eac2fe83f2be6fc980c1f1216cff3d2615e Mon Sep 17 00:00:00 2001 From: Sam Roberts Date: Wed, 4 Jan 2017 10:41:54 -0800 Subject: [PATCH 022/291] doc: sort require statements in tests PR-URL: https://github.com/nodejs/node/pull/10616 Reviewed-By: James M Snell Reviewed-By: Michael Dawson Reviewed-By: Gibson Fahnestock Reviewed-By: Colin Ihrig Reviewed-By: Prince John Wesley --- doc/guides/writing-tests.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/doc/guides/writing-tests.md b/doc/guides/writing-tests.md index 6c2441fa0f012f..c76d600e6ef49e 100644 --- a/doc/guides/writing-tests.md +++ b/doc/guides/writing-tests.md @@ -90,6 +90,9 @@ These modules are required for the test to run. Except for special cases, these modules should only include core modules. The `assert` module is used by most of the tests to check that the assumptions for the test are met. +Note that require statements are sorted, in +[ASCII](http://man7.org/linux/man-pages/man7/ascii.7.html) order (digits, upper +case, `_`, lower case). **Lines 10-21** From 56ea7eb9a7165b64413a7b9722aee434836daece Mon Sep 17 00:00:00 2001 From: Anna Henningsen Date: Fri, 6 Jan 2017 02:03:39 +0100 Subject: [PATCH 023/291] doc: mention cc-ing nodejs/url team for reviews Add the nodejs/url github team to the table of people to /cc for reviews on the WHATWG URL code. PR-URL: https://github.com/nodejs/node/pull/10652 Reviewed-By: James M Snell Reviewed-By: Joyee Cheung Reviewed-By: Jeremiah Senkpiel Reviewed-By: Gibson Fahnestock --- doc/onboarding-extras.md | 1 + 1 file changed, 1 insertion(+) diff --git a/doc/onboarding-extras.md b/doc/onboarding-extras.md index 9e1a4a7ed7b14b..a0fa985a92b35a 100644 --- a/doc/onboarding-extras.md +++ b/doc/onboarding-extras.md @@ -13,6 +13,7 @@ | `lib/{crypto,tls,https}` | @nodejs/crypto | | `lib/domains` | @misterdjules | | `lib/fs`, `src/{fs|file}` | @nodejs/fs | +| `lib/internal/url`, `src/node_url` | @nodejs/url | | `lib/{_}http{*}` | @nodejs/http | | `lib/net` | @bnoordhuis, @indutny, @nodejs/streams | | `lib/{_}stream{s|*}` | @nodejs/streams | From 9b73a8524f04375ad0a85c575e7bfaa559f382e9 Mon Sep 17 00:00:00 2001 From: Alexey Orlenko Date: Mon, 9 Jan 2017 17:05:03 +0200 Subject: [PATCH 024/291] doc: fix misleading language in vm docs The note following the http.Server example in the vm documentation contains misleading language. This commit removes the incorrect reference to threads. Fixes: https://github.com/nodejs/node/issues/10697 PR-URL: https://github.com/nodejs/node/pull/10708 Reviewed-By: Brian White Reviewed-By: James M Snell --- doc/api/vm.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/doc/api/vm.md b/doc/api/vm.md index 8c49cfb7c31f24..cb0e2fbb76e25d 100644 --- a/doc/api/vm.md +++ b/doc/api/vm.md @@ -439,9 +439,9 @@ let code = vm.runInThisContext(code)(require); ``` -*Note*: The `require()` in the above case shares the state with context it is -passed from. This may introduce risks when untrusted code is executed, e.g. -altering objects from the calling thread's context in unwanted ways. +*Note*: The `require()` in the above case shares the state with the context it +is passed from. This may introduce risks when untrusted code is executed, e.g. +altering objects in the context in unwanted ways. ## What does it mean to "contextify" an object? From 23edfe00b3bfb2d464c25dd4bd4c24a6f56849ad Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Mon, 2 Jan 2017 20:27:58 -0800 Subject: [PATCH 025/291] doc: edit writing-tests.md * Remove passive voice * Remove unneeded modifiers * Minor comma change PR-URL: https://github.com/nodejs/node/pull/10585 Reviewed-By: Gibson Fahnestock Reviewed-By: Italo A. Casas --- doc/guides/writing-tests.md | 61 +++++++++++++++++++------------------ 1 file changed, 31 insertions(+), 30 deletions(-) diff --git a/doc/guides/writing-tests.md b/doc/guides/writing-tests.md index c76d600e6ef49e..c587eb3d8e9ccd 100644 --- a/doc/guides/writing-tests.md +++ b/doc/guides/writing-tests.md @@ -12,15 +12,15 @@ with code `0` on success. A test will fail if: - It never exits. In this case, the test runner will terminate the test because it sets a maximum time limit. -Tests can be added for multiple reasons: +Add tests when: -- When adding new functionality. -- When fixing regressions and bugs. -- When expanding test coverage. +- Adding new functionality. +- Fixing regressions and bugs. +- Expanding test coverage. ## Test structure -Let's analyze this very basic test from the Node.js test suite: +Let's analyze this basic test from the Node.js test suite: ```javascript 1 'use strict'; @@ -59,11 +59,12 @@ the nature of the test requires that the test run without it. The second line loads the `common` module. The `common` module is a helper module that provides useful tools for the tests. -Even if no functions or other properties exported by `common` are used in a -test, the `common` module should still be included. This is because the `common` -module includes code that will cause tests to fail if variables are leaked into -the global space. In situations where no functions or other properties exported -by `common` are used, it can be included without assigning it to an identifier: +Even if a test uses no functions or other properties exported by `common`, +the test should still include the `common` module before any other modules. This +is because the `common` module includes code that will cause a test to fail if +the test leaks variables into the global space. In situations where a test uses +no functions or other properties exported by `common`, include it without +assigning it to an identifier: ```javascript require('../common'); @@ -86,28 +87,28 @@ const http = require('http'); const assert = require('assert'); ``` -These modules are required for the test to run. Except for special cases, these -modules should only include core modules. -The `assert` module is used by most of the tests to check that the assumptions -for the test are met. -Note that require statements are sorted, in +The test checks functionality in the `http` module. + +Most tests use the `assert` module to confirm expectations of the test. + +The require statements are sorted in [ASCII](http://man7.org/linux/man-pages/man7/ascii.7.html) order (digits, upper case, `_`, lower case). **Lines 10-21** -This is the body of the test. This test is quite simple, it just tests that an +This is the body of the test. This test is simple, it just tests that an HTTP server accepts `non-ASCII` characters in the headers of an incoming request. Interesting things to notice: -- If the test doesn't depend on a specific port number then always use 0 instead - of an arbitrary value, as it allows tests to be run in parallel safely, as the - operating system will assign a random port. If the test requires a specific - port, for example if the test checks that assigning a specific port works as - expected, then it is ok to assign a specific port number. +- If the test doesn't depend on a specific port number, then always use 0 + instead of an arbitrary value, as it allows tests to run in parallel safely, + as the operating system will assign a random port. If the test requires a + specific port, for example if the test checks that assigning a specific port + works as expected, then it is ok to assign a specific port number. - The use of `common.mustCall` to check that some callbacks/listeners are called. -- The HTTP server is closed once all the checks have run. This way, the test can +- The HTTP server closes once all the checks have run. This way, the test can exit gracefully. Remember that for a test to succeed, it must exit with a status code of 0. @@ -115,20 +116,20 @@ request. Interesting things to notice: ### Timers -The use of timers is discouraged, unless timers are being tested. There are -multiple reasons for this. Mainly, they are a source of flakiness. For a thorough +Avoid timers unless the test is specifically testing timers. There are multiple +reasons for this. Mainly, they are a source of flakiness. For a thorough explanation go [here](https://github.com/nodejs/testing/issues/27). -In the event a timer is needed, it's recommended using the -`common.platformTimeout()` method, that allows setting specific timeouts +In the event a test needs a timer, consider using the +`common.platformTimeout()` method. It allows setting specific timeouts depending on the platform. For example: ```javascript const timer = setTimeout(fail, common.platformTimeout(4000)); ``` -will create a 4-seconds timeout, except for some platforms where the delay will -be multiplied for some factor. +will create a 4-second timeout on most platforms but a longer timeout on slower +platforms. ### The *common* API @@ -193,9 +194,9 @@ var server = http.createServer(common.mustCall(function(req, res) { ### Flags Some tests will require running Node.js with specific command line flags set. To -accomplish this, a `// Flags: ` comment should be added in the preamble of the +accomplish this, add a `// Flags: ` comment in the preamble of the test followed by the flags. For example, to allow a test to require some of the -`internal/*` modules, the `--expose-internals` flag should be added. +`internal/*` modules, add the `--expose-internals` flag. A test that would require `internal/freelist` could start like this: ```javascript From 6e1a3d1e5763e52bfa31dc70847c16b26af6576d Mon Sep 17 00:00:00 2001 From: Sam Roberts Date: Tue, 20 Dec 2016 14:16:18 -0800 Subject: [PATCH 026/291] doc: use correct tls certificate property name Docs referred to an `issuer` property being optionally present, when it should have referred to the `issuerCertificate` property. PR-URL: https://github.com/nodejs/node/pull/10389 Reviewed-By: James M Snell Reviewed-By: Gibson Fahnestock Reviewed-By: Michael Dawson --- doc/api/tls.md | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/doc/api/tls.md b/doc/api/tls.md index 377bfd3dd7bb0b..64fd343c0449d5 100644 --- a/doc/api/tls.md +++ b/doc/api/tls.md @@ -583,13 +583,16 @@ For Example: `{ type: 'ECDH', name: 'prime256v1', size: 256 }` added: v0.11.4 --> -* `detailed` {boolean} Specify `true` to request that the full certificate - chain with the `issuer` property be returned; `false` to return only the - top certificate without the `issuer` property. +* `detailed` {boolean} Include the full certificate chain if `true`, otherwise + include just the peer's certificate. Returns an object representing the peer's certificate. The returned object has some properties corresponding to the fields of the certificate. +If the full certificate chain was requested, each certificate will include a +`issuerCertificate` property containing an object representing its issuer's +certificate. + For example: ```text @@ -600,15 +603,15 @@ For example: O: 'node.js', OU: 'Test TLS Certificate', CN: 'localhost' }, - issuerInfo: + issuer: { C: 'UK', ST: 'Acknack Ltd', L: 'Rhys Jones', O: 'node.js', OU: 'Test TLS Certificate', CN: 'localhost' }, - issuer: - { ... another certificate ... }, + issuerCertificate: + { ... another certificate, possibly with a .issuerCertificate ... }, raw: < RAW DER buffer >, valid_from: 'Nov 11 09:52:22 2009 GMT', valid_to: 'Nov 6 09:52:22 2029 GMT', @@ -616,8 +619,7 @@ For example: serialNumber: 'B9B0D332A1AA5635' } ``` -If the peer does not provide a certificate, `null` or an empty object will be -returned. +If the peer does not provide a certificate, an empty object will be returned. ### tlsSocket.getProtocol() -* `arrayBuffer` {ArrayBuffer} The `.buffer` property of a [`TypedArray`] or - [`ArrayBuffer`] -* `byteOffset` {Integer} Where to start copying from `arrayBuffer`. **Default:** `0` -* `length` {Integer} How many bytes to copy from `arrayBuffer`. +* `arrayBuffer` {ArrayBuffer} An [`ArrayBuffer`] or the `.buffer` property of a + [`TypedArray`]. +* `byteOffset` {Integer} Index of first byte to expose. **Default:** `0` +* `length` {Integer} Number of bytes to expose. **Default:** `arrayBuffer.length - byteOffset` -When passed a reference to the `.buffer` property of a [`TypedArray`] instance, -the newly created `Buffer` will share the same allocated memory as the -[`TypedArray`]. +This creates a view of the [`ArrayBuffer`] without copying the underlying +memory. For example, when passed a reference to the `.buffer` property of a +[`TypedArray`] instance, the newly created `Buffer` will share the same +allocated memory as the [`TypedArray`]. Example: From 61798d1fa463aa35c94a76c5d2faee134c18dc91 Mon Sep 17 00:00:00 2001 From: Anna Henningsen Date: Fri, 13 Jan 2017 04:02:17 +0100 Subject: [PATCH 030/291] doc: add missing `added:` tag for `zlib.constants` PR-URL: https://github.com/nodejs/node/pull/10826 Reviewed-By: Colin Ihrig Reviewed-By: Luigi Pinca Reviewed-By: James M Snell --- doc/api/zlib.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/doc/api/zlib.md b/doc/api/zlib.md index 73bcf8e0179366..63a22a6d022c14 100644 --- a/doc/api/zlib.md +++ b/doc/api/zlib.md @@ -388,6 +388,9 @@ Reset the compressor/decompressor to factory defaults. Only applicable to the inflate and deflate algorithms. ## zlib.constants + Provides an object enumerating Zlib-related constants. From 049258b062d6a1c721826e5fa268242b7bc97f16 Mon Sep 17 00:00:00 2001 From: Anna Henningsen Date: Fri, 13 Jan 2017 02:43:58 +0100 Subject: [PATCH 031/291] doc: fixup `added` tags in cli.md PR-URL: https://github.com/nodejs/node/pull/10826 Reviewed-By: Colin Ihrig Reviewed-By: Luigi Pinca Reviewed-By: James M Snell --- doc/api/cli.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/doc/api/cli.md b/doc/api/cli.md index d868d70533f5f2..3f51c97b818d8d 100644 --- a/doc/api/cli.md +++ b/doc/api/cli.md @@ -189,7 +189,7 @@ Track heap object allocations for heap snapshots. ### `--prof-process` Process v8 profiler output generated using the v8 option `--prof`. @@ -307,7 +307,7 @@ to an empty string (`""` or `" "`) disables persistent REPL history. ### `NODE_TTY_UNSAFE_ASYNC=1` When set to `1`, writes to `stdout` and `stderr` will be non-blocking and @@ -316,6 +316,9 @@ Setting this will void any guarantee that stdio will not be interleaved or dropped at program exit. **Use of this mode is not recommended.** ### `NODE_EXTRA_CA_CERTS=file` + When set, the well known "root" CAs (like VeriSign) will be extended with the extra certificates in `file`. The file should consist of one or more trusted From c8b0fc6d8bddd6fa5f9f4df6bc762ecf72d13a26 Mon Sep 17 00:00:00 2001 From: Anna Henningsen Date: Fri, 13 Jan 2017 02:59:05 +0100 Subject: [PATCH 032/291] doc: remove duplicate PR link from changelog This contained a duplicate link to the PR for a notable change, presumably because that PR was composed of 2 separate commits. PR-URL: https://github.com/nodejs/node/pull/10827 Reviewed-By: Luigi Pinca Reviewed-By: James M Snell --- doc/changelogs/CHANGELOG_V7.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/changelogs/CHANGELOG_V7.md b/doc/changelogs/CHANGELOG_V7.md index 1f476b8eae4649..5baa4458ab1d69 100644 --- a/doc/changelogs/CHANGELOG_V7.md +++ b/doc/changelogs/CHANGELOG_V7.md @@ -553,7 +553,7 @@ _This is a security release impacting Windows 10 users._ ### Notable changes * **crypto**: The `Decipher` methods `setAuthTag()` and `setAAD` now return `this`. (Kirill Fomichev) [#9398](https://github.com/nodejs/node/pull/9398) -* **dns**: Implemented `{ttl: true}` for `resolve4()` and `resolve6()`. (Ben Noordhuis) [#9296](https://github.com/nodejs/node/pull/9296) & [#9296](https://github.com/nodejs/node/pull/9296) +* **dns**: Implemented `{ttl: true}` for `resolve4()` and `resolve6()`. (Ben Noordhuis) [#9296](https://github.com/nodejs/node/pull/9296) * **libuv**: Upgrade to v1.10.1 (cjihrig) [#9647](https://github.com/nodejs/node/pull/9647) - Fixed a potential buffer overflow when writing data to console on Windows 10. (CVE-2016-9551) * **process**: Added a new `external` property to the data returned by `memoryUsage()`. (Fedor Indutny) [#9587](https://github.com/nodejs/node/pull/9587) From aeaf8877008a01fb8b69c2761bc90bbb09610105 Mon Sep 17 00:00:00 2001 From: Anna Henningsen Date: Fri, 13 Jan 2017 04:00:46 +0100 Subject: [PATCH 033/291] doc: fix markdown escaping in CHANGELOG_V7.md PR-URL: https://github.com/nodejs/node/pull/10827 Reviewed-By: Luigi Pinca Reviewed-By: James M Snell --- doc/changelogs/CHANGELOG_V7.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc/changelogs/CHANGELOG_V7.md b/doc/changelogs/CHANGELOG_V7.md index 5baa4458ab1d69..f10ecdcc9c2b12 100644 --- a/doc/changelogs/CHANGELOG_V7.md +++ b/doc/changelogs/CHANGELOG_V7.md @@ -986,8 +986,8 @@ _This is a security release impacting Windows 10 users._ * [[`0301ce9f55`](https://github.com/nodejs/node/commit/0301ce9f55)] - **src**: move IsolateData out of Environment (Ben Noordhuis) [#7082](https://github.com/nodejs/node/pull/7082) * [[`a3c5567eb4`](https://github.com/nodejs/node/commit/a3c5567eb4)] - **(SEMVER-MAJOR)** **src,win**: use correct exit code in old versions (yorkie) [#8204](https://github.com/nodejs/node/pull/8204) * [[`2f05af4c06`](https://github.com/nodejs/node/commit/2f05af4c06)] - **(SEMVER-MAJOR)** **stream**: improve stream error messages (Italo A. Casas) [#8801](https://github.com/nodejs/node/pull/8801) -* [[`9983af0347`](https://github.com/nodejs/node/commit/9983af0347)] - **(SEMVER-MAJOR)** **stream**: improve unimplemented _write() error (ratikesh9) [#7671](https://github.com/nodejs/node/pull/7671) -* [[`0cd0118334`](https://github.com/nodejs/node/commit/0cd0118334)] - **(SEMVER-MAJOR)** **stream**: 'data' argument on callback of Transform._flush() (Jesús Leganés Combarro "piranna) [#3708](https://github.com/nodejs/node/pull/3708) +* [[`9983af0347`](https://github.com/nodejs/node/commit/9983af0347)] - **(SEMVER-MAJOR)** **stream**: improve unimplemented \_write() error (ratikesh9) [#7671](https://github.com/nodejs/node/pull/7671) +* [[`0cd0118334`](https://github.com/nodejs/node/commit/0cd0118334)] - **(SEMVER-MAJOR)** **stream**: 'data' argument on callback of Transform.\_flush() (Jesús Leganés Combarro "piranna) [#3708](https://github.com/nodejs/node/pull/3708) * [[`a717be87a3`](https://github.com/nodejs/node/commit/a717be87a3)] - **test**: fix flaky test-timers-blocking-callback (Rich Trott) [#9198](https://github.com/nodejs/node/pull/9198) * [[`5ba02bf5db`](https://github.com/nodejs/node/commit/5ba02bf5db)] - **test**: remove arbitrary timer (Rich Trott) [#9197](https://github.com/nodejs/node/pull/9197) * [[`1518cc1e70`](https://github.com/nodejs/node/commit/1518cc1e70)] - **test**: remove duplicate required module (Rich Trott) [#9169](https://github.com/nodejs/node/pull/9169) From daf1bf588bf2c9a4866a9a7b972c104ff5890de7 Mon Sep 17 00:00:00 2001 From: Anna Henningsen Date: Mon, 16 Jan 2017 01:49:16 +0100 Subject: [PATCH 034/291] doc: add links for zlib convenience methods Add links to the engine classes for the zlib single-call convenience methods. PR-URL: https://github.com/nodejs/node/pull/10829 Reviewed-By: Luigi Pinca Reviewed-By: Daniel Bevenius Reviewed-By: Colin Ihrig Reviewed-By: James M Snell --- doc/api/zlib.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/doc/api/zlib.md b/doc/api/zlib.md index 63a22a6d022c14..0d79c084acd565 100644 --- a/doc/api/zlib.md +++ b/doc/api/zlib.md @@ -463,7 +463,7 @@ added: v0.6.0 added: v0.11.12 --> -Compress a Buffer or string with Deflate. +Compress a [Buffer][] or string with [Deflate][]. ### zlib.deflateRaw(buf[, options], callback) -Compress a Buffer or string with DeflateRaw. +Compress a [Buffer][] or string with [DeflateRaw][]. ### zlib.gunzip(buf[, options], callback) -Decompress a Buffer or string with Gunzip. +Decompress a [Buffer][] or string with [Gunzip][]. ### zlib.gzip(buf[, options], callback) -Compress a Buffer or string with Gzip. +Compress a [Buffer][] or string with [Gzip][]. ### zlib.inflate(buf[, options], callback) -Decompress a Buffer or string with Inflate. +Decompress a [Buffer][] or string with [Inflate][]. ### zlib.inflateRaw(buf[, options], callback) -Decompress a Buffer or string with InflateRaw. +Decompress a [Buffer][] or string with [InflateRaw][]. ### zlib.unzip(buf[, options], callback) -Decompress a Buffer or string with Unzip. +Decompress a [Buffer][] or string with [Unzip][]. [`Accept-Encoding`]: https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3 [`Content-Encoding`]: https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11 From 520b1f7853d656cbba9ddb81e6bada47fe5126cc Mon Sep 17 00:00:00 2001 From: Jessica Quynh Tran Date: Thu, 24 Nov 2016 18:35:15 -0500 Subject: [PATCH 035/291] doc: clarifying variables in fs.write() This commit clarifies variables in the Filesystem docs. Prior, the documentation for fs.write() had an ambiguous remark on the parameters of offset and length. Therefore, this commit makes explicit that the length parameter in fs.write() is used to denote the number of bytes, which is a clearer reference for its usage. PR-URL: https://github.com/nodejs/node/pull/9792 Ref: https://github.com/nodejs/node/issues/7868 Reviewed-By: Sam Roberts --- doc/api/fs.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/doc/api/fs.md b/doc/api/fs.md index 4651e08672dda5..638e8261e36af1 100644 --- a/doc/api/fs.md +++ b/doc/api/fs.md @@ -1832,7 +1832,8 @@ added: v0.0.2 Write `buffer` to the file specified by `fd`. -`offset` and `length` determine the part of the buffer to be written. +`offset` determines the part of the buffer to be written, and `length` is +an integer specifying the number of bytes to write. `position` refers to the offset from the beginning of the file where this data should be written. If `typeof position !== 'number'`, the data will be written From 79d8db0fef2e4329427cf2e22a519e511c03de87 Mon Sep 17 00:00:00 2001 From: Adrian Estrada Date: Wed, 18 Jan 2017 16:09:36 -0500 Subject: [PATCH 036/291] doc: add edsadr to collaborators PR-URL: https://github.com/nodejs/node/pull/10883 Reviewed-By: Rich Trott Reviewed-By: Luigi Pinca Reviewed-By: Italo A. Casas Reviewed-By: Santiago Gimeno --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 3bc0bea7020e8b..1d5bfff5576668 100644 --- a/README.md +++ b/README.md @@ -219,6 +219,8 @@ more information about the governance of the Node.js project, see **Claudio Rodriguez** <cjrodr@yahoo.com> * [danbev](https://github.com/danbev) - **Daniel Bevenius** <daniel.bevenius@gmail.com> +* [edsadr](https://github.com/edsadr) - +**Adrian Estrada** <edsadr@gmail.com> * [eljefedelrodeodeljefe](https://github.com/eljefedelrodeodeljefe) - **Robert Jefe Lindstaedt** <robert.lindstaedt@gmail.com> * [estliberitas](https://github.com/estliberitas) - From 3fcf0aed4ad7c666e3d0ee6e13f8ae01dac4af2a Mon Sep 17 00:00:00 2001 From: Anna Henningsen Date: Wed, 18 Jan 2017 12:30:19 +0100 Subject: [PATCH 037/291] doc: mention moderation repo in onboarding doc PR-URL: https://github.com/nodejs/node/pull/10869 Reviewed-By: Luigi Pinca Reviewed-By: James M Snell Reviewed-By: Evan Lucas --- doc/onboarding.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/doc/onboarding.md b/doc/onboarding.md index dbe3dfd569b7ae..14e4572890dbbe 100644 --- a/doc/onboarding.md +++ b/doc/onboarding.md @@ -71,6 +71,10 @@ onboarding session. * [**See "Who to CC in issues"**](./onboarding-extras.md#who-to-cc-in-issues) * will also come more naturally over time + * When a discussion gets heated, you can request that other collaborators keep an eye on it by opening an issue at the private [nodejs/moderation](https://github.com/nodejs/moderation) repository. + * This is a repository to which all members of the `nodejs` GitHub organization (not just Collaborators on Node.js core) have access. Its contents should not be shared externally. + * You can find the full moderation policy [here](https://github.com/nodejs/TSC/blob/master/Moderation-Policy.md). + ## Reviewing PRs * The primary goal is for the codebase to improve. * Secondary (but not far off) is for the person submitting code to succeed. From 4ffcefdc0920ff0da71ace7425e541b74dc88092 Mon Sep 17 00:00:00 2001 From: Timothy Gu Date: Sun, 22 Jan 2017 13:28:57 -0800 Subject: [PATCH 038/291] doc: add TimothyGu to collaborators PR-URL: https://github.com/nodejs/node/pull/10954 Reviewed-By: Rich Trott Reviewed-By: Colin Ihrig --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 1d5bfff5576668..4b92a194e3f3de 100644 --- a/README.md +++ b/README.md @@ -329,6 +329,8 @@ more information about the governance of the Node.js project, see **Glen Keane** <glenkeane.94@gmail.com> * [thlorenz](https://github.com/thlorenz) - **Thorsten Lorenz** <thlorenz@gmx.de> +* [TimothyGu](https://github.com/TimothyGu) - +**Timothy Gu** <timothygu99@gmail.com> * [tunniclm](https://github.com/tunniclm) - **Mike Tunnicliffe** <m.j.tunnicliffe@gmail.com> * [vkurchatkin](https://github.com/vkurchatkin) - From d2896d92a7c8fb8d8ac8702b58b572c8b83dbfab Mon Sep 17 00:00:00 2001 From: Noah Rose Ledesma Date: Sat, 21 Jan 2017 16:19:22 -0800 Subject: [PATCH 039/291] doc: update AUTHORS list to fix name Changed authors listing from `Noah Rose` to `Noah Rose Ledesma`. PR-URL: https://github.com/nodejs/node/pull/10945 Reviewed-By: Rich Trott Reviewed-By: Anna Henningsen Reviewed-By: Luigi Pinca Reviewed-By: James M Snell --- AUTHORS | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AUTHORS b/AUTHORS index f52fb4d2d72c28..6d4c9842d4774c 100644 --- a/AUTHORS +++ b/AUTHORS @@ -935,7 +935,7 @@ Felix Becker Igor Klopov Tsarevich Dmitry Ojas Shirekar -Noah Rose +Noah Rose Ledesma Rafael Cepeda Chinedu Francis Nwafili Braydon Fuller From 3177d6557a19c9d9f8fd474fbf6a894822d40ae4 Mon Sep 17 00:00:00 2001 From: Evan Lucas Date: Thu, 19 Jan 2017 05:56:43 -0600 Subject: [PATCH 040/291] doc: move topics/guides to website This commit removes the topics and guides that the documentation working group has proposed added to the website. We want them to have more visibility and believe that moving them to the website does that. Ref: https://github.com/nodejs/nodejs.org/pull/1105 Fixes: https://github.com/nodejs/node/issues/10792 PR-URL: https://github.com/nodejs/node/pull/10896 Reviewed-By: Gibson Fahnestock Reviewed-By: Luigi Pinca Reviewed-By: Sakthipriyan Vairamani Reviewed-By: Colin Ihrig Reviewed-By: Stephen Belanger Reviewed-By: James M Snell Reviewed-By: Sam Roberts --- doc/guides/timers-in-node.md | 192 ------- doc/topics/blocking-vs-non-blocking.md | 143 ------ doc/topics/domain-postmortem.md | 301 ----------- doc/topics/domain-resource-cleanup-example.js | 136 ----- doc/topics/event-loop-timers-and-nexttick.md | 486 ------------------ 5 files changed, 1258 deletions(-) delete mode 100644 doc/guides/timers-in-node.md delete mode 100644 doc/topics/blocking-vs-non-blocking.md delete mode 100644 doc/topics/domain-postmortem.md delete mode 100644 doc/topics/domain-resource-cleanup-example.js delete mode 100644 doc/topics/event-loop-timers-and-nexttick.md diff --git a/doc/guides/timers-in-node.md b/doc/guides/timers-in-node.md deleted file mode 100644 index 818cc793437cad..00000000000000 --- a/doc/guides/timers-in-node.md +++ /dev/null @@ -1,192 +0,0 @@ ---- -title: Timers in Node.js -layout: docs.hbs ---- - -# Timers in Node.js and beyond - -The Timers module in Node.js contains functions that execute code after a set -period of time. Timers do not need to be imported via `require()`, since -all the methods are available globally to emulate the browser JavaScript API. -To fully understand when timer functions will be executed, it's a good idea to -read up on the the Node.js -[Event Loop](../topics/event-loop-timers-and-nexttick.md). - -## Controlling the Time Continuum with Node.js - -The Node.js API provides several ways of scheduling code to execute at -some point after the present moment. The functions below may seem familiar, -since they are available in most browsers, but Node.js actually provides -its own implementation of these methods. Timers integrate very closely -with the system, and despite the fact that the API mirrors the browser -API, there are some differences in implementation. - -### "When I say so" Execution ~ *`setTimeout()`* - -`setTimeout()` can be used to schedule code execution after a designated -amount of milliseconds. This function is similar to -[`window.setTimeout()`](https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout) -from the browser JavaScript API, however a string of code cannot be passed -to be executed. - -`setTimeout()` accepts a function to execute as its first argument and the -millisecond delay defined as a number as the second argument. Additional -arguments may also be included and these will be passed on to the function. Here -is an example of that: - -```js -function myFunc (arg) { - console.log('arg was => ' + arg); -} - -setTimeout(myFunc, 1500, 'funky'); -``` - -The above function `myFunc()` will execute as close to 1500 -milliseconds (or 1.5 seconds) as possible due to the call of `setTimeout()`. - -The timeout interval that is set cannot be relied upon to execute after -that *exact* number of milliseconds. This is because other executing code that -blocks or holds onto the event loop will push the execution of the timeout -back. The *only* guarantee is that the timeout will not execute *sooner* than -the declared timeout interval. - -`setTimeout()` returns a `Timeout` object that can be used to reference the -timeout that was set. This returned object can be used to cancel the timeout ( -see `clearTimeout()` below) as well as change the execution behavior (see -`unref()` below). - -### "Right after this" Execution ~ *`setImmediate()`* - -`setImmediate()` will execute code at the end of the current event loop cycle. -This code will execute *after* any I/O operations in the current event loop and -*before* any timers scheduled for the next event loop. This code execution -could be thought of as happening "right after this", meaning any code following -the `setImmediate()` function call will execute before the `setImmediate()` -function argument. - -The first argument to `setImmediate()` will be the function to execute. Any -subsequent arguments will be passed to the function when it is executed. -Here's an example: - -```js -console.log('before immediate'); - -setImmediate((arg) => { - console.log(`executing immediate: ${arg}`); -}, 'so immediate'); - -console.log('after immediate'); -``` - -The above function passed to `setImmediate()` will execute after all runnable -code has executed, and the console output will be: - -```console -before immediate -after immediate -executing immediate: so immediate -``` - -`setImmediate()` returns and `Immediate` object, which can be used to cancel -the scheduled immediate (see `clearImmediate()` below). - -Note: Don't get `setImmediate()` confused with `process.nextTick()`. There are -some major ways they differ. The first is that `process.nextTick()` will run -*before* any `Immediate`s that are set as well as before any scheduled I/O. -The second is that `process.nextTick()` is non-clearable, meaning once -code has been scheduled to execute with `process.nextTick()`, the execution -cannot be stopped, just like with a normal function. Refer to [this guide](../topics/event-loop-timers-and-nexttick.md#processnexttick) -to better understand the operation of `process.nextTick()`. - -### "Infinite Loop" Execution ~ *`setInterval()`* - -If there is a block of code that should execute multiple times, `setInterval()` -can be used to execute that code. `setInterval()` takes a function -argument that will run an infinite number of times with a given millisecond -delay as the second argument. Just like `setTimeout()`, additional arguments -can be added beyond the delay, and these will be passed on to the function call. -Also like `setTimeout()`, the delay cannot be guaranteed because of operations -that may hold on to the event loop, and therefore should be treated as an -approximate delay. See the below example: - -```js -function intervalFunc () { - console.log('Cant stop me now!'); -} - -setInterval(intervalFunc, 1500); -``` -In the above example, `intervalFunc()` will execute about every 1500 -milliseconds, or 1.5 seconds, until it is stopped (see below). - -Just like `setTimeout()`, `setInterval()` also returns a `Timeout` object which -can be used to reference and modify the interval that was set. - -## Clearing the Future - -What can be done if a `Timeout` or `Immediate` object needs to be cancelled? -`setTimeout()`, `setImmediate()`, and `setInterval()` return a timer object -that can be used to reference the set `Timeout` or `Immediate` object. -By passing said object into the respective `clear` function, execution of -that object will be halted completely. The respective functions are -`clearTimeout()`, `clearImmediate()`, and `clearInterval()`. See the example -below for an example of each: - -```js -let timeoutObj = setTimeout(() => { - console.log('timeout beyond time'); -}, 1500); - -let immediateObj = setImmediate(() => { - console.log('immediately executing immediate'); -}); - -let intervalObj = setInterval(() => { - console.log('interviewing the interval'); -}, 500); - -clearTimeout(timeoutObj); -clearImmediate(immediateObj); -clearInterval(intervalObj); -``` - -## Leaving Timeouts Behind - -Remember that `Timeout` objects are returned by `setTimeout` and `setInterval`. -The `Timeout` object provides two functions intended to augment `Timeout` -behavior with `unref()` and `ref()`. If there is a `Timeout` object scheduled -using a `set` function, `unref()` can be called on that object. This will change -the behavior slightly, and not call the `Timeout` object *if it is the last -code to execute*. The `Timeout` object will not keep the process alive, waiting -to execute. - -In similar fashion, a `Timeout` object that has had `unref()` called on it -can remove that behavior by calling `ref()` on that same `Timeout` object, -which will then ensure its execution. Be aware, however, that this does -not *exactly* restore the initial behavior for performance reasons. See -below for examples of both: - -```js -let timerObj = setTimeout(() => { - console.log('will i run?'); -}); - -// if left alone, this statement will keep the above -// timeout from running, since the timeout will be the only -// thing keeping the program from exiting -timerObj.unref(); - -// we can bring it back to life by calling ref() inside -// an immediate -setImmediate(() => { - timerObj.ref(); -}); -``` -## Further Down the Event Loop - -There's much more to the Event Loop and Timers than this guide -has covered. To learn more about the internals of the Node.js -Event Loop and how Timers operate during execution, check out -this Node.js guide: [The Node.js Event Loop, Timers, and -process.nextTick()](../topics/event-loop-timers-and-nexttick.md). diff --git a/doc/topics/blocking-vs-non-blocking.md b/doc/topics/blocking-vs-non-blocking.md deleted file mode 100644 index ffdbcfc918e0e7..00000000000000 --- a/doc/topics/blocking-vs-non-blocking.md +++ /dev/null @@ -1,143 +0,0 @@ -# Overview of Blocking vs Non-Blocking - -This overview covers the difference between **blocking** and **non-blocking** -calls in Node.js. This overview will refer to the event loop and libuv but no -prior knowledge of those topics is required. Readers are assumed to have a -basic understanding of the JavaScript language and Node.js callback pattern. - -> "I/O" refers primarily to interaction with the system's disk and -> network supported by [libuv](http://libuv.org/). - - -## Blocking - -**Blocking** is when the execution of additional JavaScript in the Node.js -process must wait until a non-JavaScript operation completes. This happens -because the event loop is unable to continue running JavaScript while a -**blocking** operation is occurring. - -In Node.js, JavaScript that exhibits poor performance due to being CPU intensive -rather than waiting on a non-JavaScript operation, such as I/O, isn't typically -referred to as **blocking**. Synchronous methods in the Node.js standard library -that use libuv are the most commonly used **blocking** operations. Native -modules may also have **blocking** methods. - -All of the I/O methods in the Node.js standard library provide asynchronous -versions, which are **non-blocking**, and accept callback functions. Some -methods also have **blocking** counterparts, which have names that end with -`Sync`. - - -## Comparing Code - -**Blocking** methods execute **synchronously** and **non-blocking** methods -execute **asynchronously**. - -Using the File System module as an example, this is a **synchronous** file read: - -```js -const fs = require('fs'); -const data = fs.readFileSync('/file.md'); // blocks here until file is read -``` - -And here is an equivalent **asynchronous** example: - -```js -const fs = require('fs'); -fs.readFile('/file.md', (err, data) => { - if (err) throw err; -}); -``` - -The first example appears simpler than the second but has the disadvantage of -the second line **blocking** the execution of any additional JavaScript until -the entire file is read. Note that in the synchronous version if an error is -thrown it will need to be caught or the process will crash. In the asynchronous -version, it is up to the author to decide whether an error should throw as -shown. - -Let's expand our example a little bit: - -```js -const fs = require('fs'); -const data = fs.readFileSync('/file.md'); // blocks here until file is read -console.log(data); -// moreWork(); will run after console.log -``` - -And here is a similar, but not equivalent asynchronous example: - -```js -const fs = require('fs'); -fs.readFile('/file.md', (err, data) => { - if (err) throw err; - console.log(data); -}); -// moreWork(); will run before console.log -``` - -In the first example above, `console.log` will be called before `moreWork()`. In -the second example `fs.readFile()` is **non-blocking** so JavaScript execution -can continue and `moreWork()` will be called first. The ability to run -`moreWork()` without waiting for the file read to complete is a key design -choice that allows for higher throughput. - - -## Concurrency and Throughput - -JavaScript execution in Node.js is single threaded, so concurrency refers to the -event loop's capacity to execute JavaScript callback functions after completing -other work. Any code that is expected to run in a concurrent manner must allow -the event loop to continue running as non-JavaScript operations, like I/O, are -occurring. - -As an example, let's consider a case where each request to a web server takes -50ms to complete and 45ms of that 50ms is database I/O that can be done -asynchronously. Choosing **non-blocking** asynchronous operations frees up that -45ms per request to handle other requests. This is a significant difference in -capacity just by choosing to use **non-blocking** methods instead of -**blocking** methods. - -The event loop is different than models in many other languages where additional -threads may be created to handle concurrent work. - - -## Dangers of Mixing Blocking and Non-Blocking Code - -There are some patterns that should be avoided when dealing with I/O. Let's look -at an example: - -```js -const fs = require('fs'); -fs.readFile('/file.md', (err, data) => { - if (err) throw err; - console.log(data); -}); -fs.unlinkSync('/file.md'); -``` - -In the above example, `fs.unlinkSync()` is likely to be run before -`fs.readFile()`, which would delete `file.md` before it is actually read. A -better way to write this that is completely **non-blocking** and guaranteed to -execute in the correct order is: - - -```js -const fs = require('fs'); -fs.readFile('/file.md', (err, data) => { - if (err) throw err; - console.log(data); - fs.unlink('/file.md', (err) => { - if (err) throw err; - }); -}); -``` - -The above places a **non-blocking** call to `fs.unlink()` within the callback of -`fs.readFile()` which guarantees the correct order of operations. - - -## Additional Resources - -- [libuv](http://libuv.org/) -- [About Node.js](https://nodejs.org/en/about/) diff --git a/doc/topics/domain-postmortem.md b/doc/topics/domain-postmortem.md deleted file mode 100644 index e03012db926b08..00000000000000 --- a/doc/topics/domain-postmortem.md +++ /dev/null @@ -1,301 +0,0 @@ -# Domain Module Postmortem - -## Usability Issues - -### Implicit Behavior - -It's possible for a developer to create a new domain and then simply run -`domain.enter()`. Which then acts as a catch-all for any exception in the -future that couldn't be observed by the thrower. Allowing a module author to -intercept the exceptions of unrelated code in a different module. Preventing -the originator of the code from knowing about its own exceptions. - -Here's an example of how one indirectly linked modules can affect another: - -```js -// module a.js -const b = require('./b'); -const c = require('./c'); - - -// module b.js -const d = require('domain').create(); -d.on('error', () => { /* silence everything */ }); -d.enter(); - - -// module c.js -const dep = require('some-dep'); -dep.method(); // Uh-oh! This method doesn't actually exist. -``` - -Since module `b` enters the domain but never exits any uncaught exception will -be swallowed. Leaving module `c` in the dark as to why it didn't run the entire -script. Leaving a potentially partially populated `module.exports`. Doing this -is not the same as listening for `'uncaughtException'`. As the latter is -explicitly meant to globally catch errors. The other issue is that domains are -processed prior to any `'uncaughtException'` handlers, and prevent them from -running. - -Another issue is that domains route errors automatically if no `'error'` -handler was set on the event emitter. There is no opt-in mechanism for this, -and automatically propagates across the entire asynchronous chain. This may -seem useful at first, but once asynchronous calls are two or more modules deep -and one of them doesn't include an error handler the creator of the domain will -suddenly be catching unexpected exceptions, and the thrower's exception will go -unnoticed by the author. - -The following is a simple example of how a missing `'error'` handler allows -the active domain to hijack the error: - -```js -const domain = require('domain'); -const net = require('net'); -const d = domain.create(); -d.on('error', (err) => console.error(err.message)); - -d.run(() => net.createServer((c) => { - c.end(); - c.write('bye'); -}).listen(8000)); -``` - -Even manually removing the connection via `d.remove(c)` does not prevent the -connection's error from being automatically intercepted. - -Failures that plagues both error routing and exception handling are the -inconsistencies in how errors are bubbled. The following is an example of how -nested domains will and won't bubble the exception based on when they happen: - -```js -const domain = require('domain'); -const net = require('net'); -const d = domain.create(); -d.on('error', () => console.error('d intercepted an error')); - -d.run(() => { - const server = net.createServer((c) => { - const e = domain.create(); // No 'error' handler being set. - e.run(() => { - // This will not be caught by d's error handler. - setImmediate(() => { - throw new Error('thrown from setImmediate'); - }); - // Though this one will bubble to d's error handler. - throw new Error('immediately thrown'); - }); - }).listen(8080); -}); -``` - -It may be expected that nested domains always remain nested, and will always -propagate the exception up the domain stack. Or that exceptions will never -automatically bubble. Unfortunately both these situations occur, leading to -potentially confusing behavior that may even be prone to difficult to debug -timing conflicts. - - -### API Gaps - -While APIs based on using `EventEmitter` can use `bind()` and errback style -callbacks can use `intercept()`, alternative APIs that implicitly bind to the -active domain must be executed inside of `run()`. Meaning if module authors -wanted to support domains using a mechanism alternative to those mentioned they -must manually implement domain support themselves. Instead of being able to -leverage the implicit mechanisms already in place. - - -### Error Propagation - -Propagating errors across nested domains is not straight forward, if even -possible. Existing documentation shows a simple example of how to `close()` an -`http` server if there is an error in the request handler. What it does not -explain is how to close the server if the request handler creates another -domain instance for another async request. Using the following as a simple -example of the failing of error propagation: - -```js -const d1 = domain.create(); -d1.foo = true; // custom member to make more visible in console -d1.on('error', (er) => { /* handle error */ }); - -d1.run(() => setTimeout(() => { - const d2 = domain.create(); - d2.bar = 43; - d2.on('error', (er) => console.error(er.message, domain._stack)); - d2.run(() => { - setTimeout(() => { - setTimeout(() => { - throw new Error('outer'); - }); - throw new Error('inner') - }); - }); -})); -``` - -Even in the case that the domain instances are being used for local storage so -access to resources are made available there is still no way to allow the error -to continue propagating from `d2` back to `d1`. Quick inspection may tell us -that simply throwing from `d2`'s domain `'error'` handler would allow `d1` to -then catch the exception and execute its own error handler. Though that is not -the case. Upon inspection of `domain._stack` you'll see that the stack only -contains `d2`. - -This may be considered a failing of the API, but even if it did operate in this -way there is still the issue of transmitting the fact that a branch in the -asynchronous execution has failed, and that all further operations in that -branch must cease. In the example of the http request handler, if we fire off -several asynchronous requests and each one then `write()`'s data back to the -client many more errors will arise from attempting to `write()` to a closed -handle. More on this in _Resource Cleanup on Exception_. - - -### Resource Cleanup on Exception - -The script [`domain-resource-cleanup-example.js`][] -contains a more complex example of properly cleaning up in a small resource -dependency tree in the case that an exception occurs in a given connection or -any of its dependencies. Breaking down the script into its basic operations: - -- When a new connection happens, concurrently: - - Open a file on the file system - - Open Pipe to unique socket -- Read a chunk of the file asynchronously -- Write chunk to both the TCP connection and any listening sockets -- If any of these resources error, notify all other attached resources that - they need to clean up and shutdown - -As we can see from this example a lot more must be done to properly clean up -resources when something fails than what can be done strictly through the -domain API. All that domains offer is an exception aggregation mechanism. Even -the potentially useful ability to propagate data with the domain is easily -countered, in this example, by passing the needed resources as a function -argument. - -One problem domains perpetuated was the supposed simplicity of being able to -continue execution, contrary to what the documentation stated, of the -application despite an unexpected exception. This example demonstrates the -fallacy behind that idea. - -Attempting proper resource cleanup on unexpected exception becomes more complex -as the application itself grows in complexity. This example only has 3 basic -resources in play, and all of them with a clear dependency path. If an -application uses something like shared resources or resource reuse the ability -to cleanup, and properly test that cleanup has been done, grows greatly. - -In the end, in terms of handling errors, domains aren't much more than a -glorified `'uncaughtException'` handler. Except with more implicit and -unobservable behavior by third-parties. - - -### Resource Propagation - -Another use case for domains was to use it to propagate data along asynchronous -data paths. One problematic point is the ambiguity of when to expect the -correct domain when there are multiple in the stack (which must be assumed if -the async stack works with other modules). Also the conflict between being -able to depend on a domain for error handling while also having it available to -retrieve the necessary data. - -The following is a involved example demonstrating the failing using domains to -propagate data along asynchronous stacks: - -```js -const domain = require('domain'); -const net = require('net'); - -const server = net.createServer((c) => { - // Use a domain to propagate data across events within the - // connection so that we don't have to pass arguments - // everywhere. - const d = domain.create(); - d.data = { connection: c }; - d.add(c); - // Mock class that does some useless async data transformation - // for demonstration purposes. - const ds = new DataStream(dataTransformed); - c.on('data', (chunk) => ds.data(chunk)); -}).listen(8080, () => console.log(`listening on 8080`)); - -function dataTransformed(chunk) { - // FAIL! Because the DataStream instance also created a - // domain we have now lost the active domain we had - // hoped to use. - domain.active.data.connection.write(chunk); -} - -function DataStream(cb) { - this.cb = cb; - // DataStream wants to use domains for data propagation too! - // Unfortunately this will conflict with any domain that - // already exists. - this.domain = domain.create(); - this.domain.data = { inst: this }; -} - -DataStream.prototype.data = function data(chunk) { - // This code is self contained, but pretend it's a complex - // operation that crosses at least one other module. So - // passing along "this", etc., is not easy. - this.domain.run(function() { - // Simulate an async operation that does the data transform. - setImmediate(() => { - for (var i = 0; i < chunk.length; i++) - chunk[i] = ((chunk[i] + Math.random() * 100) % 96) + 33; - // Grab the instance from the active domain and use that - // to call the user's callback. - const self = domain.active.data.inst; - self.cb.call(self, chunk); - }); - }); -}; -``` - -The above shows that it is difficult to have more than one asynchronous API -attempt to use domains to propagate data. This example could possibly be fixed -by assigning `parent: domain.active` in the `DataStream` constructor. Then -restoring it via `domain.active = domain.active.data.parent` just before the -user's callback is called. Also the instantiation of `DataStream` in the -`'connection'` callback must be run inside `d.run()`, instead of simply using -`d.add(c)`, otherwise there will be no active domain. - -In short, for this to have a prayer of a chance usage would need to strictly -adhere to a set of guidelines that would be difficult to enforce or test. - - -## Performance Issues - -A significant deterrent from using domains is the overhead. Using node's -built-in http benchmark, `http_simple.js`, without domains it can handle over -22,000 requests/second. Whereas if it's run with `NODE_USE_DOMAINS=1` that -number drops down to under 17,000 requests/second. In this case there is only -a single global domain. If we edit the benchmark so the http request callback -creates a new domain instance performance drops further to 15,000 -requests/second. - -While this probably wouldn't affect a server only serving a few hundred or even -a thousand requests per second, the amount of overhead is directly proportional -to the number of asynchronous requests made. So if a single connection needs to -connect to several other services all of those will contribute to the overall -latency of delivering the final product to the client. - -Using `AsyncWrap` and tracking the number of times -`init`/`pre`/`post`/`destroy` are called in the mentioned benchmark we find -that the sum of all events called is over 170,000 times per second. This means -even adding 1 microsecond overhead per call for any type of setup or tear down -will result in a 17% performance loss. Granted, this is for the optimized -scenario of the benchmark, but I believe this demonstrates the necessity for a -mechanism such as domain to be as cheap to run as possible. - - -## Looking Ahead - -The domain module has been soft deprecated since Dec 2014, but has not yet been -removed because node offers no alternative functionality at the moment. As of -this writing there is ongoing work building out the `AsyncWrap` API and a -proposal for Zones being prepared for the TC39. At such time there is suitable -functionality to replace domains it will undergo the full deprecation cycle and -eventually be removed from core. - -[`domain-resource-cleanup-example.js`]: ./domain-resource-cleanup-example.js diff --git a/doc/topics/domain-resource-cleanup-example.js b/doc/topics/domain-resource-cleanup-example.js deleted file mode 100644 index d379d1a00e6695..00000000000000 --- a/doc/topics/domain-resource-cleanup-example.js +++ /dev/null @@ -1,136 +0,0 @@ -'use strict'; - -const domain = require('domain'); -const EE = require('events'); -const fs = require('fs'); -const net = require('net'); -const util = require('util'); -const print = process._rawDebug; - -const pipeList = []; -const FILENAME = '/tmp/tmp.tmp'; -const PIPENAME = '/tmp/node-domain-example-'; -const FILESIZE = 1024; -var uid = 0; - -// Setting up temporary resources -const buf = Buffer(FILESIZE); -for (var i = 0; i < buf.length; i++) - buf[i] = ((Math.random() * 1e3) % 78) + 48; // Basic ASCII -fs.writeFileSync(FILENAME, buf); - -function ConnectionResource(c) { - EE.call(this); - this._connection = c; - this._alive = true; - this._domain = domain.create(); - this._id = Math.random().toString(32).substr(2).substr(0, 8) + (++uid); - - this._domain.add(c); - this._domain.on('error', () => { - this._alive = false; - }); -} -util.inherits(ConnectionResource, EE); - -ConnectionResource.prototype.end = function end(chunk) { - this._alive = false; - this._connection.end(chunk); - this.emit('end'); -}; - -ConnectionResource.prototype.isAlive = function isAlive() { - return this._alive; -}; - -ConnectionResource.prototype.id = function id() { - return this._id; -}; - -ConnectionResource.prototype.write = function write(chunk) { - this.emit('data', chunk); - return this._connection.write(chunk); -}; - -// Example begin -net.createServer((c) => { - const cr = new ConnectionResource(c); - - const d1 = domain.create(); - fs.open(FILENAME, 'r', d1.intercept((fd) => { - streamInParts(fd, cr, 0); - })); - - pipeData(cr); - - c.on('close', () => cr.end()); -}).listen(8080); - -function streamInParts(fd, cr, pos) { - const d2 = domain.create(); - var alive = true; - d2.on('error', (er) => { - print('d2 error:', er.message) - cr.end(); - }); - fs.read(fd, new Buffer(10), 0, 10, pos, d2.intercept((bRead, buf) => { - if (!cr.isAlive()) { - return fs.close(fd); - } - if (cr._connection.bytesWritten < FILESIZE) { - // Documentation says callback is optional, but doesn't mention that if - // the write fails an exception will be thrown. - const goodtogo = cr.write(buf); - if (goodtogo) { - setTimeout(() => streamInParts(fd, cr, pos + bRead), 1000); - } else { - cr._connection.once('drain', () => streamInParts(fd, cr, pos + bRead)); - } - return; - } - cr.end(buf); - fs.close(fd); - })); -} - -function pipeData(cr) { - const pname = PIPENAME + cr.id(); - const ps = net.createServer(); - const d3 = domain.create(); - const connectionList = []; - d3.on('error', (er) => { - print('d3 error:', er.message); - cr.end(); - }); - d3.add(ps); - ps.on('connection', (conn) => { - connectionList.push(conn); - conn.on('data', () => {}); // don't care about incoming data. - conn.on('close', () => { - connectionList.splice(connectionList.indexOf(conn), 1); - }); - }); - cr.on('data', (chunk) => { - for (var i = 0; i < connectionList.length; i++) { - connectionList[i].write(chunk); - } - }); - cr.on('end', () => { - for (var i = 0; i < connectionList.length; i++) { - connectionList[i].end(); - } - ps.close(); - }); - pipeList.push(pname); - ps.listen(pname); -} - -process.on('SIGINT', () => process.exit()); -process.on('exit', () => { - try { - for (var i = 0; i < pipeList.length; i++) { - fs.unlinkSync(pipeList[i]); - } - fs.unlinkSync(FILENAME); - } catch (e) { } -}); diff --git a/doc/topics/event-loop-timers-and-nexttick.md b/doc/topics/event-loop-timers-and-nexttick.md deleted file mode 100644 index d7d0ee96e9c438..00000000000000 --- a/doc/topics/event-loop-timers-and-nexttick.md +++ /dev/null @@ -1,486 +0,0 @@ -# The Node.js Event Loop, Timers, and `process.nextTick()` - -## What is the Event Loop? - -The event loop is what allows Node.js to perform non-blocking I/O -operations — despite the fact that JavaScript is single-threaded — by -offloading operations to the system kernel whenever possible. - -Since most modern kernels are multi-threaded, they can handle multiple -operations executing in the background. When one of these operations -completes, the kernel tells Node.js so that the appropriate callback -may be added to the **poll** queue to eventually be executed. We'll explain -this in further detail later in this topic. - -## Event Loop Explained - -When Node.js starts, it initializes the event loop, processes the -provided input script (or drops into the [REPL][], which is not covered in -this document) which may make async API calls, schedule timers, or call -`process.nextTick()`, then begins processing the event loop. - -The following diagram shows a simplified overview of the event loop's -order of operations. - -```txt - ┌───────────────────────┐ -┌─>│ timers │ -│ └──────────┬────────────┘ -│ ┌──────────┴────────────┐ -│ │ I/O callbacks │ -│ └──────────┬────────────┘ -│ ┌──────────┴────────────┐ -│ │ idle, prepare │ -│ └──────────┬────────────┘ ┌───────────────┐ -│ ┌──────────┴────────────┐ │ incoming: │ -│ │ poll │<─────┤ connections, │ -│ └──────────┬────────────┘ │ data, etc. │ -│ ┌──────────┴────────────┐ └───────────────┘ -│ │ check │ -│ └──────────┬────────────┘ -│ ┌──────────┴────────────┐ -└──┤ close callbacks │ - └───────────────────────┘ -``` - -*note: each box will be referred to as a "phase" of the event loop.* - -Each phase has a FIFO queue of callbacks to execute. While each phase is -special in its own way, generally, when the event loop enters a given -phase, it will perform any operations specific to that phase, then -execute callbacks in that phase's queue until the queue has been -exhausted or the maximum number of callbacks has executed. When the -queue has been exhausted or the callback limit is reached, the event -loop will move to the next phase, and so on. - -Since any of these operations may schedule _more_ operations and new -events processed in the **poll** phase are queued by the kernel, poll -events can be queued while polling events are being processed. As a -result, long running callbacks can allow the poll phase to run much -longer than a timer's threshold. See the [**timers**](#timers) and -[**poll**](#poll) sections for more details. - -_**NOTE:** There is a slight discrepancy between the Windows and the -Unix/Linux implementation, but that's not important for this -demonstration. The most important parts are here. There are actually -seven or eight steps, but the ones we care about — ones that Node.js -actually uses - are those above._ - - -## Phases Overview - -* **timers**: this phase executes callbacks scheduled by `setTimeout()` - and `setInterval()`. -* **I/O callbacks**: executes almost all callbacks with the exception of - close callbacks, the ones scheduled by timers, and `setImmediate()`. -* **idle, prepare**: only used internally. -* **poll**: retrieve new I/O events; node will block here when appropriate. -* **check**: `setImmediate()` callbacks are invoked here. -* **close callbacks**: e.g. `socket.on('close', ...)`. - -Between each run of the event loop, Node.js checks if it is waiting for -any asynchronous I/O or timers and shuts down cleanly if there are not -any. - -## Phases in Detail - -### timers - -A timer specifies the **threshold** _after which_ a provided callback -_may be executed_ rather than the **exact** time a person _wants it to -be executed_. Timers callbacks will run as early as they can be -scheduled after the specified amount of time has passed; however, -Operating System scheduling or the running of other callbacks may delay -them. - -_**Note**: Technically, the [**poll** phase](#poll) controls when timers -are executed._ - -For example, say you schedule a timeout to execute after a 100 ms -threshold, then your script starts asynchronously reading a file which -takes 95 ms: - -```js - -var fs = require('fs'); - -function someAsyncOperation (callback) { - // Assume this takes 95ms to complete - fs.readFile('/path/to/file', callback); -} - -var timeoutScheduled = Date.now(); - -setTimeout(function () { - - var delay = Date.now() - timeoutScheduled; - - console.log(delay + "ms have passed since I was scheduled"); -}, 100); - - -// do someAsyncOperation which takes 95 ms to complete -someAsyncOperation(function () { - - var startCallback = Date.now(); - - // do something that will take 10ms... - while (Date.now() - startCallback < 10) { - ; // do nothing - } - -}); -``` - -When the event loop enters the **poll** phase, it has an empty queue -(`fs.readFile()` has not completed), so it will wait for the number of ms -remaining until the soonest timer's threshold is reached. While it is -waiting 95 ms pass, `fs.readFile()` finishes reading the file and its -callback which takes 10 ms to complete is added to the **poll** queue and -executed. When the callback finishes, there are no more callbacks in the -queue, so the event loop will see that the threshold of the soonest -timer has been reached then wrap back to the **timers** phase to execute -the timer's callback. In this example, you will see that the total delay -between the timer being scheduled and its callback being executed will -be 105ms. - -Note: To prevent the **poll** phase from starving the event loop, [libuv] -(http://libuv.org/) (the C library that implements the Node.js -event loop and all of the asynchronous behaviors of the platform) -also has a hard maximum (system dependent) before it stops polling for -more events. - -### I/O callbacks - -This phase executes callbacks for some system operations such as types -of TCP errors. For example if a TCP socket receives `ECONNREFUSED` when -attempting to connect, some \*nix systems want to wait to report the -error. This will be queued to execute in the **I/O callbacks** phase. - -### poll - -The **poll** phase has two main functions: - -1. Executing scripts for timers whose threshold has elapsed, then -2. Processing events in the **poll** queue. - -When the event loop enters the **poll** phase _and there are no timers -scheduled_, one of two things will happen: - -* _If the **poll** queue **is not empty**_, the event loop will iterate -through its queue of callbacks executing them synchronously until -either the queue has been exhausted, or the system-dependent hard limit -is reached. - -* _If the **poll** queue **is empty**_, one of two more things will -happen: - * If scripts have been scheduled by `setImmediate()`, the event loop - will end the **poll** phase and continue to the **check** phase to - execute those scheduled scripts. - - * If scripts **have not** been scheduled by `setImmediate()`, the - event loop will wait for callbacks to be added to the queue, then - execute them immediately. - -Once the **poll** queue is empty the event loop will check for timers -_whose time thresholds have been reached_. If one or more timers are -ready, the event loop will wrap back to the **timers** phase to execute -those timers' callbacks. - -### check - -This phase allows a person to execute callbacks immediately after the -**poll** phase has completed. If the **poll** phase becomes idle and -scripts have been queued with `setImmediate()`, the event loop may -continue to the **check** phase rather than waiting. - -`setImmediate()` is actually a special timer that runs in a separate -phase of the event loop. It uses a libuv API that schedules callbacks to -execute after the **poll** phase has completed. - -Generally, as the code is executed, the event loop will eventually hit -the **poll** phase where it will wait for an incoming connection, request, -etc. However, if a callback has been scheduled with `setImmediate()` -and the **poll** phase becomes idle, it will end and continue to the -**check** phase rather than waiting for **poll** events. - -### close callbacks - -If a socket or handle is closed abruptly (e.g. `socket.destroy()`), the -`'close'` event will be emitted in this phase. Otherwise it will be -emitted via `process.nextTick()`. - -## `setImmediate()` vs `setTimeout()` - -`setImmediate` and `setTimeout()` are similar, but behave in different -ways depending on when they are called. - -* `setImmediate()` is designed to execute a script once the current -**poll** phase completes. -* `setTimeout()` schedules a script to be run after a minimum threshold -in ms has elapsed. - -The order in which the timers are executed will vary depending on the -context in which they are called. If both are called from within the -main module, then timing will be bound by the performance of the process -(which can be impacted by other applications running on the machine). - -For example, if we run the following script which is not within an I/O -cycle (i.e. the main module), the order in which the two timers are -executed is non-deterministic, as it is bound by the performance of the -process: - - -```js -// timeout_vs_immediate.js -setTimeout(function timeout () { - console.log('timeout'); -},0); - -setImmediate(function immediate () { - console.log('immediate'); -}); -``` - -```console -$ node timeout_vs_immediate.js -timeout -immediate - -$ node timeout_vs_immediate.js -immediate -timeout -``` - -However, if you move the two calls within an I/O cycle, the immediate -callback is always executed first: - -```js -// timeout_vs_immediate.js -var fs = require('fs') - -fs.readFile(__filename, () => { - setTimeout(() => { - console.log('timeout') - }, 0) - setImmediate(() => { - console.log('immediate') - }) -}) -``` - -```console -$ node timeout_vs_immediate.js -immediate -timeout - -$ node timeout_vs_immediate.js -immediate -timeout -``` - -The main advantage to using `setImmediate()` over `setTimeout()` is -`setImmediate()` will always be executed before any timers if scheduled -within an I/O cycle, independently of how many timers are present. - -## `process.nextTick()` - -### Understanding `process.nextTick()` - -You may have noticed that `process.nextTick()` was not displayed in the -diagram, even though it's a part of the asynchronous API. This is because -`process.nextTick()` is not technically part of the event loop. Instead, -the `nextTickQueue` will be processed after the current operation -completes, regardless of the current phase of the event loop. - -Looking back at our diagram, any time you call `process.nextTick()` in a -given phase, all callbacks passed to `process.nextTick()` will be -resolved before the event loop continues. This can create some bad -situations because **it allows you to "starve" your I/O by making -recursive `process.nextTick()` calls**, which prevents the event loop -from reaching the **poll** phase. - -### Why would that be allowed? - -Why would something like this be included in Node.js? Part of it is a -design philosophy where an API should always be asynchronous even where -it doesn't have to be. Take this code snippet for example: - -```js -function apiCall (arg, callback) { - if (typeof arg !== 'string') - return process.nextTick(callback, - new TypeError('argument should be string')); -} -``` - -The snippet does an argument check and if it's not correct, it will pass -the error to the callback. The API updated fairly recently to allow -passing arguments to `process.nextTick()` allowing it to take any -arguments passed after the callback to be propagated as the arguments to -the callback so you don't have to nest functions. - -What we're doing is passing an error back to the user but only *after* -we have allowed the rest of the user's code to execute. By using -`process.nextTick()` we guarantee that `apiCall()` always runs its -callback *after* the rest of the user's code and *before* the event loop -is allowed to proceed. To achieve this, the JS call stack is allowed to -unwind then immediately execute the provided callback which allows a -person to make recursive calls to `process.nextTick()` without reaching a -`RangeError: Maximum call stack size exceeded from v8`. - -This philosophy can lead to some potentially problematic situations. -Take this snippet for example: - -```js -// this has an asynchronous signature, but calls callback synchronously -function someAsyncApiCall (callback) { callback(); }; - -// the callback is called before `someAsyncApiCall` completes. -someAsyncApiCall(() => { - - // since someAsyncApiCall has completed, bar hasn't been assigned any value - console.log('bar', bar); // undefined - -}); - -var bar = 1; -``` - -The user defines `someAsyncApiCall()` to have an asynchronous signature, -but it actually operates synchronously. When it is called, the callback -provided to `someAsyncApiCall()` is called in the same phase of the -event loop because `someAsyncApiCall()` doesn't actually do anything -asynchronously. As a result, the callback tries to reference `bar` even -though it may not have that variable in scope yet, because the script has not -been able to run to completion. - -By placing the callback in a `process.nextTick()`, the script still has the -ability to run to completion, allowing all the variables, functions, -etc., to be initialized prior to the callback being called. It also has -the advantage of not allowing the event loop to continue. It may be -useful for the user to be alerted to an error before the event loop is -allowed to continue. Here is the previous example using `process.nextTick()`: - -```js -function someAsyncApiCall (callback) { - process.nextTick(callback); -}; - -someAsyncApiCall(() => { - console.log('bar', bar); // 1 -}); - -var bar = 1; -``` - -Here's another real world example: - -```js -const server = net.createServer(() => {}).listen(8080); - -server.on('listening', () => {}); -``` - -When only a port is passed the port is bound immediately. So the -`'listening'` callback could be called immediately. Problem is that the -`.on('listening')` will not have been set by that time. - -To get around this the `'listening'` event is queued in a `nextTick()` -to allow the script to run to completion. Which allows the user to set -any event handlers they want. - -## `process.nextTick()` vs `setImmediate()` - -We have two calls that are similar as far as users are concerned, but -their names are confusing. - -* `process.nextTick()` fires immediately on the same phase -* `setImmediate()` fires on the following iteration or 'tick' of the -event loop - -In essence, the names should be swapped. `process.nextTick()` fires more -immediately than `setImmediate()` but this is an artifact of the past -which is unlikely to change. Making this switch would break a large -percentage of the packages on npm. Every day more new modules are being -added, which mean every day we wait, more potential breakages occur. -While they are confusing, the names themselves won't change. - -*We recommend developers use `setImmediate()` in all cases because it's -easier to reason about (and it leads to code that's compatible with a -wider variety of environments, like browser JS.)* - -## Why use `process.nextTick()`? - -There are two main reasons: - -1. Allow users to handle errors, cleanup any then unneeded resources, or -perhaps try the request again before the event loop continues. - -2. At times it's necessary to allow a callback to run after the call -stack has unwound but before the event loop continues. - -One example is to match the user's expectations. Simple example: - -```js -var server = net.createServer(); -server.on('connection', function(conn) { }); - -server.listen(8080); -server.on('listening', function() { }); -``` - -Say that `listen()` is run at the beginning of the event loop, but the -listening callback is placed in a `setImmediate()`. Now, unless a -hostname is passed binding to the port will happen immediately. Now for -the event loop to proceed it must hit the **poll** phase, which means -there is a non-zero chance that a connection could have been received -allowing the connection event to be fired before the listening event. - -Another example is running a function constructor that was to, say, -inherit from `EventEmitter` and it wanted to call an event within the -constructor: - -```js -const EventEmitter = require('events'); -const util = require('util'); - -function MyEmitter() { - EventEmitter.call(this); - this.emit('event'); -} -util.inherits(MyEmitter, EventEmitter); - -const myEmitter = new MyEmitter(); -myEmitter.on('event', function() { - console.log('an event occurred!'); -}); -``` - -You can't emit an event from the constructor immediately -because the script will not have processed to the point where the user -assigns a callback to that event. So, within the constructor itself, -you can use `process.nextTick()` to set a callback to emit the event -after the constructor has finished, which provides the expected results: - -```js -const EventEmitter = require('events'); -const util = require('util'); - -function MyEmitter() { - EventEmitter.call(this); - - // use nextTick to emit the event once a handler is assigned - process.nextTick(function () { - this.emit('event'); - }.bind(this)); -} -util.inherits(MyEmitter, EventEmitter); - -const myEmitter = new MyEmitter(); -myEmitter.on('event', function() { - console.log('an event occurred!'); -}); -``` - -[REPL]: https://nodejs.org/api/repl.html#repl_repl From 1253650cf406f950e170fef87b140e6bfd59b734 Mon Sep 17 00:00:00 2001 From: Vse Mozhet Byt Date: Fri, 20 Jan 2017 03:42:50 +0200 Subject: [PATCH 041/291] doc: update examples in api/crypto.md * var -> const / let in crypto.md * fix error in crypto.md code example * equal -> strictEqual, == -> === in crypto.md * update estimated outputs in crypto.md * snake_case -> camelCase in crypto.md examples * concatenation -> multiline template in crypto * add missing line break in crypto code example * add missing link reference in crypto.md PR-URL: https://github.com/nodejs/node/pull/10909 Reviewed-By: Luigi Pinca Reviewed-By: Sam Roberts Reviewed-By: James M Snell --- doc/api/crypto.md | 103 ++++++++++++++++++++++++---------------------- 1 file changed, 53 insertions(+), 50 deletions(-) diff --git a/doc/api/crypto.md b/doc/api/crypto.md index 7f77d3f940768c..9102f2e89c03c4 100644 --- a/doc/api/crypto.md +++ b/doc/api/crypto.md @@ -26,7 +26,7 @@ It is possible for Node.js to be built without including support for the error being thrown. ```js -var crypto; +let crypto; try { crypto = require('crypto'); } catch (err) { @@ -132,9 +132,9 @@ Example: Using `Cipher` objects as streams: const crypto = require('crypto'); const cipher = crypto.createCipher('aes192', 'a password'); -var encrypted = ''; +let encrypted = ''; cipher.on('readable', () => { - var data = cipher.read(); + const data = cipher.read(); if (data) encrypted += data.toString('hex'); }); @@ -166,7 +166,7 @@ Example: Using the [`cipher.update()`][] and [`cipher.final()`][] methods: const crypto = require('crypto'); const cipher = crypto.createCipher('aes192', 'a password'); -var encrypted = cipher.update('some clear text data', 'utf8', 'hex'); +let encrypted = cipher.update('some clear text data', 'utf8', 'hex'); encrypted += cipher.final('hex'); console.log(encrypted); // Prints: ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504 @@ -269,9 +269,9 @@ Example: Using `Decipher` objects as streams: const crypto = require('crypto'); const decipher = crypto.createDecipher('aes192', 'a password'); -var decrypted = ''; +let decrypted = ''; decipher.on('readable', () => { - var data = decipher.read(); + const data = decipher.read(); if (data) decrypted += data.toString('utf8'); }); @@ -280,7 +280,7 @@ decipher.on('end', () => { // Prints: some clear text data }); -var encrypted = 'ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504'; +const encrypted = 'ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504'; decipher.write(encrypted, 'hex'); decipher.end(); ``` @@ -304,8 +304,8 @@ Example: Using the [`decipher.update()`][] and [`decipher.final()`][] methods: const crypto = require('crypto'); const decipher = crypto.createDecipher('aes192', 'a password'); -var encrypted = 'ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504'; -var decrypted = decipher.update(encrypted, 'hex', 'utf8'); +const encrypted = 'ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504'; +let decrypted = decipher.update(encrypted, 'hex', 'utf8'); decrypted += decipher.final('utf8'); console.log(decrypted); // Prints: some clear text data @@ -402,18 +402,18 @@ const assert = require('assert'); // Generate Alice's keys... const alice = crypto.createDiffieHellman(2048); -const alice_key = alice.generateKeys(); +const aliceKey = alice.generateKeys(); // Generate Bob's keys... const bob = crypto.createDiffieHellman(alice.getPrime(), alice.getGenerator()); -const bob_key = bob.generateKeys(); +const bobKey = bob.generateKeys(); // Exchange and generate the secret... -const alice_secret = alice.computeSecret(bob_key); -const bob_secret = bob.computeSecret(alice_key); +const aliceSecret = alice.computeSecret(bobKey); +const bobSecret = bob.computeSecret(aliceKey); // OK -assert.equal(alice_secret.toString('hex'), bob_secret.toString('hex')); +assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); ``` ### diffieHellman.computeSecret(other_public_key[, input_encoding][, output_encoding]) @@ -531,17 +531,17 @@ const assert = require('assert'); // Generate Alice's keys... const alice = crypto.createECDH('secp521r1'); -const alice_key = alice.generateKeys(); +const aliceKey = alice.generateKeys(); // Generate Bob's keys... const bob = crypto.createECDH('secp521r1'); -const bob_key = bob.generateKeys(); +const bobKey = bob.generateKeys(); // Exchange and generate the secret... -const alice_secret = alice.computeSecret(bob_key); -const bob_secret = bob.computeSecret(alice_key); +const aliceSecret = alice.computeSecret(bobKey); +const bobSecret = bob.computeSecret(aliceKey); -assert(alice_secret, bob_secret); +assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); // OK ``` @@ -648,13 +648,14 @@ alice.setPrivateKey( ); // Bob uses a newly generated cryptographically strong -// pseudorandom key pair bob.generateKeys(); +// pseudorandom key pair +bob.generateKeys(); -const alice_secret = alice.computeSecret(bob.getPublicKey(), null, 'hex'); -const bob_secret = bob.computeSecret(alice.getPublicKey(), null, 'hex'); +const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex'); +const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex'); -// alice_secret and bob_secret should be the same shared secret value -console.log(alice_secret === bob_secret); +// aliceSecret and bobSecret should be the same shared secret value +console.log(aliceSecret === bobSecret); ``` ## Class: Hash @@ -680,7 +681,7 @@ const crypto = require('crypto'); const hash = crypto.createHash('sha256'); hash.on('readable', () => { - var data = hash.read(); + const data = hash.read(); if (data) console.log(data.toString('hex')); // Prints: @@ -763,7 +764,7 @@ const crypto = require('crypto'); const hmac = crypto.createHmac('sha256', 'a secret'); hmac.on('readable', () => { - var data = hmac.read(); + const data = hmac.read(); if (data) console.log(data.toString('hex')); // Prints: @@ -847,8 +848,8 @@ const sign = crypto.createSign('RSA-SHA256'); sign.write('some data to sign'); sign.end(); -const private_key = getPrivateKeySomehow(); -console.log(sign.sign(private_key, 'hex')); +const privateKey = getPrivateKeySomehow(); +console.log(sign.sign(privateKey, 'hex')); // Prints: the calculated signature ``` @@ -860,8 +861,8 @@ const sign = crypto.createSign('RSA-SHA256'); sign.update('some data to sign'); -const private_key = getPrivateKeySomehow(); -console.log(sign.sign(private_key, 'hex')); +const privateKey = getPrivateKeySomehow(); +console.log(sign.sign(privateKey, 'hex')); // Prints: the calculated signature ``` @@ -878,13 +879,14 @@ const sign = crypto.createSign('sha256'); sign.update('some data to sign'); -const private_key = '-----BEGIN EC PRIVATE KEY-----\n' + - 'MHcCAQEEIF+jnWY1D5kbVYDNvxxo/Y+ku2uJPDwS0r/VuPZQrjjVoAoGCCqGSM49\n' + - 'AwEHoUQDQgAEurOxfSxmqIRYzJVagdZfMMSjRNNhB8i3mXyIMq704m2m52FdfKZ2\n' + - 'pQhByd5eyj3lgZ7m7jbchtdgyOF8Io/1ng==\n' + - '-----END EC PRIVATE KEY-----\n'; +const privateKey = +`-----BEGIN EC PRIVATE KEY----- +MHcCAQEEIF+jnWY1D5kbVYDNvxxo/Y+ku2uJPDwS0r/VuPZQrjjVoAoGCCqGSM49 +AwEHoUQDQgAEurOxfSxmqIRYzJVagdZfMMSjRNNhB8i3mXyIMq704m2m52FdfKZ2 +pQhByd5eyj3lgZ7m7jbchtdgyOF8Io/1ng== +-----END EC PRIVATE KEY-----`; -console.log(sign.sign(private_key).toString('hex')); +console.log(sign.sign(privateKey).toString('hex')); ``` ### sign.sign(private_key[, output_format]) @@ -947,9 +949,9 @@ const verify = crypto.createVerify('RSA-SHA256'); verify.write('some data to sign'); verify.end(); -const public_key = getPublicKeySomehow(); +const publicKey = getPublicKeySomehow(); const signature = getSignatureToVerify(); -console.log(verify.verify(public_key, signature)); +console.log(verify.verify(publicKey, signature)); // Prints: true or false ``` @@ -961,9 +963,9 @@ const verify = crypto.createVerify('RSA-SHA256'); verify.update('some data to sign'); -const public_key = getPublicKeySomehow(); +const publicKey = getPublicKeySomehow(); const signature = getSignatureToVerify(); -console.log(verify.verify(public_key, signature)); +console.log(verify.verify(publicKey, signature)); // Prints: true or false ``` @@ -1192,7 +1194,7 @@ const hash = crypto.createHash('sha256'); const input = fs.createReadStream(filename); input.on('readable', () => { - var data = input.read(); + const data = input.read(); if (data) hash.update(data); else { @@ -1226,7 +1228,7 @@ const hmac = crypto.createHmac('sha256', 'a secret'); const input = fs.createReadStream(filename); input.on('readable', () => { - var data = input.read(); + const data = input.read(); if (data) hmac.update(data); else { @@ -1278,7 +1280,7 @@ Example: ```js const curves = crypto.getCurves(); -console.log(curves); // ['secp256k1', 'secp384r1', ...] +console.log(curves); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...] ``` ### crypto.getDiffieHellman(group_name) @@ -1307,11 +1309,11 @@ const bob = crypto.getDiffieHellman('modp14'); alice.generateKeys(); bob.generateKeys(); -const alice_secret = alice.computeSecret(bob.getPublicKey(), null, 'hex'); -const bob_secret = bob.computeSecret(alice.getPublicKey(), null, 'hex'); +const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex'); +const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex'); -/* alice_secret and bob_secret should be the same */ -console.log(alice_secret == bob_secret); +/* aliceSecret and bobSecret should be the same */ +console.log(aliceSecret === bobSecret); ``` ### crypto.getHashes() @@ -1326,7 +1328,7 @@ Example: ```js const hashes = crypto.getHashes(); -console.log(hashes); // ['sha', 'sha1', 'sha1WithRSAEncryption', ...] +console.log(hashes); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...] ``` ### crypto.pbkdf2(password, salt, iterations, keylen, digest, callback) @@ -1357,7 +1359,7 @@ Example: const crypto = require('crypto'); crypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', (err, key) => { if (err) throw err; - console.log(key.toString('hex')); // 'c5e478d...1469e50' + console.log(key.toString('hex')); // '3745e48...aa39b34' }); ``` @@ -1390,7 +1392,7 @@ Example: ```js const crypto = require('crypto'); const key = crypto.pbkdf2Sync('secret', 'salt', 100000, 512, 'sha512'); -console.log(key.toString('hex')); // 'c5e478d...1469e50' +console.log(key.toString('hex')); // '3745e48...aa39b34' ``` An array of supported digest functions can be retrieved using @@ -1938,6 +1940,7 @@ the `crypto`, `tls`, and `https` modules and are generally specific to OpenSSL. [`crypto.createHash()`]: #crypto_crypto_createhash_algorithm [`crypto.createHmac()`]: #crypto_crypto_createhmac_algorithm_key [`crypto.createSign()`]: #crypto_crypto_createsign_algorithm +[`crypto.createVerify()`]: #crypto_crypto_createverify_algorithm [`crypto.getCurves()`]: #crypto_crypto_getcurves [`crypto.getHashes()`]: #crypto_crypto_gethashes [`crypto.pbkdf2()`]: #crypto_crypto_pbkdf2_password_salt_iterations_keylen_digest_callback From 94c4323d56c1f05b389d5aec7a8dab3e76d89a10 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Sch=C3=BCnemann?= Date: Wed, 21 Dec 2016 11:36:50 +0100 Subject: [PATCH 042/291] async_wrap: close the destroy_ids_idle_handle_ The destroy_ids_idle_handle_ needs to be closed on environment destruction. Not closing the handle leaves a dangling pointer in the used uv loop. This leads to undefined behavior when the uv loop is used after the environment has been destroyed. PR-URL: https://github.com/nodejs/node/pull/10385 Reviewed-By: Anna Henningsen Reviewed-By: Ben Noordhuis Reviewed-By: James M Snell --- src/env-inl.h | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/env-inl.h b/src/env-inl.h index 83db3d33b6d18f..db9f5c205e4132 100644 --- a/src/env-inl.h +++ b/src/env-inl.h @@ -207,6 +207,19 @@ inline Environment::~Environment() { delete hc; } + while (handle_cleanup_waiting_ != 0) + uv_run(event_loop(), UV_RUN_ONCE); + + // Closing the destroy_ids_idle_handle_ within the handle cleanup queue + // prevents the async wrap destroy hook from being called. + uv_handle_t* handle = + reinterpret_cast(&destroy_ids_idle_handle_); + handle->data = this; + handle_cleanup_waiting_ = 1; + uv_close(handle, [](uv_handle_t* handle) { + static_cast(handle->data)->FinishHandleCleanup(handle); + }); + while (handle_cleanup_waiting_ != 0) uv_run(event_loop(), UV_RUN_ONCE); From 9916ee8c3642dc8c4663a1c8f9ffaacd045f6248 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Sat, 10 Dec 2016 21:12:58 -0800 Subject: [PATCH 043/291] test: refactor test-https-truncate * use common.mustCall() where appropriate * Buffer.allocUnsafe() -> Buffer.alloc() * do crypto check before loading any additional modules * specify 1ms duration for `setTimeout()` PR-URL: https://github.com/nodejs/node/pull/10225 Reviewed-By: Colin Ihrig Reviewed-By: Benjamin Gruenbaum Reviewed-By: Luigi Pinca --- test/parallel/test-https-truncate.js | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/test/parallel/test-https-truncate.js b/test/parallel/test-https-truncate.js index 4101a8c974e736..c96b385fc37fde 100644 --- a/test/parallel/test-https-truncate.js +++ b/test/parallel/test-https-truncate.js @@ -1,11 +1,12 @@ 'use strict'; const common = require('../common'); -const assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } + +const assert = require('assert'); const https = require('https'); const fs = require('fs'); @@ -14,7 +15,7 @@ const key = fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'); const cert = fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem'); // number of bytes discovered empirically to trigger the bug -const data = Buffer.allocUnsafe(1024 * 32 + 1); +const data = Buffer.alloc(1024 * 32 + 1); httpsTest(); @@ -36,12 +37,11 @@ function httpsTest() { } -function test(res) { - res.on('end', function() { +const test = common.mustCall(function(res) { + res.on('end', common.mustCall(function() { assert.strictEqual(res._readableState.length, 0); assert.strictEqual(bytes, data.length); - console.log('ok'); - }); + })); // Pause and then resume on each chunk, to ensure that there will be // a lone byte hanging out at the very end. @@ -49,6 +49,6 @@ function test(res) { res.on('data', function(chunk) { bytes += chunk.length; this.pause(); - setTimeout(this.resume.bind(this)); + setTimeout(this.resume.bind(this), 1); }); -} +}); From 6e8d627217e43352d91ae2de70b7524face3eb63 Mon Sep 17 00:00:00 2001 From: Ben Noordhuis Date: Fri, 9 Dec 2016 00:17:14 +0100 Subject: [PATCH 044/291] lib,src: support values > 4GB in heap statistics We were transporting the heap statistics as uint32 values to JS land but those wrap around for values > 4 GB. Use 64 bits floats instead, those should last us a while. Fixes: https://github.com/nodejs/node/issues/10185 PR-URL: https://github.com/nodejs/node/pull/10186 Reviewed-By: Anna Henningsen Reviewed-By: Colin Ihrig Reviewed-By: Evan Lucas --- lib/v8.js | 4 ++-- src/env-inl.h | 8 ++++---- src/env.h | 12 ++++++------ src/node_v8.cc | 12 ++++++------ 4 files changed, 18 insertions(+), 18 deletions(-) diff --git a/lib/v8.js b/lib/v8.js index 90abc627a45af0..415aed593eb799 100644 --- a/lib/v8.js +++ b/lib/v8.js @@ -18,7 +18,7 @@ const v8binding = process.binding('v8'); // Properties for heap statistics buffer extraction. const heapStatisticsBuffer = - new Uint32Array(v8binding.heapStatisticsArrayBuffer); + new Float64Array(v8binding.heapStatisticsArrayBuffer); const kTotalHeapSizeIndex = v8binding.kTotalHeapSizeIndex; const kTotalHeapSizeExecutableIndex = v8binding.kTotalHeapSizeExecutableIndex; const kTotalPhysicalSizeIndex = v8binding.kTotalPhysicalSizeIndex; @@ -31,7 +31,7 @@ const kPeakMallocedMemoryIndex = v8binding.kPeakMallocedMemoryIndex; // Properties for heap space statistics buffer extraction. const heapSpaceStatisticsBuffer = - new Uint32Array(v8binding.heapSpaceStatisticsArrayBuffer); + new Float64Array(v8binding.heapSpaceStatisticsArrayBuffer); const kHeapSpaces = v8binding.kHeapSpaces; const kNumberOfHeapSpaces = kHeapSpaces.length; const kHeapSpaceStatisticsPropertiesCount = diff --git a/src/env-inl.h b/src/env-inl.h index db9f5c205e4132..1a17e2947d0597 100644 --- a/src/env-inl.h +++ b/src/env-inl.h @@ -329,22 +329,22 @@ inline std::vector* Environment::destroy_ids_list() { return &destroy_ids_list_; } -inline uint32_t* Environment::heap_statistics_buffer() const { +inline double* Environment::heap_statistics_buffer() const { CHECK_NE(heap_statistics_buffer_, nullptr); return heap_statistics_buffer_; } -inline void Environment::set_heap_statistics_buffer(uint32_t* pointer) { +inline void Environment::set_heap_statistics_buffer(double* pointer) { CHECK_EQ(heap_statistics_buffer_, nullptr); // Should be set only once. heap_statistics_buffer_ = pointer; } -inline uint32_t* Environment::heap_space_statistics_buffer() const { +inline double* Environment::heap_space_statistics_buffer() const { CHECK_NE(heap_space_statistics_buffer_, nullptr); return heap_space_statistics_buffer_; } -inline void Environment::set_heap_space_statistics_buffer(uint32_t* pointer) { +inline void Environment::set_heap_space_statistics_buffer(double* pointer) { CHECK_EQ(heap_space_statistics_buffer_, nullptr); // Should be set only once. heap_space_statistics_buffer_ = pointer; } diff --git a/src/env.h b/src/env.h index b99bb45f819e59..8c256ca9c7faa4 100644 --- a/src/env.h +++ b/src/env.h @@ -469,11 +469,11 @@ class Environment { // List of id's that have been destroyed and need the destroy() cb called. inline std::vector* destroy_ids_list(); - inline uint32_t* heap_statistics_buffer() const; - inline void set_heap_statistics_buffer(uint32_t* pointer); + inline double* heap_statistics_buffer() const; + inline void set_heap_statistics_buffer(double* pointer); - inline uint32_t* heap_space_statistics_buffer() const; - inline void set_heap_space_statistics_buffer(uint32_t* pointer); + inline double* heap_space_statistics_buffer() const; + inline void set_heap_space_statistics_buffer(double* pointer); inline char* http_parser_buffer() const; inline void set_http_parser_buffer(char* buffer); @@ -581,8 +581,8 @@ class Environment { &HandleCleanup::handle_cleanup_queue_> handle_cleanup_queue_; int handle_cleanup_waiting_; - uint32_t* heap_statistics_buffer_ = nullptr; - uint32_t* heap_space_statistics_buffer_ = nullptr; + double* heap_statistics_buffer_ = nullptr; + double* heap_space_statistics_buffer_ = nullptr; char* http_parser_buffer_; diff --git a/src/node_v8.cc b/src/node_v8.cc index a033c48a7c98be..7059922607089d 100644 --- a/src/node_v8.cc +++ b/src/node_v8.cc @@ -57,8 +57,8 @@ void UpdateHeapStatisticsArrayBuffer(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); HeapStatistics s; env->isolate()->GetHeapStatistics(&s); - uint32_t* const buffer = env->heap_statistics_buffer(); -#define V(index, name, _) buffer[index] = static_cast(s.name()); + double* const buffer = env->heap_statistics_buffer(); +#define V(index, name, _) buffer[index] = static_cast(s.name()); HEAP_STATISTICS_PROPERTIES(V) #undef V } @@ -68,13 +68,13 @@ void UpdateHeapSpaceStatisticsBuffer(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); HeapSpaceStatistics s; Isolate* const isolate = env->isolate(); - uint32_t* buffer = env->heap_space_statistics_buffer(); + double* buffer = env->heap_space_statistics_buffer(); for (size_t i = 0; i < number_of_heap_spaces; i++) { isolate->GetHeapSpaceStatistics(&s, i); size_t const property_offset = i * kHeapSpaceStatisticsPropertiesCount; #define V(index, name, _) buffer[property_offset + index] = \ - static_cast(s.name()); + static_cast(s.name()); HEAP_SPACE_STATISTICS_PROPERTIES(V) #undef V } @@ -103,7 +103,7 @@ void InitializeV8Bindings(Local target, "updateHeapStatisticsArrayBuffer", UpdateHeapStatisticsArrayBuffer); - env->set_heap_statistics_buffer(new uint32_t[kHeapStatisticsPropertiesCount]); + env->set_heap_statistics_buffer(new double[kHeapStatisticsPropertiesCount]); const size_t heap_statistics_buffer_byte_length = sizeof(*env->heap_statistics_buffer()) * kHeapStatisticsPropertiesCount; @@ -149,7 +149,7 @@ void InitializeV8Bindings(Local target, UpdateHeapSpaceStatisticsBuffer); env->set_heap_space_statistics_buffer( - new uint32_t[kHeapSpaceStatisticsPropertiesCount * number_of_heap_spaces]); + new double[kHeapSpaceStatisticsPropertiesCount * number_of_heap_spaces]); const size_t heap_space_statistics_buffer_byte_length = sizeof(*env->heap_space_statistics_buffer()) * From e7b656db6eb3929d3faf05afcdc07b9cbb6beb77 Mon Sep 17 00:00:00 2001 From: Anna Henningsen Date: Sun, 18 Sep 2016 11:16:45 +0200 Subject: [PATCH 045/291] Revert "repl: disable Ctrl+C support on win32 for now" This reverts commit f59b8888f12b491c69cc5be6f812414d50b1ec36 now that the libuv update containing the proper fix has landed in 63243bcb330408d511b3945c53719425d8b7abb8. Ref: https://github.com/libuv/libuv/pull/1054 Ref: https://github.com/nodejs/node/issues/7837 PR-URL: https://github.com/nodejs/node/pull/8645 Reviewed-By: Nikolai Vavilov Reviewed-By: James M Snell Reviewed-By: Bartosz Sosnowski Reviewed-By: Colin Ihrig --- lib/repl.js | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/lib/repl.js b/lib/repl.js index 858ccd883850d3..b3258e75e56733 100644 --- a/lib/repl.js +++ b/lib/repl.js @@ -322,13 +322,7 @@ function REPLServer(prompt, if (!err) { // Unset raw mode during evaluation so that Ctrl+C raises a signal. let previouslyInRawMode; - - // Temporarily disabled on Windows due to output problems that likely - // result from the raw mode switches here, see - // https://github.com/nodejs/node/issues/7837 - // Setting NODE_REPL_CTRLC is meant as a temporary opt-in for debugging. - if (self.breakEvalOnSigint && - (process.platform !== 'win32' || process.env.NODE_REPL_CTRLC)) { + if (self.breakEvalOnSigint) { // Start the SIGINT watchdog before entering raw mode so that a very // quick Ctrl+C doesn’t lead to aborting the process completely. utilBinding.startSigintWatchdog(); @@ -348,8 +342,7 @@ function REPLServer(prompt, result = script.runInContext(context, scriptOptions); } } finally { - if (self.breakEvalOnSigint && - (process.platform !== 'win32' || process.env.NODE_REPL_CTRLC)) { + if (self.breakEvalOnSigint) { // Reset terminal mode to its previous value. self._setRawMode(previouslyInRawMode); From 656ba86a2767dcfec3471c8f567b36b1775ab5a3 Mon Sep 17 00:00:00 2001 From: Eugene Ostroukhov Date: Wed, 28 Dec 2016 15:00:46 -0800 Subject: [PATCH 046/291] test: fix Coverity warning in inspector test PR-URL: https://github.com/nodejs/node/pull/10510 Reviewed-By: James M Snell Reviewed-By: Colin Ihrig --- test/cctest/test_inspector_socket_server.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/cctest/test_inspector_socket_server.cc b/test/cctest/test_inspector_socket_server.cc index 2bbc3811390fe6..136bf796ae51dc 100644 --- a/test/cctest/test_inspector_socket_server.cc +++ b/test/cctest/test_inspector_socket_server.cc @@ -70,7 +70,7 @@ class Timeout { class InspectorSocketServerTest : public ::testing::Test { protected: void SetUp() override { - uv_loop_init(&loop); + EXPECT_EQ(0, uv_loop_init(&loop)); } void TearDown() override { From 2b01138451d08e62ed6a47d4d4175ede686ab259 Mon Sep 17 00:00:00 2001 From: Joyee Cheung Date: Sat, 31 Dec 2016 14:20:10 +0800 Subject: [PATCH 047/291] url: TupleOrigin#toString use unicode by default See: https://url.spec.whatwg.org/#dom-url-origin Also moves the tests for origins to the parsing tests since now URL#origin matches the test cases by default. PR-URL: https://github.com/nodejs/node/pull/10552 Reviewed-By: James M Snell --- lib/internal/url.js | 5 +-- test/parallel/test-whatwg-url-origin-for.js | 19 ---------- test/parallel/test-whatwg-url-parsing.js | 39 ++++++++++++--------- 3 files changed, 25 insertions(+), 38 deletions(-) delete mode 100644 test/parallel/test-whatwg-url-origin-for.js diff --git a/lib/internal/url.js b/lib/internal/url.js index e1e1c515f842d2..6ada5db3d80613 100644 --- a/lib/internal/url.js +++ b/lib/internal/url.js @@ -66,7 +66,8 @@ class TupleOrigin { return this[kDomain] || this[kHost]; } - toString(unicode = false) { + // https://url.spec.whatwg.org/#dom-url-origin + toString(unicode = true) { var result = this[kScheme]; result += '://'; result += unicode ? domainToUnicode(this[kHost]) : this[kHost]; @@ -325,7 +326,7 @@ Object.defineProperties(URL.prototype, { enumerable: true, configurable: true, get() { - return originFor(this).toString(true); + return originFor(this).toString(); } }, protocol: { diff --git a/test/parallel/test-whatwg-url-origin-for.js b/test/parallel/test-whatwg-url-origin-for.js deleted file mode 100644 index 9e015f80510148..00000000000000 --- a/test/parallel/test-whatwg-url-origin-for.js +++ /dev/null @@ -1,19 +0,0 @@ -'use strict'; - -const common = require('../common'); - -const originFor = require('url').originFor; -const path = require('path'); -const assert = require('assert'); -const tests = require(path.join(common.fixturesDir, 'url-tests.json')); - -for (const test of tests) { - if (typeof test === 'string') - continue; - - if (test.origin) { - const origin = originFor(test.input, test.base); - // Pass true to origin.toString() to enable unicode serialization. - assert.strictEqual(origin.toString(true), test.origin); - } -} diff --git a/test/parallel/test-whatwg-url-parsing.js b/test/parallel/test-whatwg-url-parsing.js index ae14d1ff5060bf..c83d30da414571 100644 --- a/test/parallel/test-whatwg-url-parsing.js +++ b/test/parallel/test-whatwg-url-parsing.js @@ -13,17 +13,30 @@ const path = require('path'); const assert = require('assert'); const tests = require(path.join(common.fixturesDir, 'url-tests.json')); +function verifyURL(url, test) { + if (test.href) assert.strictEqual(url.href, test.href); + if (test.origin) assert.strictEqual(url.origin, test.origin); + if (test.protocol) assert.strictEqual(url.protocol, test.protocol); + if (test.username) assert.strictEqual(url.username, test.username); + if (test.password) assert.strictEqual(url.password, test.password); + if (test.hostname) assert.strictEqual(url.hostname, test.hostname); + if (test.host) assert.strictEqual(url.host, test.host); + if (test.port !== undefined) assert.strictEqual(url.port, test.port); + if (test.pathname) assert.strictEqual(url.pathname, test.pathname); + if (test.search) assert.strictEqual(url.search, test.search); + if (test.hash) assert.strictEqual(url.hash, test.hash); +} + for (const test of tests) { if (typeof test === 'string') continue; if (test.failure) { - assert.throws(() => new URL(test.input, test.base), /Invalid URL/); + assert.throws(() => new URL(test.input, test.base), + /^TypeError: Invalid URL$/); } else { - assert.doesNotThrow(() => { - const url = new URL(test.input, test.base); - assert.strictEqual(url.href, test.href); - }); + const url = new URL(test.input, test.base); + verifyURL(url, test); } } @@ -115,18 +128,10 @@ const additional_tests = [ } ]; -additional_tests.forEach((test) => { - const u = new URL(test.url); - if (test.protocol) assert.strictEqual(test.protocol, u.protocol); - if (test.username) assert.strictEqual(test.username, u.username); - if (test.password) assert.strictEqual(test.password, u.password); - if (test.hostname) assert.strictEqual(test.hostname, u.hostname); - if (test.host) assert.strictEqual(test.host, u.host); - if (test.port !== undefined) assert.strictEqual(test.port, u.port); - if (test.pathname) assert.strictEqual(test.pathname, u.pathname); - if (test.search) assert.strictEqual(test.search, u.search); - if (test.hash) assert.strictEqual(test.hash, u.hash); -}); +for (const test of additional_tests) { + const url = new URL(test.url); + verifyURL(url, test); +} // test inspect const allTests = additional_tests.slice(); From 58bb263438d6d4d4d175582945687c0a46072ca1 Mon Sep 17 00:00:00 2001 From: Myles Borins Date: Mon, 2 Jan 2017 23:29:56 -0500 Subject: [PATCH 048/291] doc: update TheAlphaNerd to MylesBorins MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit new year new alias PR-URL: https://github.com/nodejs/node/pull/10586 Reviewed-By: Franziska Hinkelmann Reviewed-By: Jeremiah Senkpiel Reviewed-By: James M Snell Reviewed-By: Anna Henningsen Reviewed-By: Gibson Fahnestock Reviewed-By: Sakthipriyan Vairamani Reviewed-By: Michaël Zasso --- README.md | 4 ++-- doc/onboarding-extras.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 4b92a194e3f3de..1cc6eb11dc053b 100644 --- a/README.md +++ b/README.md @@ -178,6 +178,8 @@ more information about the governance of the Node.js project, see **Julien Gilli** <jgilli@nodejs.org> * [mscdex](https://github.com/mscdex) - **Brian White** <mscdex@mscdex.net> +* [MylesBorins](https://github.com/MylesBorins) - +**Myles Borins** <myles.borins@gmail.com> * [ofrobots](https://github.com/ofrobots) - **Ali Ijaz Sheikh** <ofrobots@google.com> * [rvagg](https://github.com/rvagg) - @@ -186,8 +188,6 @@ more information about the governance of the Node.js project, see **Shigeki Ohtsu** <ohtsu@iij.ad.jp> * [targos](https://github.com/targos) - **Michaël Zasso** <targos@protonmail.com> -* [TheAlphaNerd](https://github.com/TheAlphaNerd) - -**Myles Borins** <myles.borins@gmail.com> * [thefourtheye](https://github.com/thefourtheye) - **Sakthipriyan Vairamani** <thechargingvolcano@gmail.com> * [trevnorris](https://github.com/trevnorris) - diff --git a/doc/onboarding-extras.md b/doc/onboarding-extras.md index a0fa985a92b35a..ced9e538c938fc 100644 --- a/doc/onboarding-extras.md +++ b/doc/onboarding-extras.md @@ -27,7 +27,7 @@ | `tools/eslint`, `.eslintrc` | @silverwind, @trott | | async_hooks | @nodejs/diagnostics | | upgrading V8 | @nodejs/v8, @nodejs/post-mortem | -| upgrading npm | @fishrock123, @thealphanerd | +| upgrading npm | @fishrock123, @MylesBorins | | upgrading c-ares | @jbergstroem | | upgrading http-parser | @jbergstroem, @nodejs/http | | upgrading libuv | @saghul | From b2d0c44fb1ef6951ca9dab66a139d9a79308106f Mon Sep 17 00:00:00 2001 From: Kai Cataldo Date: Mon, 2 Jan 2017 16:50:04 -0500 Subject: [PATCH 049/291] assert: update comments Remove the numbers from the comments to make it clear that assert does not follow the [CJS spec](http://wiki.commonjs.org/wiki/Unit_Testing/1.0). Additionally, clean up the existing comments for consistent formatting/language and ease of reading. PR-URL: https://github.com/nodejs/node/pull/10579 Fixes: https://github.com/nodejs/node/issues/9063 Reviewed-By: Rich Trott Reviewed-By: James M Snell Reviewed-By: Benjamin Gruenbaum Reviewed-By: Michael Dawson --- lib/assert.js | 74 +++++++++++++++++++++++++++++---------------------- 1 file changed, 42 insertions(+), 32 deletions(-) diff --git a/lib/assert.js b/lib/assert.js index 04c5cb5ad436e1..892df6d9a0f4e2 100644 --- a/lib/assert.js +++ b/lib/assert.js @@ -30,16 +30,16 @@ const util = require('util'); const Buffer = require('buffer').Buffer; const pToString = (obj) => Object.prototype.toString.call(obj); -// 1. The assert module provides functions that throw +// The assert module provides functions that throw // AssertionError's when particular conditions are not met. The // assert module must conform to the following interface. const assert = module.exports = ok; -// 2. The AssertionError is defined in assert. +// The AssertionError is defined in assert. // new assert.AssertionError({ message: message, // actual: actual, -// expected: expected }) +// expected: expected }); assert.AssertionError = function AssertionError(options) { this.name = 'AssertionError'; @@ -75,7 +75,7 @@ function getMessage(self) { // other keys to the AssertionError's constructor - they will be // ignored. -// 3. All of the following functions must throw an AssertionError +// All of the following functions must throw an AssertionError // when a corresponding condition is not met, with a message that // may be undefined if not provided. All assertion methods provide // both the actual and expected values to the assertion error for @@ -94,7 +94,7 @@ function fail(actual, expected, message, operator, stackStartFunction) { // EXTENSION! allows for well behaved errors defined elsewhere. assert.fail = fail; -// 4. Pure assertion tests whether a value is truthy, as determined +// Pure assertion tests whether a value is truthy, as determined // by !!guard. // assert.ok(guard, message_opt); // This statement is equivalent to assert.equal(true, !!guard, @@ -106,7 +106,7 @@ function ok(value, message) { } assert.ok = ok; -// 5. The equality assertion tests shallow, coercive equality with +// The equality assertion tests shallow, coercive equality with // ==. // assert.equal(actual, expected, message_opt); @@ -114,8 +114,9 @@ assert.equal = function equal(actual, expected, message) { if (actual != expected) fail(actual, expected, message, '==', assert.equal); }; -// 6. The non-equality assertion tests for whether two objects are not equal -// with != assert.notEqual(actual, expected, message_opt); +// The non-equality assertion tests for whether two objects are not +// equal with !=. +// assert.notEqual(actual, expected, message_opt); assert.notEqual = function notEqual(actual, expected, message) { if (actual == expected) { @@ -123,7 +124,7 @@ assert.notEqual = function notEqual(actual, expected, message) { } }; -// 7. The equivalence assertion tests a deep equality relation. +// The equivalence assertion tests a deep equality relation. // assert.deepEqual(actual, expected, message_opt); /* eslint-disable no-restricted-properties */ @@ -141,18 +142,22 @@ assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) { }; function _deepEqual(actual, expected, strict, memos) { - // 7.1. All identical values are equivalent, as determined by ===. + // All identical values are equivalent, as determined by ===. if (actual === expected) { return true; + + // If both values are instances of buffers, equivalence is + // determined by comparing the values and ensuring the result + // === 0. } else if (actual instanceof Buffer && expected instanceof Buffer) { return compare(actual, expected) === 0; - // 7.2. If the expected value is a Date object, the actual value is + // If the expected value is a Date object, the actual value is // equivalent if it is also a Date object that refers to the same time. } else if (util.isDate(actual) && util.isDate(expected)) { return actual.getTime() === expected.getTime(); - // 7.3 If the expected value is a RegExp object, the actual value is + // If the expected value is a RegExp object, the actual value is // equivalent if it is also a RegExp object with the same source and // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). } else if (util.isRegExp(actual) && util.isRegExp(expected)) { @@ -162,18 +167,18 @@ function _deepEqual(actual, expected, strict, memos) { actual.lastIndex === expected.lastIndex && actual.ignoreCase === expected.ignoreCase; - // 7.4. Other pairs that do not both pass typeof value == 'object', - // equivalence is determined by ==. + // If both values are primitives, equivalence is determined by + // == or, if checking for strict equivalence, ===. } else if ((actual === null || typeof actual !== 'object') && (expected === null || typeof expected !== 'object')) { return strict ? actual === expected : actual == expected; // If both values are instances of typed arrays, wrap their underlying - // ArrayBuffers in a Buffer each to increase performance + // ArrayBuffers in a Buffer to increase performance. // This optimization requires the arrays to have the same type as checked by - // Object.prototype.toString (aka pToString). Never perform binary - // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their - // bit patterns are not identical. + // Object.prototype.toString (pToString). Never perform binary + // comparisons for Float*Arrays, though, since +0 === -0 is true despite the + // two values' bit patterns not being identical. } else if (ArrayBuffer.isView(actual) && ArrayBuffer.isView(expected) && pToString(actual) === pToString(expected) && !(actual instanceof Float32Array || @@ -185,7 +190,7 @@ function _deepEqual(actual, expected, strict, memos) { expected.byteOffset, expected.byteLength)) === 0; - // 7.5 For all other Object pairs, including Array objects, equivalence is + // For all other Object pairs, including Array objects, equivalence is // determined by having the same number of owned properties (as verified // with Object.prototype.hasOwnProperty.call), the same set of keys // (although not necessarily the same order), equivalent values for every @@ -215,7 +220,8 @@ function isArguments(object) { function objEquiv(a, b, strict, actualVisitedObjects) { if (a === null || a === undefined || b === null || b === undefined) return false; - // if one is a primitive, the other must be same + + // If one is a primitive, the other must be the same. if (util.isPrimitive(a) || util.isPrimitive(b)) return a === b; if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) @@ -227,20 +233,23 @@ function objEquiv(a, b, strict, actualVisitedObjects) { const ka = Object.keys(a); const kb = Object.keys(b); var key, i; - // having the same number of owned properties (keys incorporates - // hasOwnProperty) + + // The pair must have the same number of owned properties (keys + // incorporates hasOwnProperty). if (ka.length !== kb.length) return false; - //the same set of keys (although not necessarily the same order), + + // The pair must have the same set of keys (although not + // necessarily in the same order). ka.sort(); kb.sort(); - //~~~cheap key test + // Cheap key test: for (i = ka.length - 1; i >= 0; i--) { if (ka[i] !== kb[i]) return false; } - //equivalent values for every corresponding key, and - //~~~possibly expensive deep test + // The pair must have equivalent values for every corresponding key. + // Possibly expensive deep test: for (i = ka.length - 1; i >= 0; i--) { key = ka[i]; if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects)) @@ -249,7 +258,7 @@ function objEquiv(a, b, strict, actualVisitedObjects) { return true; } -// 8. The non-equivalence assertion tests for any deep inequality. +// The non-equivalence assertion tests for any deep inequality. // assert.notDeepEqual(actual, expected, message_opt); assert.notDeepEqual = function notDeepEqual(actual, expected, message) { @@ -266,7 +275,7 @@ function notDeepStrictEqual(actual, expected, message) { } -// 9. The strict equality assertion tests strict equality, as determined by ===. +// The strict equality assertion tests strict equality, as determined by ===. // assert.strictEqual(actual, expected, message_opt); assert.strictEqual = function strictEqual(actual, expected, message) { @@ -275,8 +284,9 @@ assert.strictEqual = function strictEqual(actual, expected, message) { } }; -// 10. The strict non-equality assertion tests for strict inequality, as -// determined by !==. assert.notStrictEqual(actual, expected, message_opt); +// The strict non-equality assertion tests for strict inequality, as +// determined by !==. +// assert.notStrictEqual(actual, expected, message_opt); assert.notStrictEqual = function notStrictEqual(actual, expected, message) { if (actual === expected) { @@ -298,7 +308,7 @@ function expectedException(actual, expected) { return true; } } catch (e) { - // Ignore. The instanceof check doesn't work for arrow functions. + // Ignore. The instanceof check doesn't work for arrow functions. } if (Error.isPrototypeOf(expected)) { @@ -356,7 +366,7 @@ function _throws(shouldThrow, block, expected, message) { } } -// 11. Expected to throw an error: +// Expected to throw an error. // assert.throws(block, Error_opt, message_opt); assert.throws = function throws(block, /*optional*/error, /*optional*/message) { From d628f3a227d8a76708e94d7acee70dbcbc0d85d2 Mon Sep 17 00:00:00 2001 From: Teddy Katz Date: Sun, 1 Jan 2017 19:42:19 -0500 Subject: [PATCH 050/291] util: avoid out-of-bounds arguments index access This updates util.inspect() to avoid accessing out-of-range indices of the `arguments` object, which is known to cause optimization bailout. Based on an average of 10 runs of the benchmark in `benchmark/util/inspect.js`, this change improves the performance of `util.inspect` by about 10%. Relates to https://github.com/nodejs/node/issues/10323 PR-URL: https://github.com/nodejs/node/pull/10569 Reviewed-By: Colin Ihrig Reviewed-By: Evan Lucas Reviewed-By: Brian White Reviewed-By: Jackson Tian Reviewed-By: Jeremiah Senkpiel Reviewed-By: James M Snell --- lib/util.js | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/lib/util.js b/lib/util.js index 37008b2d176062..85af547ebb81f7 100644 --- a/lib/util.js +++ b/lib/util.js @@ -173,8 +173,12 @@ function inspect(obj, opts) { stylize: stylizeNoColor }; // legacy... - if (arguments[2] !== undefined) ctx.depth = arguments[2]; - if (arguments[3] !== undefined) ctx.colors = arguments[3]; + if (arguments.length >= 3 && arguments[2] !== undefined) { + ctx.depth = arguments[2]; + } + if (arguments.length >= 4 && arguments[3] !== undefined) { + ctx.colors = arguments[3]; + } if (typeof opts === 'boolean') { // legacy... ctx.showHidden = opts; From d19136da84780003570ecffc378a2e4ce2beef1e Mon Sep 17 00:00:00 2001 From: Brian White Date: Sat, 24 Dec 2016 23:27:46 -0500 Subject: [PATCH 051/291] benchmark: move punycode benchmark out of net punycode/ICU is not specific to any particular module, so move it to a more generic location. PR-URL: https://github.com/nodejs/node/pull/10446 Reviewed-By: James M Snell --- benchmark/{net => misc}/punycode.js | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename benchmark/{net => misc}/punycode.js (100%) diff --git a/benchmark/net/punycode.js b/benchmark/misc/punycode.js similarity index 100% rename from benchmark/net/punycode.js rename to benchmark/misc/punycode.js From 372e3eeb4bb45203562ec9f1e4189a094949dd14 Mon Sep 17 00:00:00 2001 From: Brian White Date: Sat, 24 Dec 2016 23:29:22 -0500 Subject: [PATCH 052/291] benchmark: improve readability of net benchmarks PR-URL: https://github.com/nodejs/node/pull/10446 Reviewed-By: James M Snell --- benchmark/net/net-c2s.js | 20 ++++++++++---------- benchmark/net/net-pipe.js | 20 ++++++++++---------- benchmark/net/net-s2c.js | 20 ++++++++++---------- 3 files changed, 30 insertions(+), 30 deletions(-) diff --git a/benchmark/net/net-c2s.js b/benchmark/net/net-c2s.js index 9b4df2f5a79fe7..7e59bc528b681c 100644 --- a/benchmark/net/net-c2s.js +++ b/benchmark/net/net-c2s.js @@ -65,8 +65,17 @@ Writer.prototype.emit = function() {}; Writer.prototype.prependListener = function() {}; +function flow() { + var dest = this.dest; + var res = dest.write(chunk, encoding); + if (!res) + dest.once('drain', this.flow); + else + process.nextTick(this.flow); +} + function Reader() { - this.flow = this.flow.bind(this); + this.flow = flow.bind(this); this.readable = true; } @@ -76,15 +85,6 @@ Reader.prototype.pipe = function(dest) { return dest; }; -Reader.prototype.flow = function() { - var dest = this.dest; - var res = dest.write(chunk, encoding); - if (!res) - dest.once('drain', this.flow); - else - process.nextTick(this.flow); -}; - function server() { var reader = new Reader(); diff --git a/benchmark/net/net-pipe.js b/benchmark/net/net-pipe.js index 03db348878ede0..7d4849c4ef7bbb 100644 --- a/benchmark/net/net-pipe.js +++ b/benchmark/net/net-pipe.js @@ -65,8 +65,17 @@ Writer.prototype.emit = function() {}; Writer.prototype.prependListener = function() {}; +function flow() { + var dest = this.dest; + var res = dest.write(chunk, encoding); + if (!res) + dest.once('drain', this.flow); + else + process.nextTick(this.flow); +} + function Reader() { - this.flow = this.flow.bind(this); + this.flow = flow.bind(this); this.readable = true; } @@ -76,15 +85,6 @@ Reader.prototype.pipe = function(dest) { return dest; }; -Reader.prototype.flow = function() { - var dest = this.dest; - var res = dest.write(chunk, encoding); - if (!res) - dest.once('drain', this.flow); - else - process.nextTick(this.flow); -}; - function server() { var reader = new Reader(); diff --git a/benchmark/net/net-s2c.js b/benchmark/net/net-s2c.js index 469b66a25a3ee4..a4a5b4ab4987a0 100644 --- a/benchmark/net/net-s2c.js +++ b/benchmark/net/net-s2c.js @@ -65,8 +65,17 @@ Writer.prototype.emit = function() {}; Writer.prototype.prependListener = function() {}; +function flow() { + var dest = this.dest; + var res = dest.write(chunk, encoding); + if (!res) + dest.once('drain', this.flow); + else + process.nextTick(this.flow); +} + function Reader() { - this.flow = this.flow.bind(this); + this.flow = flow.bind(this); this.readable = true; } @@ -76,15 +85,6 @@ Reader.prototype.pipe = function(dest) { return dest; }; -Reader.prototype.flow = function() { - var dest = this.dest; - var res = dest.write(chunk, encoding); - if (!res) - dest.once('drain', this.flow); - else - process.nextTick(this.flow); -}; - function server() { var reader = new Reader(); From 2f4577c07d027164c5b072ceda7039b16230b54a Mon Sep 17 00:00:00 2001 From: Brian White Date: Sat, 31 Dec 2016 21:50:25 -0500 Subject: [PATCH 053/291] benchmark: keep decimals in results Some benchmarks' results are small values, so keeping decimals when running them manually (not comparing) can be helpful. PR-URL: https://github.com/nodejs/node/pull/10559 Reviewed-By: James M Snell --- benchmark/common.js | 5 +++-- benchmark/run.js | 5 +++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/benchmark/common.js b/benchmark/common.js index 9e7253504f9e7e..4ce9501dd9cff7 100644 --- a/benchmark/common.js +++ b/benchmark/common.js @@ -195,8 +195,9 @@ function formatResult(data) { conf += ' ' + key + '=' + JSON.stringify(data.conf[key]); } - const rate = Math.floor(data.rate) - .toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1,'); + var rate = data.rate.toString().split('.'); + rate[0] = rate[0].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1,'); + rate = (rate[1] ? rate.join('.') : rate[0]); return `${data.name}${conf}: ${rate}`; } diff --git a/benchmark/run.js b/benchmark/run.js index 52ce74024e1ae4..198406622803c5 100644 --- a/benchmark/run.js +++ b/benchmark/run.js @@ -56,8 +56,9 @@ if (format === 'csv') { conf = conf.replace(/"/g, '""'); console.log(`"${data.name}", "${conf}", ${data.rate}, ${data.time}`); } else { - const rate = Math.floor(data.rate) - .toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1,'); + var rate = data.rate.toString().split('.'); + rate[0] = rate[0].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1,'); + rate = (rate[1] ? rate.join('.') : rate[0]); console.log(`${data.name} ${conf}: ${rate}`); } }); From ded17579e50a70dc2339fc594df288f8a17ab790 Mon Sep 17 00:00:00 2001 From: Brian White Date: Mon, 2 Jan 2017 03:17:21 -0500 Subject: [PATCH 054/291] events: improve removeListener() performance array.shift() seems to be faster than arrayClone() when the item to remove is at the front (at least with V8 5.4). PR-URL: https://github.com/nodejs/node/pull/10572 Reviewed-By: Benjamin Gruenbaum Reviewed-By: James M Snell Reviewed-By: Michael Dawson --- lib/events.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lib/events.js b/lib/events.js index 6a8345ab7bc516..209700e65ad596 100644 --- a/lib/events.js +++ b/lib/events.js @@ -360,6 +360,8 @@ EventEmitter.prototype.removeListener = } else { delete events[type]; } + } else if (position === 0) { + list.shift(); } else { spliceOne(list, position); } From 59196af646aef9600a96843b623a416d085950c6 Mon Sep 17 00:00:00 2001 From: Brian White Date: Mon, 2 Jan 2017 18:37:26 -0500 Subject: [PATCH 055/291] stream: avoid additional validation for Buffers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit These changes result in ~50% improvement in the included benchmark. PR-URL: https://github.com/nodejs/node/pull/10580 Reviewed-By: Сковорода Никита Андреевич Reviewed-By: Matteo Collina Reviewed-By: James M Snell --- benchmark/streams/writable-manywrites.js | 23 +++++++++++++++ lib/_stream_writable.js | 37 +++++++++++------------- 2 files changed, 40 insertions(+), 20 deletions(-) create mode 100644 benchmark/streams/writable-manywrites.js diff --git a/benchmark/streams/writable-manywrites.js b/benchmark/streams/writable-manywrites.js new file mode 100644 index 00000000000000..fadafe86e4cf70 --- /dev/null +++ b/benchmark/streams/writable-manywrites.js @@ -0,0 +1,23 @@ +'use strict'; + +const common = require('../common'); +const Writable = require('stream').Writable; + +const bench = common.createBenchmark(main, { + n: [2e6] +}); + +function main(conf) { + const n = +conf.n; + const b = Buffer.allocUnsafe(1024); + const s = new Writable(); + s._write = function(chunk, encoding, cb) { + cb(); + }; + + bench.start(); + for (var k = 0; k < n; ++k) { + s.write(b); + } + bench.end(n); +} diff --git a/lib/_stream_writable.js b/lib/_stream_writable.js index b20fe8d2ea91ed..ba56225d974fe9 100644 --- a/lib/_stream_writable.js +++ b/lib/_stream_writable.js @@ -194,23 +194,18 @@ function writeAfterEnd(stream, cb) { process.nextTick(cb, er); } -// If we get something that is not a buffer, string, null, or undefined, -// and we're not in objectMode, then that's an error. -// Otherwise stream chunks are all considered to be of length=1, and the -// watermarks determine how many objects to keep in the buffer, rather than -// how many bytes or characters. +// Checks that a user-supplied chunk is valid, especially for the particular +// mode the stream is in. Currently this means that `null` is never accepted +// and undefined/non-string values are only allowed in object mode. function validChunk(stream, state, chunk, cb) { var valid = true; var er = false; - // Always throw error if a null is written - // if we are not in object mode then throw - // if it is not a buffer, string, or undefined. + if (chunk === null) { er = new TypeError('May not write null values to stream'); - } else if (!(chunk instanceof Buffer) && - typeof chunk !== 'string' && - chunk !== undefined && - !state.objectMode) { + } else if (typeof chunk !== 'string' && + chunk !== undefined && + !state.objectMode) { er = new TypeError('Invalid non-string/buffer chunk'); } if (er) { @@ -224,13 +219,14 @@ function validChunk(stream, state, chunk, cb) { Writable.prototype.write = function(chunk, encoding, cb) { var state = this._writableState; var ret = false; + var isBuf = (chunk instanceof Buffer); if (typeof encoding === 'function') { cb = encoding; encoding = null; } - if (chunk instanceof Buffer) + if (isBuf) encoding = 'buffer'; else if (!encoding) encoding = state.defaultEncoding; @@ -240,9 +236,9 @@ Writable.prototype.write = function(chunk, encoding, cb) { if (state.ended) writeAfterEnd(this, cb); - else if (validChunk(this, state, chunk, cb)) { + else if (isBuf || validChunk(this, state, chunk, cb)) { state.pendingcb++; - ret = writeOrBuffer(this, state, chunk, encoding, cb); + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); } return ret; @@ -291,11 +287,12 @@ function decodeChunk(state, chunk, encoding) { // if we're already writing something, then just put this // in the queue, and wait our turn. Otherwise, call _write // If we return false, then we need a drain event, so set that flag. -function writeOrBuffer(stream, state, chunk, encoding, cb) { - chunk = decodeChunk(state, chunk, encoding); - - if (chunk instanceof Buffer) - encoding = 'buffer'; +function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + chunk = decodeChunk(state, chunk, encoding); + if (chunk instanceof Buffer) + encoding = 'buffer'; + } var len = state.objectMode ? 1 : chunk.length; state.length += len; From cf875d17f3f468d4cabf432644a62ee808f23241 Mon Sep 17 00:00:00 2001 From: Adrian Estrada Date: Fri, 30 Dec 2016 09:47:55 -0500 Subject: [PATCH 056/291] test: improve test-fs-null-bytes * use const instead of var * use common.mustCall to control functions execution * use assert.strictEqual instead of assert.equal * use arrow functions * remove console.error PR-URL: https://github.com/nodejs/node/pull/10521 Reviewed-By: Prince John Wesley Reviewed-By: Colin Ihrig Reviewed-By: James M Snell Reviewed-By: Luigi Pinca --- test/parallel/test-fs-null-bytes.js | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/test/parallel/test-fs-null-bytes.js b/test/parallel/test-fs-null-bytes.js index 3c70d2953ca0f4..e04aa1cb76cb6f 100644 --- a/test/parallel/test-fs-null-bytes.js +++ b/test/parallel/test-fs-null-bytes.js @@ -4,16 +4,15 @@ var assert = require('assert'); var fs = require('fs'); function check(async, sync) { - var expected = /Path must be a string without null bytes/; - var argsSync = Array.prototype.slice.call(arguments, 2); - var argsAsync = argsSync.concat(function(er) { + const expected = /Path must be a string without null bytes/; + const argsSync = Array.prototype.slice.call(arguments, 2); + const argsAsync = argsSync.concat((er) => { assert(er && er.message.match(expected)); - assert.equal(er.code, 'ENOENT'); + assert.strictEqual(er.code, 'ENOENT'); }); if (sync) - assert.throws(function() { - console.error(sync.name, argsSync); + assert.throws(() => { sync.apply(null, argsSync); }, expected); @@ -51,7 +50,7 @@ check(fs.writeFile, fs.writeFileSync, 'foo\u0000bar'); // an 'error' for exists means that it doesn't exist. // one of many reasons why this file is the absolute worst. -fs.exists('foo\u0000bar', function(exists) { +fs.exists('foo\u0000bar', common.mustCall((exists) => { assert(!exists); -}); +})); assert(!fs.existsSync('foo\u0000bar')); From a77940c2d57f2f0cb600ab58d59833abea4d1e7b Mon Sep 17 00:00:00 2001 From: Michael Dawson Date: Wed, 4 Jan 2017 15:33:46 -0500 Subject: [PATCH 057/291] test: mark test-tty-wrap as flaky for AIX We have had https://github.com/nodejs/node/issues/9728 open for a while but the frequency of the failures seems to be such that we should mark it as flaky while we continue to investigate. PR-URL: https://github.com/nodejs/node/pull/10618 Reviewed-by: Colin Ihrig Reviewed-By: Rich Trott Reviewed-By: Sakthipriyan Vairamani Reviewed-By: James M Snell --- test/pseudo-tty/pseudo-tty.status | 2 ++ 1 file changed, 2 insertions(+) diff --git a/test/pseudo-tty/pseudo-tty.status b/test/pseudo-tty/pseudo-tty.status index e16bb28cd7be61..50f54de029d874 100644 --- a/test/pseudo-tty/pseudo-tty.status +++ b/test/pseudo-tty/pseudo-tty.status @@ -4,3 +4,5 @@ prefix pseudo-tty # test issue only, covered under https://github.com/nodejs/node/issues/7973 no_dropped_stdio : SKIP no_interleaved_stdio : SKIP +# being investigated under https://github.com/nodejs/node/issues/9728 +test-tty-wrap : FAIL, PASS From 5cca69320f9b6228d9e24ae7eefbf3852c8af8fb Mon Sep 17 00:00:00 2001 From: Victor Felder Date: Mon, 2 Jan 2017 22:28:04 +0100 Subject: [PATCH 058/291] events: avoid emit() eager deopt This commit makes sure EventEmitter.emit() doesn't get deoptimized by V8. The deopt happens when accessing out of bound indexes of the `arguments` object. This issue has been raised here: #10323 and this specific case might become a more serious performance issue in upcoming V8 releases. PR-URL: https://github.com/nodejs/node/pull/10568 Reviewed-By: Benjamin Gruenbaum Reviewed-By: Colin Ihrig Reviewed-By: Evan Lucas Reviewed-By: Jeremiah Senkpiel Reviewed-By: James M Snell Reviewed-By: Michael Dawson --- lib/events.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/events.js b/lib/events.js index 209700e65ad596..000fa98d5a88c5 100644 --- a/lib/events.js +++ b/lib/events.js @@ -148,7 +148,8 @@ EventEmitter.prototype.emit = function emit(type) { // If there is no 'error' event listener then throw. if (doError) { - er = arguments[1]; + if (arguments.length > 1) + er = arguments[1]; if (domain) { if (!er) er = new Error('Uncaught, unspecified "error" event'); From 4f96272f12a0ba18c7967455da66eb924c5cfe23 Mon Sep 17 00:00:00 2001 From: Victor Felder Date: Mon, 2 Jan 2017 22:32:21 +0100 Subject: [PATCH 059/291] benchmark: fix typo "categoty" -> "category" PR-URL: https://github.com/nodejs/node/pull/10568 Reviewed-By: Benjamin Gruenbaum Reviewed-By: Colin Ihrig Reviewed-By: Evan Lucas Reviewed-By: Jeremiah Senkpiel Reviewed-By: James M Snell Reviewed-By: Michael Dawson --- benchmark/run.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/benchmark/run.js b/benchmark/run.js index 198406622803c5..c04824866710a8 100644 --- a/benchmark/run.js +++ b/benchmark/run.js @@ -6,7 +6,7 @@ const CLI = require('./_cli.js'); const cli = CLI(`usage: ./node run.js [options] [--] ... Run each benchmark in the directory a single time, more than one - directory can be specified. + directory can be specified. --filter pattern string to filter benchmark scripts --set variable=value set benchmark variable (can be repeated) From f380a5fb5aee13272251ade9e6ff8d5077c71b87 Mon Sep 17 00:00:00 2001 From: Anna Henningsen Date: Thu, 5 Jan 2017 19:04:01 +0100 Subject: [PATCH 060/291] doc: mention cc-ing nodejs/python team for reviews Add the nodejs/python github team to the table of people to /cc for reviews on python code. PR-URL: https://github.com/nodejs/node/pull/10637 Reviewed-By: Jeremiah Senkpiel Reviewed-By: James M Snell Reviewed-By: Sakthipriyan Vairamani Reviewed-By: Michael Dawson Reviewed-By: Luigi Pinca Reviewed-By: Gibson Fahnestock --- doc/onboarding-extras.md | 1 + 1 file changed, 1 insertion(+) diff --git a/doc/onboarding-extras.md b/doc/onboarding-extras.md index ced9e538c938fc..1b5d082434fd71 100644 --- a/doc/onboarding-extras.md +++ b/doc/onboarding-extras.md @@ -31,6 +31,7 @@ | upgrading c-ares | @jbergstroem | | upgrading http-parser | @jbergstroem, @nodejs/http | | upgrading libuv | @saghul | +| python code | @nodejs/python | | platform specific | @nodejs/platform-{aix,arm,freebsd,macos,ppc,smartos,s390,windows} | From e46bdcf2bb55f517da8983c11eae478b5fbe5230 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Tue, 3 Jan 2017 21:29:47 -0800 Subject: [PATCH 061/291] url: change null password handling Pulls in new URL parsing tests from w3c web-platform-tests and updates null password handling. Refs: https://github.com/w3c/web-platform-tests/commit/e0012406859014e8f31dbaf12122d0cd10249db4 Refs: https://github.com/whatwg/url/pull/186 PR-URL: https://github.com/nodejs/node/pull/10601 Fixes: https://github.com/nodejs/node/issues/10595 Reviewed-By: Michal Zasso Reviewed-By: Italo A. Casas Reviewed-By: Colin Ihrig --- lib/internal/url.js | 3 +- test/fixtures/url-tests.json | 68 +++++++++++++++++++++++++++++++++--- 2 files changed, 66 insertions(+), 5 deletions(-) diff --git a/lib/internal/url.js b/lib/internal/url.js index 6ada5db3d80613..9815d035a15676 100644 --- a/lib/internal/url.js +++ b/lib/internal/url.js @@ -285,7 +285,8 @@ Object.defineProperties(URL.prototype, { if (ctx.host !== undefined) { ret += '//'; const has_username = typeof ctx.username === 'string'; - const has_password = typeof ctx.password === 'string'; + const has_password = typeof ctx.password === 'string' && + ctx.password !== ''; if (has_username || has_password) { if (has_username) ret += ctx.username; diff --git a/test/fixtures/url-tests.json b/test/fixtures/url-tests.json index 44d665b99f5bb6..1ba3e6ee4ba86f 100644 --- a/test/fixtures/url-tests.json +++ b/test/fixtures/url-tests.json @@ -32,6 +32,66 @@ "search": "?b", "hash": "#c" }, + { + "input": "https://test:@test", + "base": "about:blank", + "href": "https://test@test/", + "origin": "https://test", + "protocol": "https:", + "username": "test", + "password": "", + "host": "test", + "hostname": "test", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "https://:@test", + "base": "about:blank", + "href": "https://test/", + "origin": "https://test", + "protocol": "https:", + "username": "", + "password": "", + "host": "test", + "hostname": "test", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "non-special://test:@test/x", + "base": "about:blank", + "href": "non-special://test@test/x", + "origin": "null", + "protocol": "non-special:", + "username": "test", + "password": "", + "host": "test", + "hostname": "test", + "port": "", + "pathname": "/x", + "search": "", + "hash": "" + }, + { + "input": "non-special://:@test/x", + "base": "about:blank", + "href": "non-special://test/x", + "origin": "null", + "protocol": "non-special:", + "username": "", + "password": "", + "host": "test", + "hostname": "test", + "port": "", + "pathname": "/x", + "search": "", + "hash": "" + }, { "input": "http:foo.com", "base": "http://example.org/foo/bar", @@ -3098,7 +3158,7 @@ { "input": "http:a:@www.example.com", "base": "about:blank", - "href": "http://a:@www.example.com/", + "href": "http://a@www.example.com/", "origin": "http://www.example.com", "protocol": "http:", "username": "a", @@ -3113,7 +3173,7 @@ { "input": "http:/a:@www.example.com", "base": "about:blank", - "href": "http://a:@www.example.com/", + "href": "http://a@www.example.com/", "origin": "http://www.example.com", "protocol": "http:", "username": "a", @@ -3128,7 +3188,7 @@ { "input": "http://a:@www.example.com", "base": "about:blank", - "href": "http://a:@www.example.com/", + "href": "http://a@www.example.com/", "origin": "http://www.example.com", "protocol": "http:", "username": "a", @@ -3173,7 +3233,7 @@ { "input": "http://:@www.example.com", "base": "about:blank", - "href": "http://:@www.example.com/", + "href": "http://www.example.com/", "origin": "http://www.example.com", "protocol": "http:", "username": "", From 824978e33766d8b55ef9a3f203ecbdcea6affd94 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Tue, 3 Jan 2017 21:39:08 -0800 Subject: [PATCH 062/291] url: do not decode arbitrary %2e sequences in paths Per a recent change to the URL spec, arbitrary %2e sequences in URL paths that are not single or double dot segments are not to be decoded. Refs: https://github.com/whatwg/url/issues/87 Refs: https://github.com/whatwg/url/pull/156 Refs: https://github.com/w3c/web-platform-tests/commit/d93247d5cb7d70f80da8b154a171f4e3d50969f4 Fixes: https://github.com/nodejs/node/issues/10598 PR-URL: https://github.com/nodejs/node/pull/10602 Reviewed-By: Michal Zasso Reviewed-By: Italo A. Casas Reviewed-By: Benjamin Gruenbaum Reviewed-By: Colin Ihrig --- src/node_url.cc | 7 +------ test/fixtures/url-setter-tests.json | 10 +++++----- test/fixtures/url-tests.json | 12 ++++++------ 3 files changed, 12 insertions(+), 17 deletions(-) diff --git a/src/node_url.cc b/src/node_url.cc index 11a03ea5211a89..538126eb872b2a 100644 --- a/src/node_url.cc +++ b/src/node_url.cc @@ -1214,12 +1214,7 @@ namespace url { state = kFragment; } } else { - if (ch == '%' && p[1] == '2' && TO_LOWER(p[2]) == 'e') { - buffer += '.'; - p += 2; - } else { - AppendOrEscape(&buffer, ch, DefaultEncodeSet); - } + AppendOrEscape(&buffer, ch, DefaultEncodeSet); } break; case kCannotBeBase: diff --git a/test/fixtures/url-setter-tests.json b/test/fixtures/url-setter-tests.json index e3a163e788301e..56a1c00a86fd45 100644 --- a/test/fixtures/url-setter-tests.json +++ b/test/fixtures/url-setter-tests.json @@ -953,8 +953,8 @@ "href": "view-source+http://example.net/home?lang=fr#nav", "new_value": "\\a\\%2E\\b\\%2e.\\c", "expected": { - "href": "view-source+http://example.net/\\a\\.\\b\\..\\c?lang=fr#nav", - "pathname": "/\\a\\.\\b\\..\\c" + "href": "view-source+http://example.net/\\a\\%2E\\b\\%2e.\\c?lang=fr#nav", + "pathname": "/\\a\\%2E\\b\\%2e.\\c" } }, { @@ -967,12 +967,12 @@ } }, { - "comment": "Bytes already percent-encoded are left as-is, except %2E.", + "comment": "Bytes already percent-encoded are left as-is, including %2E outside dotted segments.", "href": "http://example.net", "new_value": "%2e%2E%c3%89té", "expected": { - "href": "http://example.net/..%c3%89t%C3%A9", - "pathname": "/..%c3%89t%C3%A9" + "href": "http://example.net/%2e%2E%c3%89t%C3%A9", + "pathname": "/%2e%2E%c3%89t%C3%A9" } }, { diff --git a/test/fixtures/url-tests.json b/test/fixtures/url-tests.json index 1ba3e6ee4ba86f..634a8e3f663985 100644 --- a/test/fixtures/url-tests.json +++ b/test/fixtures/url-tests.json @@ -1847,7 +1847,7 @@ { "input": "http://example.com/foo/%2e%2", "base": "about:blank", - "href": "http://example.com/foo/.%2", + "href": "http://example.com/foo/%2e%2", "origin": "http://example.com", "protocol": "http:", "username": "", @@ -1855,14 +1855,14 @@ "host": "example.com", "hostname": "example.com", "port": "", - "pathname": "/foo/.%2", + "pathname": "/foo/%2e%2", "search": "", "hash": "" }, { "input": "http://example.com/foo/%2e./%2e%2e/.%2e/%2e.bar", "base": "about:blank", - "href": "http://example.com/..bar", + "href": "http://example.com/%2e.bar", "origin": "http://example.com", "protocol": "http:", "username": "", @@ -1870,7 +1870,7 @@ "host": "example.com", "hostname": "example.com", "port": "", - "pathname": "/..bar", + "pathname": "/%2e.bar", "search": "", "hash": "" }, @@ -2288,7 +2288,7 @@ { "input": "http://www/foo%2Ehtml", "base": "about:blank", - "href": "http://www/foo.html", + "href": "http://www/foo%2Ehtml", "origin": "http://www", "protocol": "http:", "username": "", @@ -2296,7 +2296,7 @@ "host": "www", "hostname": "www", "port": "", - "pathname": "/foo.html", + "pathname": "/foo%2Ehtml", "search": "", "hash": "" }, From de8eee6b1630b989000fd394500398d013510ba8 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Tue, 3 Jan 2017 22:14:59 -0800 Subject: [PATCH 063/291] meta: decharter the http working group Fixes: https://github.com/nodejs/CTC/issues/41 PR-URL: https://github.com/nodejs/node/pull/10604 Fixes: https://github.com/nodejs/CTC#41 Reviewed-By: Evan Lucas Reviewed-By: Sakthipriyan Vairamani Reviewed-By: Michal Zasso Reviewed-By: Colin Ihrig --- WORKING_GROUPS.md | 16 ---------------- 1 file changed, 16 deletions(-) diff --git a/WORKING_GROUPS.md b/WORKING_GROUPS.md index 0367165a81a5d2..6ba06c9cafa697 100644 --- a/WORKING_GROUPS.md +++ b/WORKING_GROUPS.md @@ -42,7 +42,6 @@ Top Level Working Group](https://github.com/nodejs/TSC/blob/master/WORKING_GROUP * [Benchmarking](#benchmarking) * [Post-mortem](#post-mortem) * [Intl](#intl) -* [HTTP](#http) * [Documentation](#documentation) * [Testing](#testing) @@ -189,21 +188,6 @@ Responsibilities include: * Publishing regular update summaries and other promotional content. -### [HTTP](https://github.com/nodejs/http) - -The HTTP Working Group is chartered for the support and improvement of the -HTTP implementation in Node.js. - -Responsibilities include: -* Addressing HTTP issues on the Node.js issue tracker. -* Authoring and editing HTTP documentation within the Node.js project. -* Reviewing changes to HTTP functionality within the Node.js project. -* Working with the ecosystem of HTTP related module developers to evolve the - HTTP implementation and APIs in core. -* Advising the CTC on all HTTP related issues and discussions. -* Messaging about the future of HTTP to give the community advance notice of - changes. - ### [Docker](https://github.com/nodejs/docker-iojs) The Docker Working Group's purpose is to build, maintain, and improve official From 736b95a61748a7887b48a4b53a31918824967b2b Mon Sep 17 00:00:00 2001 From: Anna Henningsen Date: Wed, 4 Jan 2017 17:27:22 +0100 Subject: [PATCH 064/291] test: check error and cleanups in test-fs-read-buffer Use arrow functions and prefer `strictEqual` over `deepStrictEqual` where it works. PR-URL: https://github.com/nodejs/node/pull/10611 Reviewed-By: Colin Ihrig Reviewed-By: James M Snell Reviewed-By: Sakthipriyan Vairamani Reviewed-By: Rich Trott Reviewed-By: Benjamin Gruenbaum --- test/parallel/test-fs-read-buffer.js | 1 + test/parallel/test-fs-write-buffer.js | 24 ++++++++++++------------ 2 files changed, 13 insertions(+), 12 deletions(-) diff --git a/test/parallel/test-fs-read-buffer.js b/test/parallel/test-fs-read-buffer.js index 82fb3c284fb98a..733be5ba0db4c6 100644 --- a/test/parallel/test-fs-read-buffer.js +++ b/test/parallel/test-fs-read-buffer.js @@ -16,6 +16,7 @@ function test(bufferAsync, bufferSync, expected) { expected.length, 0, common.mustCall((err, bytesRead) => { + assert.ifError(err); assert.strictEqual(bytesRead, expected.length); assert.deepStrictEqual(bufferAsync, Buffer.from(expected)); })); diff --git a/test/parallel/test-fs-write-buffer.js b/test/parallel/test-fs-write-buffer.js index 0e24f33872825f..927ebb15412bc8 100644 --- a/test/parallel/test-fs-write-buffer.js +++ b/test/parallel/test-fs-write-buffer.js @@ -10,17 +10,17 @@ common.refreshTmpDir(); // fs.write with all parameters provided: { const filename = path.join(common.tmpDir, 'write1.txt'); - fs.open(filename, 'w', 0o644, common.mustCall(function(err, fd) { + fs.open(filename, 'w', 0o644, common.mustCall((err, fd) => { assert.ifError(err); - const cb = common.mustCall(function(err, written) { + const cb = common.mustCall((err, written) => { assert.ifError(err); assert.strictEqual(expected.length, written); fs.closeSync(fd); var found = fs.readFileSync(filename, 'utf8'); - assert.deepStrictEqual(expected.toString(), found); + assert.strictEqual(expected.toString(), found); }); fs.write(fd, expected, 0, expected.length, null, cb); @@ -30,17 +30,17 @@ common.refreshTmpDir(); // fs.write with a buffer, without the length parameter: { const filename = path.join(common.tmpDir, 'write2.txt'); - fs.open(filename, 'w', 0o644, common.mustCall(function(err, fd) { + fs.open(filename, 'w', 0o644, common.mustCall((err, fd) => { assert.ifError(err); - const cb = common.mustCall(function(err, written) { + const cb = common.mustCall((err, written) => { assert.ifError(err); assert.strictEqual(2, written); fs.closeSync(fd); const found = fs.readFileSync(filename, 'utf8'); - assert.deepStrictEqual('lo', found); + assert.strictEqual('lo', found); }); fs.write(fd, Buffer.from('hello'), 3, cb); @@ -90,17 +90,17 @@ common.refreshTmpDir(); // fs.write with offset and length passed as undefined followed by the callback: { const filename = path.join(common.tmpDir, 'write5.txt'); - fs.open(filename, 'w', 0o644, common.mustCall(function(err, fd) { + fs.open(filename, 'w', 0o644, common.mustCall((err, fd) => { assert.ifError(err); - const cb = common.mustCall(function(err, written) { + const cb = common.mustCall((err, written) => { assert.ifError(err); assert.strictEqual(expected.length, written); fs.closeSync(fd); const found = fs.readFileSync(filename, 'utf8'); - assert.deepStrictEqual(expected.toString(), found); + assert.strictEqual(expected.toString(), found); }); fs.write(fd, expected, undefined, undefined, cb); @@ -110,17 +110,17 @@ common.refreshTmpDir(); // fs.write with a Uint8Array, without the offset and length parameters: { const filename = path.join(common.tmpDir, 'write6.txt'); - fs.open(filename, 'w', 0o644, common.mustCall(function(err, fd) { + fs.open(filename, 'w', 0o644, common.mustCall((err, fd) => { assert.ifError(err); - const cb = common.mustCall(function(err, written) { + const cb = common.mustCall((err, written) => { assert.ifError(err); assert.strictEqual(expected.length, written); fs.closeSync(fd); const found = fs.readFileSync(filename, 'utf8'); - assert.deepStrictEqual(expected.toString(), found); + assert.strictEqual(expected.toString(), found); }); fs.write(fd, Uint8Array.from(expected), cb); From 75aa6050ab05f07d71a5995d5f7156d02d1a1006 Mon Sep 17 00:00:00 2001 From: Evan Torrie Date: Sun, 4 Dec 2016 17:51:51 -0800 Subject: [PATCH 065/291] http: eliminate capture of ClientRequest in Agent Keepalive sockets that are returned to the agent's freesocket pool were previously capturing a reference to the ClientRequest that initiated the request. This commit eliminates that by moving the installation of the socket listeners to a different function. PR-URL: https://github.com/nodejs/node/pull/10134 Reviewed-By: Colin Ihrig Reviewed-By: Ben Noordhuis Reviewed-By: Evan Lucas Reviewed-By: James M Snell --- lib/_http_agent.js | 56 +++++++++++++++++++++++++--------------------- 1 file changed, 30 insertions(+), 26 deletions(-) diff --git a/lib/_http_agent.js b/lib/_http_agent.js index 2a07cd25e26dd9..eebdb242463b5d 100644 --- a/lib/_http_agent.js +++ b/lib/_http_agent.js @@ -206,36 +206,40 @@ Agent.prototype.createSocket = function createSocket(req, options, cb) { } self.sockets[name].push(s); debug('sockets', name, self.sockets[name].length); - - function onFree() { - self.emit('free', s, options); - } - s.on('free', onFree); - - function onClose(err) { - debug('CLIENT socket onClose'); - // This is the only place where sockets get removed from the Agent. - // If you want to remove a socket from the pool, just close it. - // All socket errors end in a close event anyway. - self.removeSocket(s, options); - } - s.on('close', onClose); - - function onRemove() { - // We need this function for cases like HTTP 'upgrade' - // (defined by WebSockets) where we need to remove a socket from the - // pool because it'll be locked up indefinitely - debug('CLIENT socket onRemove'); - self.removeSocket(s, options); - s.removeListener('close', onClose); - s.removeListener('free', onFree); - s.removeListener('agentRemove', onRemove); - } - s.on('agentRemove', onRemove); + installListeners(self, s, options); cb(null, s); } }; +function installListeners(agent, s, options) { + function onFree() { + debug('CLIENT socket onFree'); + agent.emit('free', s, options); + } + s.on('free', onFree); + + function onClose(err) { + debug('CLIENT socket onClose'); + // This is the only place where sockets get removed from the Agent. + // If you want to remove a socket from the pool, just close it. + // All socket errors end in a close event anyway. + agent.removeSocket(s, options); + } + s.on('close', onClose); + + function onRemove() { + // We need this function for cases like HTTP 'upgrade' + // (defined by WebSockets) where we need to remove a socket from the + // pool because it'll be locked up indefinitely + debug('CLIENT socket onRemove'); + agent.removeSocket(s, options); + s.removeListener('close', onClose); + s.removeListener('free', onFree); + s.removeListener('agentRemove', onRemove); + } + s.on('agentRemove', onRemove); +} + Agent.prototype.removeSocket = function removeSocket(s, options) { var name = this.getName(options); debug('removeSocket', name, 'writable:', s.writable); From 06a82436c2455fef1b1bf1a0971cc4d79cb8e4ef Mon Sep 17 00:00:00 2001 From: Adrian Estrada Date: Fri, 6 Jan 2017 12:52:23 -0500 Subject: [PATCH 066/291] test: improve test-event-emitter-modify-in-emit * use let instead of var * use assert.strictEqual instead of assert.equal * swap assertions arguments to match the standard PR-URL: https://github.com/nodejs/node/pull/10600 Reviewed-By: Colin Ihrig Reviewed-By: Luigi Pinca Reviewed-By: James M Snell --- .../test-event-emitter-modify-in-emit.js | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/test/parallel/test-event-emitter-modify-in-emit.js b/test/parallel/test-event-emitter-modify-in-emit.js index 7864438fff4df6..c13fad4347d617 100644 --- a/test/parallel/test-event-emitter-modify-in-emit.js +++ b/test/parallel/test-event-emitter-modify-in-emit.js @@ -3,7 +3,7 @@ require('../common'); const assert = require('assert'); const events = require('events'); -var callbacks_called = []; +let callbacks_called = []; const e = new events.EventEmitter(); @@ -25,27 +25,27 @@ function callback3() { } e.on('foo', callback1); -assert.equal(1, e.listeners('foo').length); +assert.strictEqual(e.listeners('foo').length, 1); e.emit('foo'); -assert.equal(2, e.listeners('foo').length); +assert.strictEqual(e.listeners('foo').length, 2); assert.deepStrictEqual(['callback1'], callbacks_called); e.emit('foo'); -assert.equal(0, e.listeners('foo').length); +assert.strictEqual(e.listeners('foo').length, 0); assert.deepStrictEqual(['callback1', 'callback2', 'callback3'], callbacks_called); e.emit('foo'); -assert.equal(0, e.listeners('foo').length); +assert.strictEqual(e.listeners('foo').length, 0); assert.deepStrictEqual(['callback1', 'callback2', 'callback3'], callbacks_called); e.on('foo', callback1); e.on('foo', callback2); -assert.equal(2, e.listeners('foo').length); +assert.strictEqual(e.listeners('foo').length, 2); e.removeAllListeners('foo'); -assert.equal(0, e.listeners('foo').length); +assert.strictEqual(e.listeners('foo').length, 0); // Verify that removing callbacks while in emit allows emits to propagate to // all listeners @@ -53,7 +53,7 @@ callbacks_called = []; e.on('foo', callback2); e.on('foo', callback3); -assert.equal(2, e.listeners('foo').length); +assert.strictEqual(2, e.listeners('foo').length); e.emit('foo'); assert.deepStrictEqual(['callback2', 'callback3'], callbacks_called); -assert.equal(0, e.listeners('foo').length); +assert.strictEqual(0, e.listeners('foo').length); From f0de955220b1b2c3be757f542a9b07d35cfc16b4 Mon Sep 17 00:00:00 2001 From: Daniel Bevenius Date: Wed, 28 Dec 2016 09:08:07 +0100 Subject: [PATCH 067/291] src: reduce test_inspector_socket_server output Currently, when test/cctest/test_inspector_socket_server.cc is run there is output written to stderr by src/inspector_socket_server.cc which is interleaved with the gtest report: Debugger listening on port 9229. Warning: This is an experimental feature and could change at any time. To start debugging, open the following URLs in Chrome: ... The goal of this commit is to remove the above logged information by introducing an out_ member in the InspectorSocketServer class which defaults to stderr (keeping the current behavior). Setting out_ to NULL is supported in which case nothing will be written and is what the test has been configured with. When working on specific test case the appropriate output stream can be specified for the ServerHolder constructor to limit logging to that test case. PR-URL: https://github.com/nodejs/node/pull/10537 Reviewed-By: James M Snell Reviewed-By: Eugene Ostroukhov Reviewed-By: Colin Ihrig --- src/inspector_socket_server.cc | 39 +++++++++++++-------- src/inspector_socket_server.h | 5 ++- test/cctest/test_inspector_socket_server.cc | 4 +-- 3 files changed, 30 insertions(+), 18 deletions(-) diff --git a/src/inspector_socket_server.cc b/src/inspector_socket_server.cc index 4bd35ae8bed4fb..723f8f0b72c2b0 100644 --- a/src/inspector_socket_server.cc +++ b/src/inspector_socket_server.cc @@ -74,22 +74,27 @@ void OnBufferAlloc(uv_handle_t* handle, size_t len, uv_buf_t* buf) { buf->len = len; } -void PrintDebuggerReadyMessage(int port, const std::vector& ids) { - fprintf(stderr, +void PrintDebuggerReadyMessage(int port, + const std::vector& ids, + FILE* out) { + if (out == NULL) { + return; + } + fprintf(out, "Debugger listening on port %d.\n" "Warning: This is an experimental feature " "and could change at any time.\n", port); if (ids.size() == 1) - fprintf(stderr, "To start debugging, open the following URL in Chrome:\n"); + fprintf(out, "To start debugging, open the following URL in Chrome:\n"); if (ids.size() > 1) - fprintf(stderr, "To start debugging, open the following URLs in Chrome:\n"); + fprintf(out, "To start debugging, open the following URLs in Chrome:\n"); for (const std::string& id : ids) { - fprintf(stderr, + fprintf(out, " chrome-devtools://devtools/bundled/inspector.html?" "experiments=true&v8only=true&ws=%s\n", GetWsUrl(port, id).c_str()); } - fflush(stderr); + fflush(out); } void SendHttpResponse(InspectorSocket* socket, const std::string& response) { @@ -207,12 +212,14 @@ class SocketSession { }; InspectorSocketServer::InspectorSocketServer(SocketServerDelegate* delegate, - int port) : loop_(nullptr), - delegate_(delegate), - port_(port), - server_(uv_tcp_t()), - closer_(nullptr), - next_session_id_(0) { } + int port, + FILE* out) : loop_(nullptr), + delegate_(delegate), + port_(port), + server_(uv_tcp_t()), + closer_(nullptr), + next_session_id_(0), + out_(out) { } // static @@ -260,7 +267,7 @@ void InspectorSocketServer::SessionTerminated(int session_id) { delegate_->EndSession(session_id); if (connected_sessions_.empty() && uv_is_active(reinterpret_cast(&server_))) { - PrintDebuggerReadyMessage(port_, delegate_->GetTargetIds()); + PrintDebuggerReadyMessage(port_, delegate_->GetTargetIds(), out_); } } @@ -337,10 +344,12 @@ bool InspectorSocketServer::Start(uv_loop_t* loop) { SocketConnectedCallback); } if (err == 0 && connected_sessions_.empty()) { - PrintDebuggerReadyMessage(port_, delegate_->GetTargetIds()); + PrintDebuggerReadyMessage(port_, delegate_->GetTargetIds(), out_); } if (err != 0 && connected_sessions_.empty()) { - fprintf(stderr, "Unable to open devtools socket: %s\n", uv_strerror(err)); + if (out_ != NULL) { + fprintf(out_, "Unable to open devtools socket: %s\n", uv_strerror(err)); + } uv_close(reinterpret_cast(&server_), nullptr); return false; } diff --git a/src/inspector_socket_server.h b/src/inspector_socket_server.h index 4c139e138f7547..d498c882a928d9 100644 --- a/src/inspector_socket_server.h +++ b/src/inspector_socket_server.h @@ -32,7 +32,9 @@ class SocketServerDelegate { class InspectorSocketServer { public: using ServerCallback = void (*)(InspectorSocketServer*); - InspectorSocketServer(SocketServerDelegate* delegate, int port); + InspectorSocketServer(SocketServerDelegate* delegate, + int port, + FILE* out = stderr); bool Start(uv_loop_t* loop); void Stop(ServerCallback callback); void Send(int session_id, const std::string& message); @@ -66,6 +68,7 @@ class InspectorSocketServer { Closer* closer_; std::map connected_sessions_; int next_session_id_; + FILE* out_; friend class SocketSession; friend class Closer; diff --git a/test/cctest/test_inspector_socket_server.cc b/test/cctest/test_inspector_socket_server.cc index 136bf796ae51dc..3c19661f97408b 100644 --- a/test/cctest/test_inspector_socket_server.cc +++ b/test/cctest/test_inspector_socket_server.cc @@ -300,9 +300,9 @@ class SocketWrapper { class ServerHolder { public: template - ServerHolder(Delegate* delegate, int port) + ServerHolder(Delegate* delegate, int port, FILE* out = NULL) : closed(false), paused(false), sessions_terminated(false), - server_(delegate, port) { + server_(delegate, port, out) { delegate->Connect(&server_); } From 1634a7017e9b46dcd2510937f0dfddf958bcbd0e Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Sat, 31 Dec 2016 21:51:03 -0800 Subject: [PATCH 068/291] tools: remove custom align-function-arguments rule ESLint `indent` rule now has options that duplicate functionality in our custom `align-function-arguments` rule. Remove `align-function-arguments` custom rule. PR-URL: https://github.com/nodejs/node/pull/10561 Reviewed-By: Teddy Katz Reviewed-By: James M Snell Reviewed-By: Sam Roberts --- .eslintrc | 1 - .../eslint-rules/align-function-arguments.js | 76 ------------------- 2 files changed, 77 deletions(-) delete mode 100644 tools/eslint-rules/align-function-arguments.js diff --git a/.eslintrc b/.eslintrc index 0aed06ca55f5c3..812637821841ce 100644 --- a/.eslintrc +++ b/.eslintrc @@ -120,7 +120,6 @@ rules: template-curly-spacing: 2 # Custom rules in tools/eslint-rules - align-function-arguments: 2 align-multiline-assignment: 2 assert-fail-single-argument: 2 assert-throws-arguments: [2, { requireTwo: false }] diff --git a/tools/eslint-rules/align-function-arguments.js b/tools/eslint-rules/align-function-arguments.js deleted file mode 100644 index 015552489a9d44..00000000000000 --- a/tools/eslint-rules/align-function-arguments.js +++ /dev/null @@ -1,76 +0,0 @@ -/** - * @fileoverview Align arguments in multiline function calls - * @author Rich Trott - */ -'use strict'; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -function checkArgumentAlignment(context, node) { - - function isNodeFirstInLine(node, byEndLocation) { - const firstToken = byEndLocation === true ? context.getLastToken(node, 1) : - context.getTokenBefore(node); - const startLine = byEndLocation === true ? node.loc.end.line : - node.loc.start.line; - const endLine = firstToken ? firstToken.loc.end.line : -1; - - return startLine !== endLine; - } - - if (node.arguments.length === 0) - return; - - var msg = ''; - const first = node.arguments[0]; - var currentLine = first.loc.start.line; - const firstColumn = first.loc.start.column; - - const ignoreTypes = [ - 'ArrowFunctionExpression', - 'FunctionExpression', - 'ObjectExpression', - ]; - - const args = node.arguments; - - // For now, don't bother trying to validate potentially complicating things - // like closures. Different people will have very different ideas and it's - // probably best to implement configuration options. - if (args.some((node) => { return ignoreTypes.indexOf(node.type) !== -1; })) { - return; - } - - if (!isNodeFirstInLine(node)) { - return; - } - - var misaligned; - - args.slice(1).forEach((argument) => { - if (!misaligned) { - if (argument.loc.start.line === currentLine + 1) { - if (argument.loc.start.column !== firstColumn) { - if (isNodeFirstInLine(argument)) { - msg = 'Function argument in column ' + - `${argument.loc.start.column + 1}, ` + - `expected in ${firstColumn + 1}`; - misaligned = argument; - } - } - } - } - currentLine = argument.loc.start.line; - }); - - if (msg) - context.report(misaligned, msg); -} - -module.exports = function(context) { - return { - 'CallExpression': (node) => checkArgumentAlignment(context, node) - }; -}; From 891874406ae7dced25d815acc2b2d059a794b771 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Sat, 31 Dec 2016 21:52:56 -0800 Subject: [PATCH 069/291] tools: remove no-useless-regex-char-class-escape The `no-useless-regex-char-class-escape` custom lint rule was introduced as a less aggressive alternative to some enhancements that were introduced into ESLint. Those enhancements were blocking us from updating ESLint. However, they have since been relaxed and the custom rule is no longer needed. Remove it. PR-URL: https://github.com/nodejs/node/pull/10561 Reviewed-By: Teddy Katz Reviewed-By: James M Snell Reviewed-By: Sam Roberts --- .eslintrc | 1 - .../no-useless-regex-char-class-escape.js | 190 ------------------ 2 files changed, 191 deletions(-) delete mode 100644 tools/eslint-rules/no-useless-regex-char-class-escape.js diff --git a/.eslintrc b/.eslintrc index 812637821841ce..d2cc8ea000ac3f 100644 --- a/.eslintrc +++ b/.eslintrc @@ -124,7 +124,6 @@ rules: assert-fail-single-argument: 2 assert-throws-arguments: [2, { requireTwo: false }] new-with-error: [2, Error, RangeError, TypeError, SyntaxError, ReferenceError] - no-useless-regex-char-class-escape: [2, { override: ['[', ']'] }] # Global scoped method and vars globals: diff --git a/tools/eslint-rules/no-useless-regex-char-class-escape.js b/tools/eslint-rules/no-useless-regex-char-class-escape.js deleted file mode 100644 index e18077098daee2..00000000000000 --- a/tools/eslint-rules/no-useless-regex-char-class-escape.js +++ /dev/null @@ -1,190 +0,0 @@ -/** - * @fileoverview Disallow useless escape in regex character class - * Based on 'no-useless-escape' rule - */ -'use strict'; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -const REGEX_CHARCLASS_ESCAPES = new Set('\\bcdDfnrsStvwWxu0123456789]'); - -/** - * Parses a regular expression into a list of regex character class list. - * @param {string} regExpText raw text used to create the regular expression - * @returns {Object[]} A list of character classes tokens with index and - * escape info - * @example - * - * parseRegExpCharClass('a\\b[cd-]') - * - * returns: - * [ - * { - * empty: false, - * start: 4, - * end: 6, - * chars: [ - * {text: 'c', index: 4, escaped: false}, - * {text: 'd', index: 5, escaped: false}, - * {text: '-', index: 6, escaped: false} - * ] - * } - * ] - */ - -function parseRegExpCharClass(regExpText) { - const charList = []; - let charListIdx = -1; - const initState = { - escapeNextChar: false, - inCharClass: false, - startingCharClass: false - }; - - regExpText.split('').reduce((state, char, index) => { - if (!state.escapeNextChar) { - if (char === '\\') { - return Object.assign(state, { escapeNextChar: true }); - } - if (char === '[' && !state.inCharClass) { - charListIdx += 1; - charList.push({ start: index + 1, chars: [], end: -1 }); - return Object.assign(state, { - inCharClass: true, - startingCharClass: true - }); - } - if (char === ']' && state.inCharClass) { - const charClass = charList[charListIdx]; - charClass.empty = charClass.chars.length === 0; - if (charClass.empty) { - charClass.start = charClass.end = -1; - } else { - charList[charListIdx].end = index - 1; - } - return Object.assign(state, { - inCharClass: false, - startingCharClass: false - }); - } - } - if (state.inCharClass) { - charList[charListIdx].chars.push({ - text: char, - index, escaped: - state.escapeNextChar - }); - } - return Object.assign(state, { - escapeNextChar: false, - startingCharClass: false - }); - }, initState); - - return charList; -} - -module.exports = { - meta: { - docs: { - description: 'disallow unnecessary regex characer class escape sequences', - category: 'Best Practices', - recommended: false - }, - fixable: 'code', - schema: [{ - 'type': 'object', - 'properties': { - 'override': { - 'type': 'array', - 'items': { 'type': 'string' }, - 'uniqueItems': true - } - }, - 'additionalProperties': false - }] - }, - - create(context) { - const overrideSet = new Set(context.options.length ? - context.options[0].override || [] : - []); - - /** - * Reports a node - * @param {ASTNode} node The node to report - * @param {number} startOffset The backslash's offset - * from the start of the node - * @param {string} character The uselessly escaped character - * (not including the backslash) - * @returns {void} - */ - function report(node, startOffset, character) { - context.report({ - node, - loc: { - line: node.loc.start.line, - column: node.loc.start.column + startOffset - }, - message: 'Unnecessary regex escape in character' + - ' class: \\{{character}}', - data: { character }, - fix: (fixer) => { - const start = node.range[0] + startOffset; - return fixer.replaceTextRange([start, start + 1], ''); - } - }); - } - - /** - * Checks if a node has superflous escape character - * in regex character class. - * - * @param {ASTNode} node - node to check. - * @returns {void} - */ - function check(node) { - if (node.regex) { - parseRegExpCharClass(node.regex.pattern) - .forEach((charClass) => { - charClass - .chars - // The '-' character is a special case if is not at - // either edge of the character class. To account for this, - // filter out '-' characters that appear in the middle of a - // character class. - .filter((charInfo) => !(charInfo.text === '-' && - (charInfo.index !== charClass.start && - charInfo.index !== charClass.end))) - - // The '^' character is a special case if it's at the beginning - // of the character class. To account for this, filter out '^' - // characters that appear at the start of a character class. - // - .filter((charInfo) => !(charInfo.text === '^' && - charInfo.index === charClass.start)) - - // Filter out characters that aren't escaped. - .filter((charInfo) => charInfo.escaped) - - // Filter out characters that are valid to escape, based on - // their position in the regular expression. - .filter((charInfo) => !REGEX_CHARCLASS_ESCAPES.has(charInfo.text)) - - // Filter out overridden character list. - .filter((charInfo) => !overrideSet.has(charInfo.text)) - - // Report all the remaining characters. - .forEach((charInfo) => - report(node, charInfo.index, charInfo.text)); - }); - } - } - - return { - Literal: check - }; - } -}; From 09f35a49e376cc6c8b5a74faa5b04517aa6fd3be Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Fri, 4 Nov 2016 14:04:00 -0700 Subject: [PATCH 070/291] test: provide duration/interval to timers There are places in the code base where setTimeout() or setInterval() are called with just a callback and no duration/interval. The timers module will use a value of `1` in that situation. An unspecified duration or interval can be confusing. Did the original author forget to provide a value? Did they intend to use setImmediate() or process.nextTick() instead of setTimeout()? And so on. This change provides a duration or interval of `1` to all calls in the codebase where it is missing. `parallel/test-timers.js` still tests the situation where `setTimeout()` and `setInterval()` are called with `undefined` and other non-numeric values for the duration/interval. PR-URL: https://github.com/nodejs/node/pull/9472 Reviewed-By: Teddy Katz Reviewed-By: James M Snell --- test/message/timeout_throw.js | 2 +- test/parallel/test-handle-wrap-close-abort.js | 2 +- test/parallel/test-stream-end-paused.js | 2 +- test/parallel/test-stream-readable-event.js | 6 +++--- test/parallel/test-stream2-large-read-stall.js | 2 +- test/parallel/test-stream2-readable-non-empty-end.js | 4 ++-- 6 files changed, 9 insertions(+), 9 deletions(-) diff --git a/test/message/timeout_throw.js b/test/message/timeout_throw.js index 14291fabd12565..4008f306fe58be 100644 --- a/test/message/timeout_throw.js +++ b/test/message/timeout_throw.js @@ -4,4 +4,4 @@ require('../common'); setTimeout(function() { // eslint-disable-next-line no-undef undefined_reference_error_maker; -}); +}, 1); diff --git a/test/parallel/test-handle-wrap-close-abort.js b/test/parallel/test-handle-wrap-close-abort.js index 5355e65df60821..e9f69195ad29cd 100644 --- a/test/parallel/test-handle-wrap-close-abort.js +++ b/test/parallel/test-handle-wrap-close-abort.js @@ -13,4 +13,4 @@ setTimeout(function() { setTimeout(function() { throw new Error('setTimeout'); }, 1); -}); +}, 1); diff --git a/test/parallel/test-stream-end-paused.js b/test/parallel/test-stream-end-paused.js index 3c46d49ea65d65..4b585fdb999890 100644 --- a/test/parallel/test-stream-end-paused.js +++ b/test/parallel/test-stream-end-paused.js @@ -21,7 +21,7 @@ stream.pause(); setTimeout(common.mustCall(function() { stream.on('end', common.mustCall(function() {})); stream.resume(); -})); +}), 1); process.on('exit', function() { assert(calledRead); diff --git a/test/parallel/test-stream-readable-event.js b/test/parallel/test-stream-readable-event.js index a20fc2ee732d0f..a8536bdcbab861 100644 --- a/test/parallel/test-stream-readable-event.js +++ b/test/parallel/test-stream-readable-event.js @@ -20,7 +20,7 @@ const Readable = require('stream').Readable; // we're testing what we think we are assert(!r._readableState.reading); r.on('readable', common.mustCall(function() {})); - }); + }, 1); } { @@ -40,7 +40,7 @@ const Readable = require('stream').Readable; // assert we're testing what we think we are assert(r._readableState.reading); r.on('readable', common.mustCall(function() {})); - }); + }, 1); } { @@ -60,5 +60,5 @@ const Readable = require('stream').Readable; // assert we're testing what we think we are assert(!r._readableState.reading); r.on('readable', common.mustCall(function() {})); - }); + }, 1); } diff --git a/test/parallel/test-stream2-large-read-stall.js b/test/parallel/test-stream2-large-read-stall.js index 823407d396afb6..a2ae3f5174272d 100644 --- a/test/parallel/test-stream2-large-read-stall.js +++ b/test/parallel/test-stream2-large-read-stall.js @@ -46,7 +46,7 @@ function push() { console.error(' push #%d', pushes); if (r.push(Buffer.allocUnsafe(PUSHSIZE))) - setTimeout(push); + setTimeout(push, 1); } process.on('exit', function() { diff --git a/test/parallel/test-stream2-readable-non-empty-end.js b/test/parallel/test-stream2-readable-non-empty-end.js index c08cc287ce1cbf..dd2cb8d51055c7 100644 --- a/test/parallel/test-stream2-readable-non-empty-end.js +++ b/test/parallel/test-stream2-readable-non-empty-end.js @@ -16,7 +16,7 @@ test._read = function(size) { var chunk = chunks[n++]; setTimeout(function() { test.push(chunk === undefined ? null : chunk); - }); + }, 1); }; test.on('end', thrower); @@ -31,7 +31,7 @@ test.on('readable', function() { if (res) { bytesread += res.length; console.error('br=%d len=%d', bytesread, len); - setTimeout(next); + setTimeout(next, 1); } test.read(0); }); From dec5900c421166291612afabe2832d11dde2d201 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Fri, 4 Nov 2016 14:08:50 -0700 Subject: [PATCH 071/291] tools: add lint rule to enforce timer arguments Add a custom ESLint rule to require that setTimeout() and setInterval() get called with at least two arguments. This prevents omitting the duration or interval. PR-URL: https://github.com/nodejs/node/pull/9472 Reviewed-By: Teddy Katz Reviewed-By: James M Snell --- .eslintrc | 1 + tools/eslint-rules/timer-arguments.js | 25 +++++++++++++++++++++++++ 2 files changed, 26 insertions(+) create mode 100644 tools/eslint-rules/timer-arguments.js diff --git a/.eslintrc b/.eslintrc index d2cc8ea000ac3f..34f32e59f0a626 100644 --- a/.eslintrc +++ b/.eslintrc @@ -124,6 +124,7 @@ rules: assert-fail-single-argument: 2 assert-throws-arguments: [2, { requireTwo: false }] new-with-error: [2, Error, RangeError, TypeError, SyntaxError, ReferenceError] + timer-arguments: 2 # Global scoped method and vars globals: diff --git a/tools/eslint-rules/timer-arguments.js b/tools/eslint-rules/timer-arguments.js new file mode 100644 index 00000000000000..4dd7816ff82ff2 --- /dev/null +++ b/tools/eslint-rules/timer-arguments.js @@ -0,0 +1,25 @@ +/** + * @fileoverview Require at least two arguments when calling setTimeout() or + * setInterval(). + * @author Rich Trott + */ +'use strict'; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +function isTimer(name) { + return ['setTimeout', 'setInterval'].includes(name); +} + +module.exports = function(context) { + return { + 'CallExpression': function(node) { + const name = node.callee.name; + if (isTimer(name) && node.arguments.length < 2) { + context.report(node, `${name} must have at least 2 arguments`); + } + } + }; +}; From 38bdfb0b8ebfd697ab61165aa5c3e2d7363f0dae Mon Sep 17 00:00:00 2001 From: Junshu Okamoto Date: Wed, 26 Oct 2016 02:30:12 -0700 Subject: [PATCH 072/291] test: refactor test-fs-utimes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * favor `===` over `==` * `var` -> `const`/`let` * use `common.mustCall()` PR-URL: https://github.com/nodejs/node/pull/9290 Reviewed-By: Michaël Zasso Reviewed-By: James M Snell --- test/parallel/test-fs-utimes.js | 43 +++++++++++++++++---------------- 1 file changed, 22 insertions(+), 21 deletions(-) diff --git a/test/parallel/test-fs-utimes.js b/test/parallel/test-fs-utimes.js index f245a7962da0f4..108ca7c7d71c03 100644 --- a/test/parallel/test-fs-utimes.js +++ b/test/parallel/test-fs-utimes.js @@ -4,11 +4,11 @@ var assert = require('assert'); var util = require('util'); var fs = require('fs'); -var tests_ok = 0; -var tests_run = 0; +let tests_ok = 0; +let tests_run = 0; function stat_resource(resource) { - if (typeof resource == 'string') { + if (typeof resource === 'string') { return fs.statSync(resource); } else { // ensure mtime has been written to disk @@ -19,8 +19,8 @@ function stat_resource(resource) { function check_mtime(resource, mtime) { mtime = fs._toUnixTimestamp(mtime); - var stats = stat_resource(resource); - var real_mtime = fs._toUnixTimestamp(stats.mtime); + const stats = stat_resource(resource); + const real_mtime = fs._toUnixTimestamp(stats.mtime); // check up to single-second precision // sub-second precision is OS and fs dependant return mtime - real_mtime < 2; @@ -46,9 +46,9 @@ function expect_ok(syscall, resource, err, atime, mtime) { // the tests assume that __filename belongs to the user running the tests // this should be a fairly safe assumption; testing against a temp file // would be even better though (node doesn't have such functionality yet) -function runTest(atime, mtime, callback) { +function testIt(atime, mtime, callback) { - var fd; + let fd; // // test synchronized code paths, these functions throw on failure // @@ -67,8 +67,7 @@ function runTest(atime, mtime, callback) { expect_errno('futimesSync', fd, ex, 'ENOSYS'); } - var err; - err = undefined; + let err = undefined; try { fs.utimesSync('foobarbaz', atime, mtime); } catch (ex) { @@ -90,10 +89,10 @@ function runTest(atime, mtime, callback) { // // test async code paths // - fs.utimes(__filename, atime, mtime, function(err) { + fs.utimes(__filename, atime, mtime, common.mustCall(function(err) { expect_ok('utimes', __filename, err, atime, mtime); - fs.utimes('foobarbaz', atime, mtime, function(err) { + fs.utimes('foobarbaz', atime, mtime, common.mustCall(function(err) { expect_errno('utimes', 'foobarbaz', err, 'ENOENT'); // don't close this fd @@ -103,34 +102,36 @@ function runTest(atime, mtime, callback) { fd = fs.openSync(__filename, 'r'); } - fs.futimes(fd, atime, mtime, function(err) { + fs.futimes(fd, atime, mtime, common.mustCall(function(err) { expect_ok('futimes', fd, err, atime, mtime); - fs.futimes(-1, atime, mtime, function(err) { + fs.futimes(-1, atime, mtime, common.mustCall(function(err) { expect_errno('futimes', -1, err, 'EBADF'); syncTests(); callback(); - }); + })); tests_run++; - }); + })); tests_run++; - }); + })); tests_run++; - }); + })); tests_run++; } -var stats = fs.statSync(__filename); +const stats = fs.statSync(__filename); // run tests +const runTest = common.mustCall(testIt, 6); + runTest(new Date('1982-09-10 13:37'), new Date('1982-09-10 13:37'), function() { runTest(new Date(), new Date(), function() { runTest(123456.789, 123456.789, function() { runTest(stats.mtime, stats.mtime, function() { runTest(NaN, Infinity, function() { - runTest('123456', -1, function() { + runTest('123456', -1, common.mustCall(function() { // done - }); + })); }); }); }); @@ -140,5 +141,5 @@ runTest(new Date('1982-09-10 13:37'), new Date('1982-09-10 13:37'), function() { process.on('exit', function() { console.log('Tests run / ok:', tests_run, '/', tests_ok); - assert.equal(tests_ok, tests_run); + assert.strictEqual(tests_ok, tests_run); }); From ff23d8112a2e472ec738c5d1e3e54f98f4b15852 Mon Sep 17 00:00:00 2001 From: Adrian Estrada Date: Sun, 1 Jan 2017 23:48:58 -0500 Subject: [PATCH 073/291] test: improve test-fs-readfile-zero-byte-liar * use const instead of var * use assert.strictEqual instead of assert.equal * use arrow functions PR-URL: https://github.com/nodejs/node/pull/10570 Reviewed-By: Luigi Pinca Reviewed-By: Italo A. Casas Reviewed-By: James M Snell --- .../test-fs-readfile-zero-byte-liar.js | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/test/parallel/test-fs-readfile-zero-byte-liar.js b/test/parallel/test-fs-readfile-zero-byte-liar.js index 283a986f8a038a..c3887979bb0b4a 100644 --- a/test/parallel/test-fs-readfile-zero-byte-liar.js +++ b/test/parallel/test-fs-readfile-zero-byte-liar.js @@ -3,29 +3,29 @@ const common = require('../common'); var assert = require('assert'); var fs = require('fs'); -var dataExpected = fs.readFileSync(__filename, 'utf8'); +const dataExpected = fs.readFileSync(__filename, 'utf8'); // sometimes stat returns size=0, but it's a lie. fs._fstat = fs.fstat; fs._fstatSync = fs.fstatSync; -fs.fstat = function(fd, cb) { - fs._fstat(fd, function(er, st) { +fs.fstat = (fd, cb) => { + fs._fstat(fd, (er, st) => { if (er) return cb(er); st.size = 0; return cb(er, st); }); }; -fs.fstatSync = function(fd) { - var st = fs._fstatSync(fd); +fs.fstatSync = (fd) => { + const st = fs._fstatSync(fd); st.size = 0; return st; }; -var d = fs.readFileSync(__filename, 'utf8'); -assert.equal(d, dataExpected); +const d = fs.readFileSync(__filename, 'utf8'); +assert.strictEqual(d, dataExpected); -fs.readFile(__filename, 'utf8', common.mustCall(function(er, d) { - assert.equal(d, dataExpected); +fs.readFile(__filename, 'utf8', common.mustCall((er, d) => { + assert.strictEqual(d, dataExpected); })); From e78de99bcbfd1a344a9a112603b15f27b662fc7a Mon Sep 17 00:00:00 2001 From: Adrian Estrada Date: Sat, 7 Jan 2017 10:56:53 -0500 Subject: [PATCH 074/291] test: improve test-http-chunked-304 * change the nested functions call to run tests in parallel * use const and let instead of var * use common.mustCall to control functions execution * use assert.strictEqual instead of assert.equal * use arrow functions PR-URL: https://github.com/nodejs/node/pull/10462 Reviewed-By: Colin Ihrig Reviewed-By: James M Snell Reviewed-By: Italo A. Casas Reviewed-By: Sakthipriyan Vairamani Reviewed-By: Prince John Wesley Reviewed-By: Luigi Pinca --- test/parallel/test-http-chunked-304.js | 45 ++++++++++++++------------ 1 file changed, 24 insertions(+), 21 deletions(-) diff --git a/test/parallel/test-http-chunked-304.js b/test/parallel/test-http-chunked-304.js index 5ea1912b72dfee..82fe138fd926da 100644 --- a/test/parallel/test-http-chunked-304.js +++ b/test/parallel/test-http-chunked-304.js @@ -12,32 +12,35 @@ var net = require('net'); // Likewise for 304 responses. Verify that no empty chunk is sent when // the user explicitly sets a Transfer-Encoding header. -test(204, function() { - test(304); -}); +test(204); +test(304); -function test(statusCode, next) { - var server = http.createServer(function(req, res) { +function test(statusCode) { + const server = http.createServer(common.mustCall((req, res) => { res.writeHead(statusCode, { 'Transfer-Encoding': 'chunked' }); res.end(); server.close(); - }); + })); - server.listen(0, function() { - var conn = net.createConnection(this.address().port, function() { - conn.write('GET / HTTP/1.1\r\n\r\n'); + server.listen(0, common.mustCall(() => { + const conn = net.createConnection( + server.address().port, + common.mustCall(() => { + conn.write('GET / HTTP/1.1\r\n\r\n'); - var resp = ''; - conn.setEncoding('utf8'); - conn.on('data', function(data) { - resp += data; - }); + let resp = ''; + conn.setEncoding('utf8'); + conn.on('data', common.mustCall((data) => { + resp += data; + })); - conn.on('end', common.mustCall(function() { - assert.equal(/^Connection: close\r\n$/m.test(resp), true); - assert.equal(/^0\r\n$/m.test(resp), false); - if (next) process.nextTick(next); - })); - }); - }); + conn.on('end', common.mustCall(() => { + // Connection: close should be in the response + assert.strictEqual(/^Connection: close\r\n$/m.test(resp), true); + // Make sure this doesn't end with 0\r\n\r\n + assert.strictEqual(/^0\r\n$/m.test(resp), false); + })); + }) + ); + })); } From 4aa32c196a2f43d94ba22cba3e43cd3b0c0bed16 Mon Sep 17 00:00:00 2001 From: Adrian Estrada Date: Fri, 6 Jan 2017 10:09:54 -0500 Subject: [PATCH 075/291] test: improve code in test-https-strict * use let and const instead of var * use assert.strictEqual instead of assert.equal * remove unused var PR-URL: https://github.com/nodejs/node/pull/10648 Reviewed-By: Colin Ihrig Reviewed-By: James M Snell Reviewed-By: Luigi Pinca Reviewed-By: Michael Dawson --- test/parallel/test-https-strict.js | 73 +++++++++++++++--------------- 1 file changed, 36 insertions(+), 37 deletions(-) diff --git a/test/parallel/test-https-strict.js b/test/parallel/test-https-strict.js index 871d9ef94e6960..ff9c1790824429 100644 --- a/test/parallel/test-https-strict.js +++ b/test/parallel/test-https-strict.js @@ -23,60 +23,60 @@ function read(fname) { } // key1 is signed by ca1. -var key1 = read('agent1-key.pem'); -var cert1 = read('agent1-cert.pem'); +const key1 = read('agent1-key.pem'); +const cert1 = read('agent1-cert.pem'); // key2 has a self signed cert -var key2 = read('agent2-key.pem'); -var cert2 = read('agent2-cert.pem'); +const key2 = read('agent2-key.pem'); +const cert2 = read('agent2-cert.pem'); // key3 is signed by ca2. -var key3 = read('agent3-key.pem'); -var cert3 = read('agent3-cert.pem'); +const key3 = read('agent3-key.pem'); +const cert3 = read('agent3-cert.pem'); -var ca1 = read('ca1-cert.pem'); -var ca2 = read('ca2-cert.pem'); +const ca1 = read('ca1-cert.pem'); +const ca2 = read('ca2-cert.pem'); // different agents to use different CA lists. // this api is beyond bad. -var agent0 = new https.Agent(); -var agent1 = new https.Agent({ ca: [ca1] }); -var agent2 = new https.Agent({ ca: [ca2] }); -var agent3 = new https.Agent({ ca: [ca1, ca2] }); +const agent0 = new https.Agent(); +const agent1 = new https.Agent({ ca: [ca1] }); +const agent2 = new https.Agent({ ca: [ca2] }); +const agent3 = new https.Agent({ ca: [ca1, ca2] }); -var options1 = { +const options1 = { key: key1, cert: cert1 }; -var options2 = { +const options2 = { key: key2, cert: cert2 }; -var options3 = { +const options3 = { key: key3, cert: cert3 }; -var server1 = server(options1); -var server2 = server(options2); -var server3 = server(options3); +const server1 = server(options1); +const server2 = server(options2); +const server3 = server(options3); -var listenWait = 0; +let listenWait = 0; server1.listen(0, listening()); server2.listen(0, listening()); server3.listen(0, listening()); -var responseErrors = {}; -var expectResponseCount = 0; -var responseCount = 0; -var pending = 0; +const responseErrors = {}; +let expectResponseCount = 0; +let responseCount = 0; +let pending = 0; -function server(options, port) { - var s = https.createServer(options, handler); +function server(options) { + const s = https.createServer(options, handler); s.requests = []; s.expectCount = 0; return s; @@ -91,7 +91,7 @@ function handler(req, res) { function listening() { listenWait++; - return function() { + return () => { listenWait--; if (listenWait === 0) { allListening(); @@ -101,7 +101,7 @@ function listening() { function makeReq(path, port, error, host, ca) { pending++; - var options = { + const options = { port: port, path: path, ca: ca @@ -125,9 +125,9 @@ function makeReq(path, port, error, host, ca) { if (host) { options.headers = { host: host }; } - var req = https.get(options); + const req = https.get(options); expectResponseCount++; - var server = port === server1.address().port ? server1 : + const server = port === server1.address().port ? server1 : port === server2.address().port ? server2 : port === server3.address().port ? server3 : null; @@ -135,9 +135,9 @@ function makeReq(path, port, error, host, ca) { if (!server) throw new Error('invalid port: ' + port); server.expectCount++; - req.on('response', function(res) { + req.on('response', (res) => { responseCount++; - assert.equal(res.connection.authorizationError, error); + assert.strictEqual(res.connection.authorizationError, error); responseErrors[path] = res.connection.authorizationError; pending--; if (pending === 0) { @@ -195,10 +195,9 @@ function allListening() { } -process.on('exit', function() { - console.error(responseErrors); - assert.equal(server1.requests.length, server1.expectCount); - assert.equal(server2.requests.length, server2.expectCount); - assert.equal(server3.requests.length, server3.expectCount); - assert.equal(responseCount, expectResponseCount); +process.on('exit', () => { + assert.strictEqual(server1.requests.length, server1.expectCount); + assert.strictEqual(server2.requests.length, server2.expectCount); + assert.strictEqual(server3.requests.length, server3.expectCount); + assert.strictEqual(responseCount, expectResponseCount); }); From 1329eb47f0c00515574550a37116c23b59b9bf8f Mon Sep 17 00:00:00 2001 From: cjihrig Date: Thu, 5 Jan 2017 16:47:20 -0500 Subject: [PATCH 076/291] test: allow testing uid and gid separately MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This commit lets the uid and gid options of spawn() to be tested independently of one another based on the user's uid and gid. Fixes: https://github.com/nodejs/node/issues/10646 PR-URL: https://github.com/nodejs/node/pull/10647 Reviewed-By: James M Snell Reviewed-By: Michaël Zasso --- test/parallel/test-child-process-uid-gid.js | 22 ++++++++++----------- 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/test/parallel/test-child-process-uid-gid.js b/test/parallel/test-child-process-uid-gid.js index 1ee7661227701e..ec2cb9a31956c1 100644 --- a/test/parallel/test-child-process-uid-gid.js +++ b/test/parallel/test-child-process-uid-gid.js @@ -2,18 +2,16 @@ const common = require('../common'); const assert = require('assert'); const spawn = require('child_process').spawn; - -if (!common.isWindows && process.getuid() === 0) { - common.skip('as this test should not be run as `root`'); - return; -} - const expectedError = common.isWindows ? /\bENOTSUP\b/ : /\bEPERM\b/; -assert.throws(() => { - spawn('echo', ['fhqwhgads'], {uid: 0}); -}, expectedError); +if (common.isWindows || process.getuid() !== 0) { + assert.throws(() => { + spawn('echo', ['fhqwhgads'], {uid: 0}); + }, expectedError); +} -assert.throws(() => { - spawn('echo', ['fhqwhgads'], {gid: 0}); -}, expectedError); +if (common.isWindows || !process.getgroups().some((gid) => gid === 0)) { + assert.throws(() => { + spawn('echo', ['fhqwhgads'], {gid: 0}); + }, expectedError); +} From 2d856097b3e4300959fc3fd6e56e2fa6087827b8 Mon Sep 17 00:00:00 2001 From: sivaprasanna Date: Wed, 4 Jan 2017 13:03:20 +0530 Subject: [PATCH 077/291] test: refactor the code in test-child-process-spawn-loop.js * use const and let instead of var * use assert.strictEqual instead of assert.equal * use arrow functions PR-URL: https://github.com/nodejs/node/pull/10605 Reviewed-By: Benjamin Gruenbaum Reviewed-By: James M Snell --- test/pummel/test-child-process-spawn-loop.js | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/test/pummel/test-child-process-spawn-loop.js b/test/pummel/test-child-process-spawn-loop.js index 7e686cada244b3..7a3cf114b4e8e9 100644 --- a/test/pummel/test-child-process-spawn-loop.js +++ b/test/pummel/test-child-process-spawn-loop.js @@ -4,26 +4,26 @@ var assert = require('assert'); var spawn = require('child_process').spawn; -var SIZE = 1000 * 1024; -var N = 40; -var finished = false; +const SIZE = 1000 * 1024; +const N = 40; +let finished = false; function doSpawn(i) { - var child = spawn('python', ['-c', 'print ' + SIZE + ' * "C"']); - var count = 0; + const child = spawn('python', ['-c', 'print ' + SIZE + ' * "C"']); + let count = 0; child.stdout.setEncoding('ascii'); - child.stdout.on('data', function(chunk) { + child.stdout.on('data', (chunk) => { count += chunk.length; }); - child.stderr.on('data', function(chunk) { + child.stderr.on('data', (chunk) => { console.log('stderr: ' + chunk); }); - child.on('close', function() { + child.on('close', () => { // + 1 for \n or + 2 for \r\n on Windows - assert.equal(SIZE + (common.isWindows ? 2 : 1), count); + assert.strictEqual(SIZE + (common.isWindows ? 2 : 1), count); if (i < N) { doSpawn(i + 1); } else { @@ -34,6 +34,6 @@ function doSpawn(i) { doSpawn(0); -process.on('exit', function() { +process.on('exit', () => { assert.ok(finished); }); From cf5579d746c0a5cc673bdd7c546cc5c101eba766 Mon Sep 17 00:00:00 2001 From: Michael Lefkowitz Date: Fri, 6 Jan 2017 22:11:42 -0600 Subject: [PATCH 078/291] test: improve zlib-from-gzip-with-trailing-garbage * use assert.strictEqual instead of assert.equal * add RegExp in second argument of assert.throws * validate error message and code PR-URL: https://github.com/nodejs/node/pull/10674 Reviewed-By: James M Snell Reviewed-By: Colin Ihrig Reviewed-By: Luigi Pinca --- ...st-zlib-from-gzip-with-trailing-garbage.js | 28 +++++++++++++++---- 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/test/parallel/test-zlib-from-gzip-with-trailing-garbage.js b/test/parallel/test-zlib-from-gzip-with-trailing-garbage.js index 37f89f5b94bf08..872c2581c53b90 100644 --- a/test/parallel/test-zlib-from-gzip-with-trailing-garbage.js +++ b/test/parallel/test-zlib-from-gzip-with-trailing-garbage.js @@ -12,11 +12,15 @@ let data = Buffer.concat([ Buffer(10).fill(0) ]); -assert.equal(zlib.gunzipSync(data).toString(), 'abcdef'); +assert.strictEqual(zlib.gunzipSync(data).toString(), 'abcdef'); zlib.gunzip(data, common.mustCall((err, result) => { assert.ifError(err); - assert.equal(result, 'abcdef', 'result should match original string'); + assert.strictEqual( + result.toString(), + 'abcdef', + 'result should match original string' + ); })); // if the trailing garbage happens to look like a gzip header, it should @@ -28,10 +32,16 @@ data = Buffer.concat([ Buffer(10).fill(0) ]); -assert.throws(() => zlib.gunzipSync(data)); +assert.throws( + () => zlib.gunzipSync(data), + /^Error: unknown compression method$/ +); zlib.gunzip(data, common.mustCall((err, result) => { - assert(err); + assert(err instanceof Error); + assert.strictEqual(err.code, 'Z_DATA_ERROR'); + assert.strictEqual(err.message, 'unknown compression method'); + assert.strictEqual(result, undefined); })); // In this case the trailing junk is too short to be a gzip segment @@ -42,8 +52,14 @@ data = Buffer.concat([ Buffer([0x1f, 0x8b, 0xff, 0xff]) ]); -assert.throws(() => zlib.gunzipSync(data)); +assert.throws( + () => zlib.gunzipSync(data), + /^Error: unknown compression method$/ +); zlib.gunzip(data, common.mustCall((err, result) => { - assert(err); + assert(err instanceof Error); + assert.strictEqual(err.code, 'Z_DATA_ERROR'); + assert.strictEqual(err.message, 'unknown compression method'); + assert.strictEqual(result, undefined); })); From 4323c8018e4f6cffa2da6a53b7de176d5d1396c4 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Fri, 6 Jan 2017 21:40:51 -0800 Subject: [PATCH 079/291] test,cluster: add test-cluster-worker-deprecated Add test to cover setter for deprecated cluster Worker property. Previously, the setter was not being exercised in tests. PR-URL: https://github.com/nodejs/node/pull/10675 Reviewed-By: James M Snell Reviewed-By: Sam Roberts --- lib/cluster.js | 14 ++++++-------- .../parallel/test-cluster-worker-deprecated.js | 18 ++++++++++++++++++ 2 files changed, 24 insertions(+), 8 deletions(-) create mode 100644 test/parallel/test-cluster-worker-deprecated.js diff --git a/lib/cluster.js b/lib/cluster.js index e95e19bcc672d4..a12b83cd0c34c0 100644 --- a/lib/cluster.js +++ b/lib/cluster.js @@ -31,14 +31,12 @@ function Worker(options) { this.exitedAfterDisconnect = undefined; Object.defineProperty(this, 'suicide', { - get: internalUtil.deprecate(() => { - return this.exitedAfterDisconnect; - }, 'worker.suicide is deprecated. ' + - 'Please use worker.exitedAfterDisconnect.'), - set: internalUtil.deprecate((val) => { - this.exitedAfterDisconnect = val; - }, 'worker.suicide is deprecated. ' + - 'Please use worker.exitedAfterDisconnect.'), + get: internalUtil.deprecate( + () => this.exitedAfterDisconnect, + 'worker.suicide is deprecated. Please use worker.exitedAfterDisconnect.'), + set: internalUtil.deprecate( + (val) => { this.exitedAfterDisconnect = val; }, + 'worker.suicide is deprecated. Please use worker.exitedAfterDisconnect.'), enumerable: true }); diff --git a/test/parallel/test-cluster-worker-deprecated.js b/test/parallel/test-cluster-worker-deprecated.js new file mode 100644 index 00000000000000..2f433aae797ccc --- /dev/null +++ b/test/parallel/test-cluster-worker-deprecated.js @@ -0,0 +1,18 @@ +'use strict'; +require('../common'); + +const assert = require('assert'); +const cluster = require('cluster'); + +const worker = new cluster.Worker(); + +assert.strictEqual(worker.exitedAfterDisconnect, undefined); +assert.strictEqual(worker.suicide, undefined); + +worker.exitedAfterDisconnect = 'recommended'; +assert.strictEqual(worker.exitedAfterDisconnect, 'recommended'); +assert.strictEqual(worker.suicide, 'recommended'); + +worker.suicide = 'deprecated'; +assert.strictEqual(worker.exitedAfterDisconnect, 'deprecated'); +assert.strictEqual(worker.suicide, 'deprecated'); From 8ba2cf9c51b6ab40ed1ccbc7c3d161c3cd25e80c Mon Sep 17 00:00:00 2001 From: vitkarpov Date: Sun, 16 Oct 2016 15:47:07 +0300 Subject: [PATCH 080/291] http: define all used properties in constructors MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adding all used properties in the constructor makes the hidden class stable and heap snapshots more verbose. Refs: https://github.com/nodejs/node/issues/8912 PR-URL: https://github.com/nodejs/node/pull/9116 Reviewed-By: Brian White Reviewed-By: James M Snell Reviewed-By: Colin Ihrig Reviewed-By: Michaël Zasso --- lib/_http_client.js | 16 ++++++++++------ lib/_http_server.js | 1 + 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/lib/_http_client.js b/lib/_http_client.js index b52d3caf63f92c..97fdf16cc875b1 100644 --- a/lib/_http_client.js +++ b/lib/_http_client.js @@ -172,6 +172,14 @@ function ClientRequest(options, cb) { self._renderHeaders()); } + this._ended = false; + this.res = null; + this.aborted = undefined; + this.timeoutCb = null; + this.upgradeOrConnect = false; + this.parser = null; + this.maxHeadersCount = null; + var called = false; if (self.socketPath) { self._last = true; @@ -239,16 +247,12 @@ function ClientRequest(options, cb) { self._flush(); self = null; }); - - this._ended = false; } util.inherits(ClientRequest, OutgoingMessage); exports.ClientRequest = ClientRequest; -ClientRequest.prototype.aborted = undefined; - ClientRequest.prototype._finish = function _finish() { DTRACE_HTTP_CLIENT_REQUEST(this, this.connection); LTTNG_HTTP_CLIENT_REQUEST(this, this.connection); @@ -262,7 +266,7 @@ ClientRequest.prototype._implicitHeader = function _implicitHeader() { }; ClientRequest.prototype.abort = function abort() { - if (this.aborted === undefined) { + if (!this.aborted) { process.nextTick(emitAbortNT, this); } // Mark as aborting so we can avoid sending queued request data @@ -491,7 +495,7 @@ function parserOnIncomingClient(res, shouldKeepAlive) { if (res.statusCode === 100) { // restart the parser, as this is a continue message. - delete req.res; // Clear res so that we don't hit double-responses. + req.res = null; // Clear res so that we don't hit double-responses. req.emit('continue'); return true; } diff --git a/lib/_http_server.js b/lib/_http_server.js index 21113fc37a9f5b..bd726f83e3e638 100644 --- a/lib/_http_server.js +++ b/lib/_http_server.js @@ -248,6 +248,7 @@ function Server(requestListener) { this.timeout = 2 * 60 * 1000; this._pendingResponseData = 0; + this.maxHeadersCount = null; } util.inherits(Server, net.Server); From 17d9a739c18ad067dd5cef3b5cc43e614b4602fd Mon Sep 17 00:00:00 2001 From: sivaprasanna Date: Sat, 7 Jan 2017 23:10:16 +0530 Subject: [PATCH 081/291] test: refactor test-watch-file.js * use const and let instead of var * use arrow function * removed console.log statements PR-URL: https://github.com/nodejs/node/pull/10679 Reviewed-By: James M Snell Reviewed-By: Colin Ihrig Reviewed-By: Luigi Pinca Reviewed-By: Italo A. Casas Reviewed-By: Sakthipriyan Vairamani --- test/pummel/test-watch-file.js | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/test/pummel/test-watch-file.js b/test/pummel/test-watch-file.js index 8fdf6b32b2d78c..8b79ef8ede4a63 100644 --- a/test/pummel/test-watch-file.js +++ b/test/pummel/test-watch-file.js @@ -5,14 +5,11 @@ var assert = require('assert'); var fs = require('fs'); var path = require('path'); -var f = path.join(common.fixturesDir, 'x.txt'); +const f = path.join(common.fixturesDir, 'x.txt'); -console.log('watching for changes of ' + f); - -var changes = 0; +let changes = 0; function watchFile() { - fs.watchFile(f, function(curr, prev) { - console.log(f + ' change'); + fs.watchFile(f, (curr, prev) => { changes++; assert.notDeepStrictEqual(curr.mtime, prev.mtime); fs.unwatchFile(f); @@ -24,7 +21,7 @@ function watchFile() { watchFile(); -var fd = fs.openSync(f, 'w+'); +const fd = fs.openSync(f, 'w+'); fs.writeSync(fd, 'xyz\n'); fs.closeSync(fd); From da572131db8178cc8f46b96e531d8e0873f6b222 Mon Sep 17 00:00:00 2001 From: Adrian Estrada Date: Sun, 8 Jan 2017 18:41:26 -0500 Subject: [PATCH 082/291] test: improve the code in test-process-hrtime * use const instead of var * use assert.strictEqual instead of assert.equal and plain assert * use arrow functions * swap assertions arguments to match the standard * validate the error for assert.throws PR-URL: https://github.com/nodejs/node/pull/10667 Reviewed-By: James M Snell Reviewed-By: Michal Zasso Reviewed-By: Colin Ihrig Reviewed-By: Luigi Pinca --- test/parallel/test-process-hrtime.js | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/test/parallel/test-process-hrtime.js b/test/parallel/test-process-hrtime.js index db16be0ad9e812..9280b671f316d6 100644 --- a/test/parallel/test-process-hrtime.js +++ b/test/parallel/test-process-hrtime.js @@ -3,7 +3,7 @@ require('../common'); var assert = require('assert'); // the default behavior, return an Array "tuple" of numbers -var tuple = process.hrtime(); +const tuple = process.hrtime(); // validate the default behavior validateTuple(tuple); @@ -12,16 +12,16 @@ validateTuple(tuple); validateTuple(process.hrtime(tuple)); // test that only an Array may be passed to process.hrtime() -assert.throws(function() { +assert.throws(() => { process.hrtime(1); -}); +}, /^TypeError: process.hrtime\(\) only accepts an Array tuple$/); function validateTuple(tuple) { assert(Array.isArray(tuple)); - assert.equal(2, tuple.length); - tuple.forEach(function(v) { - assert.equal('number', typeof v); - assert(isFinite(v)); + assert.strictEqual(tuple.length, 2); + tuple.forEach((v) => { + assert.strictEqual(typeof v, 'number'); + assert.strictEqual(isFinite(v), true); }); } From 09ac2a2cb7a8a18068016b8b2c707bcd297c04c8 Mon Sep 17 00:00:00 2001 From: Sam Roberts Date: Mon, 9 Jan 2017 12:35:08 -0800 Subject: [PATCH 083/291] doc: specify sorted requires in tests And allow anchor links to the various sections, to more easily reference them when reviewing PRs. PR-URL: https://github.com/nodejs/node/pull/10716 Reviewed-By: Colin Ihrig Reviewed-By: Rich Trott Reviewed-By: James M Snell Reviewed-By: Luigi Pinca Reviewed-By: Gibson Fahnestock --- doc/guides/writing-tests.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/doc/guides/writing-tests.md b/doc/guides/writing-tests.md index c587eb3d8e9ccd..f27c076590e513 100644 --- a/doc/guides/writing-tests.md +++ b/doc/guides/writing-tests.md @@ -29,8 +29,8 @@ Let's analyze this basic test from the Node.js test suite: 4 // This test ensures that the http-parser can handle UTF-8 characters 5 // in the http header. 6 -7 const http = require('http'); -8 const assert = require('assert'); +7 const assert = require('assert'); +8 const http = require('http'); 9 10 const server = http.createServer(common.mustCall((req, res) => { 11 res.end('ok'); @@ -46,7 +46,7 @@ Let's analyze this basic test from the Node.js test suite: 21 }); ``` -**Lines 1-2** +### **Lines 1-2** ```javascript 'use strict'; @@ -70,7 +70,7 @@ assigning it to an identifier: require('../common'); ``` -**Lines 4-5** +### **Lines 4-5** ```javascript // This test ensures that the http-parser can handle UTF-8 characters @@ -80,11 +80,11 @@ require('../common'); A test should start with a comment containing a brief description of what it is designed to test. -**Lines 7-8** +### **Lines 7-8** ```javascript -const http = require('http'); const assert = require('assert'); +const http = require('http'); ``` The test checks functionality in the `http` module. @@ -95,7 +95,7 @@ The require statements are sorted in [ASCII](http://man7.org/linux/man-pages/man7/ascii.7.html) order (digits, upper case, `_`, lower case). -**Lines 10-21** +### **Lines 10-21** This is the body of the test. This test is simple, it just tests that an HTTP server accepts `non-ASCII` characters in the headers of an incoming From 4c8676bc26357f561b8a5aeb2396bc75d51648d8 Mon Sep 17 00:00:00 2001 From: abouthiroppy Date: Mon, 9 Jan 2017 07:14:16 +0900 Subject: [PATCH 084/291] test: refactor test-doctool-html.js PR-URL: https://github.com/nodejs/node/pull/10696 Reviewed-By: James M Snell Reviewed-By: Luigi Pinca Reviewed-By: Michael Dawson --- test/doctool/test-doctool-html.js | 2 +- test/doctool/test-doctool-json.js | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/test/doctool/test-doctool-html.js b/test/doctool/test-doctool-html.js index bd21e21d9563d2..1745c8fea3df5c 100644 --- a/test/doctool/test-doctool-html.js +++ b/test/doctool/test-doctool-html.js @@ -74,7 +74,7 @@ const testData = [ }, ]; -testData.forEach(function(item) { +testData.forEach((item) => { // Normalize expected data by stripping whitespace const expected = item.html.replace(/\s/g, ''); diff --git a/test/doctool/test-doctool-json.js b/test/doctool/test-doctool-json.js index 520c79bef8bcda..ae7b2007b7d2ef 100644 --- a/test/doctool/test-doctool-json.js +++ b/test/doctool/test-doctool-json.js @@ -18,7 +18,7 @@ const json = require('../../tools/doc/json.js'); // Test data is a list of objects with two properties. // The file property is the file path. // The json property is some json which will be generated by the doctool. -var testData = [ +const testData = [ { file: path.join(common.fixturesDir, 'sample_document.md'), json: { @@ -136,10 +136,10 @@ var testData = [ } ]; -testData.forEach(function(item) { - fs.readFile(item.file, 'utf8', common.mustCall(function(err, input) { +testData.forEach((item) => { + fs.readFile(item.file, 'utf8', common.mustCall((err, input) => { assert.ifError(err); - json(input, 'foo', common.mustCall(function(err, output) { + json(input, 'foo', common.mustCall((err, output) => { assert.ifError(err); assert.deepStrictEqual(output, item.json); })); From e408f0a1f557483aa4044eea67ec403b18dda807 Mon Sep 17 00:00:00 2001 From: Nathan Friedly Date: Sun, 8 Jan 2017 16:36:19 -0500 Subject: [PATCH 085/291] test: fix misplaced ) in http response statuscode test This fixes a misplaced parenthesis in each of the tests in test/parallel/test-http-response-statuscodes.js, causing the tests to pass as long as any error was thrown, without validating the error message. PR-URL: https://github.com/nodejs/node/pull/10692 Reviewed-By: Colin Ihrig Reviewed-By: James M Snell Reviewed-By: Luigi Pinca Reviewed-By: Michal Zasso Reviewed-By: Rich Trott --- .../parallel/test-http-response-statuscode.js | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/test/parallel/test-http-response-statuscode.js b/test/parallel/test-http-response-statuscode.js index 3314506339b564..57256db6032324 100644 --- a/test/parallel/test-http-response-statuscode.js +++ b/test/parallel/test-http-response-statuscode.js @@ -11,62 +11,62 @@ const server = http.Server(common.mustCall(function(req, res) { case 0: assert.throws(common.mustCall(() => { res.writeHead(-1); - }, /invalid status code/i)); + }), /invalid status code/i); break; case 1: assert.throws(common.mustCall(() => { res.writeHead(Infinity); - }, /invalid status code/i)); + }), /invalid status code/i); break; case 2: assert.throws(common.mustCall(() => { res.writeHead(NaN); - }, /invalid status code/i)); + }), /invalid status code/i); break; case 3: assert.throws(common.mustCall(() => { res.writeHead({}); - }, /invalid status code/i)); + }), /invalid status code/i); break; case 4: assert.throws(common.mustCall(() => { res.writeHead(99); - }, /invalid status code/i)); + }), /invalid status code/i); break; case 5: assert.throws(common.mustCall(() => { res.writeHead(1000); - }, /invalid status code/i)); + }), /invalid status code/i); break; case 6: assert.throws(common.mustCall(() => { res.writeHead('1000'); - }, /invalid status code/i)); + }), /invalid status code/i); break; case 7: assert.throws(common.mustCall(() => { res.writeHead(null); - }, /invalid status code/i)); + }), /invalid status code/i); break; case 8: assert.throws(common.mustCall(() => { res.writeHead(true); - }, /invalid status code/i)); + }), /invalid status code/i); break; case 9: assert.throws(common.mustCall(() => { res.writeHead([]); - }, /invalid status code/i)); + }), /invalid status code/i); break; case 10: assert.throws(common.mustCall(() => { res.writeHead('this is not valid'); - }, /invalid status code/i)); + }), /invalid status code/i); break; case 11: assert.throws(common.mustCall(() => { res.writeHead('404 this is not valid either'); - }, /invalid status code/i)); + }), /invalid status code/i); this.close(); break; default: From dbb772732020429e19d6e3dcceb35bb1caa17188 Mon Sep 17 00:00:00 2001 From: Nathan Friedly Date: Tue, 11 Oct 2016 15:43:36 -0400 Subject: [PATCH 086/291] test: validate 'expected' argument to mustCall() instead of silently overwriting invalid values with the default PR-URL: https://github.com/nodejs/node/pull/10692 Reviewed-By: Colin Ihrig Reviewed-By: James M Snell Reviewed-By: Luigi Pinca Reviewed-By: Michal Zasso Reviewed-By: Rich Trott --- test/common.js | 5 ++++- test/parallel/test-common.js | 8 ++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/test/common.js b/test/common.js index 0fff06bfc0944d..9d090d6bb786bb 100644 --- a/test/common.js +++ b/test/common.js @@ -398,7 +398,10 @@ function runCallChecks(exitCode) { exports.mustCall = function(fn, expected) { - if (typeof expected !== 'number') expected = 1; + if (expected === undefined) + expected = 1; + else if (typeof expected !== 'number') + throw new TypeError(`Invalid expected value: ${expected}`); const context = { expected: expected, diff --git a/test/parallel/test-common.js b/test/parallel/test-common.js index 5ffe2c351503c1..59485eec4a327f 100644 --- a/test/parallel/test-common.js +++ b/test/parallel/test-common.js @@ -5,3 +5,11 @@ var assert = require('assert'); common.globalCheck = false; global.gc = 42; // Not a valid global unless --expose_gc is set. assert.deepStrictEqual(common.leakedGlobals(), ['gc']); + +assert.throws(function() { + common.mustCall(function() {}, 'foo'); +}, /^TypeError: Invalid expected value: foo$/); + +assert.throws(function() { + common.mustCall(function() {}, /foo/); +}, /^TypeError: Invalid expected value: \/foo\/$/); From a6c93af24411abffd2b5fb10b28438b9eadb326b Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Sat, 7 Jan 2017 20:12:08 -0800 Subject: [PATCH 087/291] lib: refactor crypto cipher/hash/curve getters * refactor internal util.filterDuplicateStrings() to eliminate unused code paths * `.indexOf()` -> `.includes()` in test * more concise arrow functions PR-URL: https://github.com/nodejs/node/pull/10682 Reviewed-By: James M Snell Reviewed-By: Michal Zasso --- lib/crypto.js | 18 +++++++++--------- lib/internal/util.js | 10 ++-------- test/parallel/test-crypto-authenticated.js | 2 +- 3 files changed, 12 insertions(+), 18 deletions(-) diff --git a/lib/crypto.js b/lib/crypto.js index 6b2a04711a868a..c33728ac88c91f 100644 --- a/lib/crypto.js +++ b/lib/crypto.js @@ -637,17 +637,17 @@ exports.randomBytes = exports.pseudoRandomBytes = randomBytes; exports.rng = exports.prng = randomBytes; -exports.getCiphers = internalUtil.cachedResult(() => { - return internalUtil.filterDuplicateStrings(getCiphers()); -}); +exports.getCiphers = internalUtil.cachedResult( + () => internalUtil.filterDuplicateStrings(getCiphers()) +); -exports.getHashes = internalUtil.cachedResult(() => { - return internalUtil.filterDuplicateStrings(getHashes()); -}); +exports.getHashes = internalUtil.cachedResult( + () => internalUtil.filterDuplicateStrings(getHashes()) +); -exports.getCurves = internalUtil.cachedResult(() => { - return internalUtil.filterDuplicateStrings(getCurves()); -}); +exports.getCurves = internalUtil.cachedResult( + () => internalUtil.filterDuplicateStrings(getCurves()) +); Object.defineProperty(exports, 'fips', { get: getFipsCrypto, diff --git a/lib/internal/util.js b/lib/internal/util.js index 238eb65891365c..0c7f391eb1fad1 100644 --- a/lib/internal/util.js +++ b/lib/internal/util.js @@ -134,20 +134,14 @@ exports.normalizeEncoding = function normalizeEncoding(enc) { // Filters duplicate strings. Used to support functions in crypto and tls // modules. Implemented specifically to maintain existing behaviors in each. exports.filterDuplicateStrings = function filterDuplicateStrings(items, low) { - if (!Array.isArray(items)) - return []; - const len = items.length; - if (len <= 1) - return items; const map = new Map(); - for (var i = 0; i < len; i++) { + for (var i = 0; i < items.length; i++) { const item = items[i]; const key = item.toLowerCase(); if (low) { map.set(key, key); } else { - if (!map.has(key) || map.get(key) <= item) - map.set(key, item); + map.set(key, item); } } return Array.from(map.values()).sort(); diff --git a/test/parallel/test-crypto-authenticated.js b/test/parallel/test-crypto-authenticated.js index 4bed5aa665b64d..ee67250ff35223 100644 --- a/test/parallel/test-crypto-authenticated.js +++ b/test/parallel/test-crypto-authenticated.js @@ -312,7 +312,7 @@ const ciphers = crypto.getCiphers(); for (const i in TEST_CASES) { const test = TEST_CASES[i]; - if (ciphers.indexOf(test.algo) === -1) { + if (!ciphers.includes(test.algo)) { common.skip('unsupported ' + test.algo + ' test'); continue; } From cb111c96cc0761814c4f5c897010abd749bc549e Mon Sep 17 00:00:00 2001 From: sivaprasanna Date: Sun, 8 Jan 2017 14:03:09 +0530 Subject: [PATCH 088/291] test: refactor the code of test-keep-alive.js * use const and let instead of var * use assert.strictEqual instead of assert.equal * use arrow functions * removed console.log statements PR-URL: https://github.com/nodejs/node/pull/10684 Reviewed-By: Colin Ihrig Reviewed-By: James M Snell Reviewed-By: Sakthipriyan Vairamani --- test/pummel/test-keep-alive.js | 34 +++++++++++++++------------------- 1 file changed, 15 insertions(+), 19 deletions(-) diff --git a/test/pummel/test-keep-alive.js b/test/pummel/test-keep-alive.js index 1861b2df970e18..47d529b64082fa 100644 --- a/test/pummel/test-keep-alive.js +++ b/test/pummel/test-keep-alive.js @@ -12,8 +12,8 @@ if (common.isWindows) { return; } -var body = 'hello world\n'; -var server = http.createServer(function(req, res) { +const body = 'hello world\n'; +const server = http.createServer(function(req, res) { res.writeHead(200, { 'Content-Length': body.length, 'Content-Type': 'text/plain' @@ -22,12 +22,12 @@ var server = http.createServer(function(req, res) { res.end(); }); -var keepAliveReqSec = 0; -var normalReqSec = 0; +let keepAliveReqSec = 0; +let normalReqSec = 0; function runAb(opts, callback) { - var args = [ + const args = [ '-c', opts.concurrent || 100, '-t', opts.threads || 2, '-d', opts.duration || '10s', @@ -41,13 +41,11 @@ function runAb(opts, callback) { args.push(url.format({ hostname: '127.0.0.1', port: common.PORT, protocol: 'http'})); - //console.log(comm, args.join(' ')); - - var child = spawn('wrk', args); + const child = spawn('wrk', args); child.stderr.pipe(process.stderr); child.stdout.setEncoding('utf8'); - var stdout; + let stdout; child.stdout.on('data', function(data) { stdout += data; @@ -60,11 +58,11 @@ function runAb(opts, callback) { return; } - var matches = /Requests\/sec:\s*(\d+)\./mi.exec(stdout); - var reqSec = parseInt(matches[1]); + let matches = /Requests\/sec:\s*(\d+)\./mi.exec(stdout); + const reqSec = parseInt(matches[1]); matches = /Keep-Alive requests:\s*(\d+)/mi.exec(stdout); - var keepAliveRequests; + let keepAliveRequests; if (matches) { keepAliveRequests = parseInt(matches[1]); } else { @@ -75,21 +73,19 @@ function runAb(opts, callback) { }); } -server.listen(common.PORT, function() { - runAb({ keepalive: true }, function(reqSec) { +server.listen(common.PORT, () => { + runAb({ keepalive: true }, (reqSec) => { keepAliveReqSec = reqSec; - console.log('keep-alive:', keepAliveReqSec, 'req/sec'); runAb({ keepalive: false }, function(reqSec) { normalReqSec = reqSec; - console.log('normal:' + normalReqSec + ' req/sec'); server.close(); }); }); }); process.on('exit', function() { - assert.equal(true, normalReqSec > 50); - assert.equal(true, keepAliveReqSec > 50); - assert.equal(true, normalReqSec < keepAliveReqSec); + assert.strictEqual(true, normalReqSec > 50); + assert.strictEqual(true, keepAliveReqSec > 50); + assert.strictEqual(true, normalReqSec < keepAliveReqSec); }); From 160d0381d2a225d310ee315b53519b3c9b3cdca6 Mon Sep 17 00:00:00 2001 From: adelmann Date: Wed, 4 Jan 2017 16:31:28 -0800 Subject: [PATCH 089/291] test: refactor test-crypto-padding-aes256 * replace var with const/let * replace assert.equal() with assert.strictEqual() PR-URL: https://github.com/nodejs/node/pull/10622 Reviewed-By: James M Snell Reviewed-By: Luigi Pinca --- test/parallel/test-crypto-padding-aes256.js | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/test/parallel/test-crypto-padding-aes256.js b/test/parallel/test-crypto-padding-aes256.js index e835867d61d005..7fd2e98de617cf 100644 --- a/test/parallel/test-crypto-padding-aes256.js +++ b/test/parallel/test-crypto-padding-aes256.js @@ -11,18 +11,18 @@ var crypto = require('crypto'); crypto.DEFAULT_ENCODING = 'buffer'; function aes256(decipherFinal) { - var iv = Buffer.from('00000000000000000000000000000000', 'hex'); - var key = Buffer.from('0123456789abcdef0123456789abcdef' + - '0123456789abcdef0123456789abcdef', 'hex'); + const iv = Buffer.from('00000000000000000000000000000000', 'hex'); + const key = Buffer.from('0123456789abcdef0123456789abcdef' + + '0123456789abcdef0123456789abcdef', 'hex'); function encrypt(val, pad) { - var c = crypto.createCipheriv('aes256', key, iv); + const c = crypto.createCipheriv('aes256', key, iv); c.setAutoPadding(pad); return c.update(val, 'utf8', 'latin1') + c.final('latin1'); } function decrypt(val, pad) { - var c = crypto.createDecipheriv('aes256', key, iv); + const c = crypto.createDecipheriv('aes256', key, iv); c.setAutoPadding(pad); return c.update(val, 'latin1', 'utf8') + c[decipherFinal]('utf8'); } @@ -30,10 +30,10 @@ function aes256(decipherFinal) { // echo 0123456789abcdef0123456789abcdef \ // | openssl enc -e -aes256 -nopad -K -iv \ // | openssl enc -d -aes256 -nopad -K -iv - var plaintext = '0123456789abcdef0123456789abcdef'; // multiple of block size - var encrypted = encrypt(plaintext, false); - var decrypted = decrypt(encrypted, false); - assert.equal(decrypted, plaintext); + let plaintext = '0123456789abcdef0123456789abcdef'; // multiple of block size + let encrypted = encrypt(plaintext, false); + let decrypted = decrypt(encrypted, false); + assert.strictEqual(decrypted, plaintext); // echo 0123456789abcdef0123456789abcde \ // | openssl enc -e -aes256 -K -iv \ @@ -41,7 +41,7 @@ function aes256(decipherFinal) { plaintext = '0123456789abcdef0123456789abcde'; // not a multiple encrypted = encrypt(plaintext, true); decrypted = decrypt(encrypted, true); - assert.equal(decrypted, plaintext); + assert.strictEqual(decrypted, plaintext); } aes256('final'); From c012dd79dc58a65761341b38bb9649cb33e79651 Mon Sep 17 00:00:00 2001 From: Andreas Lind Date: Wed, 2 Nov 2016 23:20:12 +0100 Subject: [PATCH 090/291] https: Use secureProtocol in Agent#getName Refs: https://github.com/nodejs/node/issues/9324 PR-URL: https://github.com/nodejs/node/pull/9452 Reviewed-By: Ben Noordhuis Reviewed-By: James M Snell Reviewed-By: Colin Ihrig --- lib/https.js | 4 ++ test/parallel/test-https-agent-getname.js | 4 +- .../test-https-agent-secure-protocol.js | 60 +++++++++++++++++++ 3 files changed, 66 insertions(+), 2 deletions(-) create mode 100644 test/parallel/test-https-agent-secure-protocol.js diff --git a/lib/https.js b/lib/https.js index 26b6cbf279a15f..3b4e4294c23259 100644 --- a/lib/https.js +++ b/lib/https.js @@ -143,6 +143,10 @@ Agent.prototype.getName = function getName(options) { if (options.servername && options.servername !== options.host) name += options.servername; + name += ':'; + if (options.secureProtocol) + name += options.secureProtocol; + return name; }; diff --git a/test/parallel/test-https-agent-getname.js b/test/parallel/test-https-agent-getname.js index 49c1dcef4fb5fb..9b4f29602b79c6 100644 --- a/test/parallel/test-https-agent-getname.js +++ b/test/parallel/test-https-agent-getname.js @@ -14,7 +14,7 @@ const agent = new https.Agent(); // empty options assert.strictEqual( agent.getName({}), - 'localhost:::::::::' + 'localhost::::::::::' ); // pass all options arguments @@ -33,5 +33,5 @@ const options = { assert.strictEqual( agent.getName(options), - '0.0.0.0:443:192.168.1.1:ca:cert:ciphers:key:pfx:false:localhost' + '0.0.0.0:443:192.168.1.1:ca:cert:ciphers:key:pfx:false:localhost:' ); diff --git a/test/parallel/test-https-agent-secure-protocol.js b/test/parallel/test-https-agent-secure-protocol.js new file mode 100644 index 00000000000000..7cca682101fa0b --- /dev/null +++ b/test/parallel/test-https-agent-secure-protocol.js @@ -0,0 +1,60 @@ +'use strict'; +const assert = require('assert'); +const common = require('../common'); + +if (!common.hasCrypto) { + common.skip('missing crypto'); + return; +} + +const https = require('https'); +const fs = require('fs'); + +const options = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem'), + ca: fs.readFileSync(common.fixturesDir + '/keys/ca1-cert.pem') +}; + +const server = https.Server(options, function(req, res) { + res.writeHead(200); + res.end('hello world\n'); +}); + +server.listen(0, common.mustCall(function() { + const port = this.address().port; + const globalAgent = https.globalAgent; + globalAgent.keepAlive = true; + https.get({ + path: '/', + port: port, + ca: options.ca, + rejectUnauthorized: true, + servername: 'agent1', + secureProtocol: 'SSLv23_method' + }, common.mustCall(function(res) { + res.resume(); + globalAgent.once('free', common.mustCall(function() { + https.get({ + path: '/', + port: port, + ca: options.ca, + rejectUnauthorized: true, + servername: 'agent1', + secureProtocol: 'TLSv1_method' + }, common.mustCall(function(res) { + res.resume(); + globalAgent.once('free', common.mustCall(function() { + // Verify that two keep-alived connections are created + // due to the different secureProtocol settings: + const keys = Object.keys(globalAgent.freeSockets); + assert.strictEqual(keys.length, 2); + assert.ok(keys[0].includes(':SSLv23_method')); + assert.ok(keys[1].includes(':TLSv1_method')); + globalAgent.destroy(); + server.close(); + })); + })); + })); + })); +})); From 06a1e9eb7b7776a85c196d422506f04f6d9fb641 Mon Sep 17 00:00:00 2001 From: larissayvette Date: Thu, 5 Jan 2017 06:40:22 +0100 Subject: [PATCH 091/291] test: add test for noAssert option in buf.read*() PR-URL: https://github.com/nodejs/node/pull/10713 Reviewed-By: Rich Trott Reviewed-By: James M Snell --- test/parallel/test-buffer-read-noassert.js | 59 ++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 test/parallel/test-buffer-read-noassert.js diff --git a/test/parallel/test-buffer-read-noassert.js b/test/parallel/test-buffer-read-noassert.js new file mode 100644 index 00000000000000..83d533a32031cb --- /dev/null +++ b/test/parallel/test-buffer-read-noassert.js @@ -0,0 +1,59 @@ +'use strict'; +require('../common'); +const assert = require('assert'); + +// testing basic buffer read functions +const buf = Buffer.from([0xa4, 0xfd, 0x48, 0xea, 0xcf, 0xff, 0xd9, 0x01, 0xde]); + +function read(buff, funx, args, expected) { + + assert.strictEqual(buff[funx](...args), expected); + assert.throws( + () => buff[funx](-1), + /^RangeError: Index out of range$/ + ); + + assert.doesNotThrow( + () => assert.strictEqual(buff[funx](...args, true), expected), + 'noAssert does not change return value for valid ranges' +); + +} + +// testing basic functionality of readDoubleBE() and readDOubleLE() +read(buf, 'readDoubleBE', [1], -3.1827727774563287e+295); +read(buf, 'readDoubleLE', [1], -6.966010051009108e+144); + +// testing basic functionality of readFLoatBE() and readFloatLE() +read(buf, 'readFloatBE', [1], -1.6691549692541768e+37); +read(buf, 'readFloatLE', [1], -7861303808); + +// testing basic functionality of readInt8() +read(buf, 'readInt8', [1], -3); + +// testing basic functionality of readInt16BE() and readInt16LE() +read(buf, 'readInt16BE', [1], -696); +read(buf, 'readInt16LE', [1], 0x48fd); + +// testing basic functionality of readInt32BE() and readInt32LE() +read(buf, 'readInt32BE', [1], -45552945); +read(buf, 'readInt32LE', [1], -806729475); + +// testing basic functionality of readIntBE() and readIntLE() +read(buf, 'readIntBE', [1, 1], -3); +read(buf, 'readIntLE', [2, 1], 0x48); + +// testing basic functionality of readUInt8() +read(buf, 'readUInt8', [1], 0xfd); + +// testing basic functionality of readUInt16BE() and readUInt16LE() +read(buf, 'readUInt16BE', [2], 0x48ea); +read(buf, 'readUInt16LE', [2], 0xea48); + +// testing basic functionality of readUInt32BE() and readUInt32LE() +read(buf, 'readUInt32BE', [1], 0xfd48eacf); +read(buf, 'readUInt32LE', [1], 0xcfea48fd); + +// testing basic functionality of readUIntBE() and readUIntLE() +read(buf, 'readUIntBE', [2, 0], 0xfd); +read(buf, 'readUIntLE', [2, 0], 0x48); From b89d848b36791c4af8a7aa1f017da559e9930f12 Mon Sep 17 00:00:00 2001 From: Alexey Orlenko Date: Sat, 7 Jan 2017 09:25:03 +0200 Subject: [PATCH 092/291] src: enable writev for pipe handles on Unix This commit enables writev for Unix Domain Sockets on supported platforms thus enabling cork/uncork functionality for them and improving IPC performance. Fixes: https://github.com/nodejs/node/issues/5095 PR-URL: https://github.com/nodejs/node/pull/10677 Reviewed-By: Anna Henningsen Reviewed-By: Fedor Indutny Reviewed-By: Trevor Norris Reviewed-By: James M Snell --- src/pipe_wrap.cc | 4 +++ test/parallel/test-pipe-writev.js | 46 +++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 test/parallel/test-pipe-writev.js diff --git a/src/pipe_wrap.cc b/src/pipe_wrap.cc index 8fd2f8f5f3bbce..5f47dadddb4d96 100644 --- a/src/pipe_wrap.cc +++ b/src/pipe_wrap.cc @@ -53,7 +53,11 @@ void PipeWrap::Initialize(Local target, env->SetProtoMethod(t, "ref", HandleWrap::Ref); env->SetProtoMethod(t, "hasRef", HandleWrap::HasRef); +#ifdef _WIN32 StreamWrap::AddMethods(env, t); +#else + StreamWrap::AddMethods(env, t, StreamBase::kFlagHasWritev); +#endif env->SetProtoMethod(t, "bind", Bind); env->SetProtoMethod(t, "listen", Listen); diff --git a/test/parallel/test-pipe-writev.js b/test/parallel/test-pipe-writev.js new file mode 100644 index 00000000000000..6440b5f623761d --- /dev/null +++ b/test/parallel/test-pipe-writev.js @@ -0,0 +1,46 @@ +'use strict'; + +const common = require('../common'); +const assert = require('assert'); +const net = require('net'); + +if (common.isWindows) { + common.skip('Unix-specific test'); + return; +} + +common.refreshTmpDir(); + +const server = net.createServer((connection) => { + connection.on('error', (err) => { + throw err; + }); + + const writev = connection._writev.bind(connection); + connection._writev = common.mustCall(writev); + + connection.cork(); + connection.write('pi'); + connection.write('ng'); + connection.end(); +}); + +server.on('error', (err) => { + throw err; +}); + +server.listen(common.PIPE, () => { + const client = net.connect(common.PIPE); + + client.on('error', (err) => { + throw err; + }); + + client.on('data', common.mustCall((data) => { + assert.strictEqual(data.toString(), 'ping'); + })); + + client.on('end', () => { + server.close(); + }); +}); From 30926ac6d6a4eac1df92b2d7118bef1f491f2790 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Wed, 11 Jan 2017 10:32:45 -0800 Subject: [PATCH 093/291] test: move resource intensive test to sequential test-fs-readfile-tostring-fail is resource-intensive and is flaky in CI. Move to sequential tests so it is not competing for resources with other tests. PR-URL: https://github.com/nodejs/node/pull/10744 Fixes: https://github.com/nodejs/node/issues/10742 Reviewed-By: James M Snell Reviewed-By: Colin Ihrig Reviewed-By: Michael Dawson Reviewed-By: Gibson Fahnestock Reviewed-By: Brian White Reviewed-By: Santiago Gimeno --- test/{parallel => sequential}/test-fs-readfile-tostring-fail.js | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename test/{parallel => sequential}/test-fs-readfile-tostring-fail.js (100%) diff --git a/test/parallel/test-fs-readfile-tostring-fail.js b/test/sequential/test-fs-readfile-tostring-fail.js similarity index 100% rename from test/parallel/test-fs-readfile-tostring-fail.js rename to test/sequential/test-fs-readfile-tostring-fail.js From ffd938a694ec73bc2dbf3d6cc424cc55b68abc82 Mon Sep 17 00:00:00 2001 From: cjihrig Date: Mon, 9 Jan 2017 17:10:37 -0500 Subject: [PATCH 094/291] deps: upgrade libuv to 1.10.2 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Refs: https://github.com/nodejs/node/issues/9439 Fixes: https://github.com/nodejs/node/issues/9464 Fixes: https://github.com/nodejs/node/issues/9690 PR-URL: https://github.com/nodejs/node/pull/10717 Reviewed-By: James M Snell Reviewed-By: Santiago Gimeno Reviewed-By: Saúl Ibarra Corretgé --- deps/uv/AUTHORS | 1 + deps/uv/ChangeLog | 28 +++++++++ deps/uv/appveyor.yml | 2 +- deps/uv/configure.ac | 2 +- deps/uv/include/uv-version.h | 2 +- deps/uv/src/unix/darwin.c | 10 +++ deps/uv/src/unix/fs.c | 29 +++++++-- deps/uv/src/win/error.c | 1 + deps/uv/src/win/fs.c | 2 - deps/uv/src/win/getaddrinfo.c | 3 +- deps/uv/src/win/process.c | 2 +- deps/uv/src/win/tty.c | 107 +++++++++++++++++++++++++++++--- deps/uv/test/test-error.c | 1 + deps/uv/test/test-fs.c | 20 +++--- deps/uv/test/test-getaddrinfo.c | 7 +++ deps/uv/test/test-list.h | 4 ++ deps/uv/test/test-tty.c | 87 ++++++++++++++++++++++++++ 17 files changed, 275 insertions(+), 33 deletions(-) diff --git a/deps/uv/AUTHORS b/deps/uv/AUTHORS index 50916c67cdc30a..49c8e17f23b35c 100644 --- a/deps/uv/AUTHORS +++ b/deps/uv/AUTHORS @@ -278,3 +278,4 @@ Brad King Philippe Laferriere Will Speak Hitesh Kanwathirtha +Eric Sciple diff --git a/deps/uv/ChangeLog b/deps/uv/ChangeLog index b6f89af51f40bf..d865f22667ec39 100644 --- a/deps/uv/ChangeLog +++ b/deps/uv/ChangeLog @@ -1,3 +1,31 @@ +2017.01.10, Version 1.10.2 (Stable), cb9f579a454b8db592030ffa274ae58df78dbe20 + +Changes since version 1.10.1: + +* Now working on version 1.10.2 (cjihrig) + +* darwin: fix fsync and fdatasync (Joran Dirk Greef) + +* Revert "Revert "win,tty: add support for ANSI codes in win10 v1511"" + (Santiago Gimeno) + +* win,tty: fix MultiByteToWideChar output buffer (Santiago Gimeno) + +* win: remove dead code related to BACKUP_SEMANTICS (Sam Roberts) + +* win: fix comment in quote_cmd_arg (Eric Sciple) + +* darwin: use clock_gettime in macOS 10.12 (Saúl Ibarra Corretgé) + +* win, tty: fix crash on restarting with pending data (Nicholas Vavilov) + +* fs: fix uv__to_stat on BSD platforms (Santiago Gimeno) + +* win: map ERROR_ELEVATION_REQUIRED to UV_EACCES (Richard Lau) + +* win: fix free() on bad input in uv_getaddrinfo() (Ben Noordhuis) + + 2016.11.17, Version 1.10.1 (Stable), 2e49e332bdede6db7cf17fa784a902e8386d5d86 Changes since version 1.10.0: diff --git a/deps/uv/appveyor.yml b/deps/uv/appveyor.yml index 6b785611536c39..63294137833fb7 100644 --- a/deps/uv/appveyor.yml +++ b/deps/uv/appveyor.yml @@ -1,4 +1,4 @@ -version: v1.10.1.build{build} +version: v1.10.2.build{build} install: - cinst -y nsis diff --git a/deps/uv/configure.ac b/deps/uv/configure.ac index d3787c0d6dd9f7..abaf971772ffe7 100644 --- a/deps/uv/configure.ac +++ b/deps/uv/configure.ac @@ -13,7 +13,7 @@ # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. AC_PREREQ(2.57) -AC_INIT([libuv], [1.10.1], [https://github.com/libuv/libuv/issues]) +AC_INIT([libuv], [1.10.2], [https://github.com/libuv/libuv/issues]) AC_CONFIG_MACRO_DIR([m4]) m4_include([m4/libuv-extra-automake-flags.m4]) m4_include([m4/as_case.m4]) diff --git a/deps/uv/include/uv-version.h b/deps/uv/include/uv-version.h index 63454a5d0aee39..99f7eb8c1fae1d 100644 --- a/deps/uv/include/uv-version.h +++ b/deps/uv/include/uv-version.h @@ -32,7 +32,7 @@ #define UV_VERSION_MAJOR 1 #define UV_VERSION_MINOR 10 -#define UV_VERSION_PATCH 1 +#define UV_VERSION_PATCH 2 #define UV_VERSION_IS_RELEASE 1 #define UV_VERSION_SUFFIX "" diff --git a/deps/uv/src/unix/darwin.c b/deps/uv/src/unix/darwin.c index cf95da21693b9a..b1ffbc37b47b78 100644 --- a/deps/uv/src/unix/darwin.c +++ b/deps/uv/src/unix/darwin.c @@ -34,8 +34,12 @@ #include /* _NSGetExecutablePath */ #include #include +#include #include /* sysconf */ +#undef NANOSEC +#define NANOSEC ((uint64_t) 1e9) + int uv__platform_loop_init(uv_loop_t* loop) { loop->cf_state = NULL; @@ -53,6 +57,11 @@ void uv__platform_loop_delete(uv_loop_t* loop) { uint64_t uv__hrtime(uv_clocktype_t type) { +#ifdef MAC_OS_X_VERSION_10_12 + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return (((uint64_t) ts.tv_sec) * NANOSEC + ts.tv_nsec); +#else static mach_timebase_info_data_t info; if ((ACCESS_ONCE(uint32_t, info.numer) == 0 || @@ -61,6 +70,7 @@ uint64_t uv__hrtime(uv_clocktype_t type) { abort(); return mach_absolute_time() * info.numer / info.denom; +#endif } diff --git a/deps/uv/src/unix/fs.c b/deps/uv/src/unix/fs.c index 3d478b790e6c5a..e047b671651466 100644 --- a/deps/uv/src/unix/fs.c +++ b/deps/uv/src/unix/fs.c @@ -129,8 +129,23 @@ static ssize_t uv__fs_fdatasync(uv_fs_t* req) { #if defined(__linux__) || defined(__sun) || defined(__NetBSD__) return fdatasync(req->file); -#elif defined(__APPLE__) && defined(SYS_fdatasync) - return syscall(SYS_fdatasync, req->file); +#elif defined(__APPLE__) + /* Apple's fdatasync and fsync explicitly do NOT flush the drive write cache + * to the drive platters. This is in contrast to Linux's fdatasync and fsync + * which do, according to recent man pages. F_FULLFSYNC is Apple's equivalent + * for flushing buffered data to permanent storage. + */ + return fcntl(req->file, F_FULLFSYNC); +#else + return fsync(req->file); +#endif +} + + +static ssize_t uv__fs_fsync(uv_fs_t* req) { +#if defined(__APPLE__) + /* See the comment in uv__fs_fdatasync. */ + return fcntl(req->file, F_FULLFSYNC); #else return fsync(req->file); #endif @@ -798,6 +813,10 @@ static void uv__to_stat(struct stat* src, uv_stat_t* dst) { dst->st_flags = 0; dst->st_gen = 0; #elif !defined(_AIX) && ( \ + defined(__DragonFly__) || \ + defined(__FreeBSD__) || \ + defined(__OpenBSD__) || \ + defined(__NetBSD__) || \ defined(_GNU_SOURCE) || \ defined(_BSD_SOURCE) || \ defined(_SVID_SOURCE) || \ @@ -809,9 +828,7 @@ static void uv__to_stat(struct stat* src, uv_stat_t* dst) { dst->st_mtim.tv_nsec = src->st_mtim.tv_nsec; dst->st_ctim.tv_sec = src->st_ctim.tv_sec; dst->st_ctim.tv_nsec = src->st_ctim.tv_nsec; -# if defined(__DragonFly__) || \ - defined(__FreeBSD__) || \ - defined(__OpenBSD__) || \ +# if defined(__FreeBSD__) || \ defined(__NetBSD__) dst->st_birthtim.tv_sec = src->st_birthtim.tv_sec; dst->st_birthtim.tv_nsec = src->st_birthtim.tv_nsec; @@ -945,7 +962,7 @@ static void uv__fs_work(struct uv__work* w) { X(FCHOWN, fchown(req->file, req->uid, req->gid)); X(FDATASYNC, uv__fs_fdatasync(req)); X(FSTAT, uv__fs_fstat(req->file, &req->statbuf)); - X(FSYNC, fsync(req->file)); + X(FSYNC, uv__fs_fsync(req)); X(FTRUNCATE, ftruncate(req->file, req->off)); X(FUTIME, uv__fs_futime(req)); X(LSTAT, uv__fs_lstat(req->path, &req->statbuf)); diff --git a/deps/uv/src/win/error.c b/deps/uv/src/win/error.c index c512f35af979a3..642d1112e11928 100644 --- a/deps/uv/src/win/error.c +++ b/deps/uv/src/win/error.c @@ -71,6 +71,7 @@ int uv_translate_sys_error(int sys_errno) { switch (sys_errno) { case ERROR_NOACCESS: return UV_EACCES; case WSAEACCES: return UV_EACCES; + case ERROR_ELEVATION_REQUIRED: return UV_EACCES; case ERROR_ADDRESS_ALREADY_ASSOCIATED: return UV_EADDRINUSE; case WSAEADDRINUSE: return UV_EADDRINUSE; case WSAEADDRNOTAVAIL: return UV_EADDRNOTAVAIL; diff --git a/deps/uv/src/win/fs.c b/deps/uv/src/win/fs.c index dc0ac89a35293e..6902d4f1a69485 100644 --- a/deps/uv/src/win/fs.c +++ b/deps/uv/src/win/fs.c @@ -403,7 +403,6 @@ void fs__open(uv_fs_t* req) { switch (flags & (_O_RDONLY | _O_WRONLY | _O_RDWR)) { case _O_RDONLY: access = FILE_GENERIC_READ; - attributes |= FILE_FLAG_BACKUP_SEMANTICS; break; case _O_WRONLY: access = FILE_GENERIC_WRITE; @@ -418,7 +417,6 @@ void fs__open(uv_fs_t* req) { if (flags & _O_APPEND) { access &= ~FILE_WRITE_DATA; access |= FILE_APPEND_DATA; - attributes &= ~FILE_FLAG_BACKUP_SEMANTICS; } /* diff --git a/deps/uv/src/win/getaddrinfo.c b/deps/uv/src/win/getaddrinfo.c index 744f8e02629ccd..c13bfec350f27e 100644 --- a/deps/uv/src/win/getaddrinfo.c +++ b/deps/uv/src/win/getaddrinfo.c @@ -262,8 +262,7 @@ int uv_getaddrinfo(uv_loop_t* loop, int err; if (req == NULL || (node == NULL && service == NULL)) { - err = WSAEINVAL; - goto error; + return UV_EINVAL; } uv_req_init(loop, (uv_req_t*)req); diff --git a/deps/uv/src/win/process.c b/deps/uv/src/win/process.c index 855c3740816db2..bdf88d2cdd944c 100644 --- a/deps/uv/src/win/process.c +++ b/deps/uv/src/win/process.c @@ -492,7 +492,7 @@ WCHAR* quote_cmd_arg(const WCHAR *source, WCHAR *target) { * input : hello\\"world * output: "hello\\\\\"world" * input : hello world\ - * output: "hello world\" + * output: "hello world\\" */ *(target++) = L'"'; diff --git a/deps/uv/src/win/tty.c b/deps/uv/src/win/tty.c index 76dc2fab8aa3c7..1b7adf64ffcbdb 100644 --- a/deps/uv/src/win/tty.c +++ b/deps/uv/src/win/tty.c @@ -56,7 +56,11 @@ #define ANSI_BACKSLASH_SEEN 0x80 #define MAX_INPUT_BUFFER_LENGTH 8192 +#define MAX_CONSOLE_CHAR 8192 +#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING +#define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004 +#endif static void uv_tty_capture_initial_style(CONSOLE_SCREEN_BUFFER_INFO* info); static void uv_tty_update_virtual_window(CONSOLE_SCREEN_BUFFER_INFO* info); @@ -125,6 +129,14 @@ static char uv_tty_default_fg_bright = 0; static char uv_tty_default_bg_bright = 0; static char uv_tty_default_inverse = 0; +typedef enum { + UV_SUPPORTED, + UV_UNCHECKED, + UV_UNSUPPORTED +} uv_vtermstate_t; +/* Determine whether or not ANSI support is enabled. */ +static uv_vtermstate_t uv__vterm_state = UV_UNCHECKED; +static void uv__determine_vterm_state(HANDLE handle); void uv_console_init() { if (uv_sem_init(&uv_tty_output_lock, 1)) @@ -168,6 +180,9 @@ int uv_tty_init(uv_loop_t* loop, uv_tty_t* tty, uv_file fd, int readable) { /* shared between all uv_tty_t handles. */ uv_sem_wait(&uv_tty_output_lock); + if (uv__vterm_state == UV_UNCHECKED) + uv__determine_vterm_state(handle); + /* Store the global tty output handle. This handle is used by TTY read */ /* streams to update the virtual window when a CONSOLE_BUFFER_SIZE_EVENT */ /* is received. */ @@ -989,6 +1004,9 @@ int uv_tty_read_start(uv_tty_t* handle, uv_alloc_cb alloc_cb, if (handle->tty.rd.last_key_len > 0) { SET_REQ_SUCCESS(&handle->read_req); uv_insert_pending_req(handle->loop, (uv_req_t*) &handle->read_req); + /* Make sure no attempt is made to insert it again until it's handled. */ + handle->flags |= UV_HANDLE_READ_PENDING; + handle->reqs_pending++; return 0; } @@ -1602,17 +1620,29 @@ static int uv_tty_write_bufs(uv_tty_t* handle, DWORD* error) { /* We can only write 8k characters at a time. Windows can't handle */ /* much more characters in a single console write anyway. */ - WCHAR utf16_buf[8192]; + WCHAR utf16_buf[MAX_CONSOLE_CHAR]; + WCHAR* utf16_buffer; DWORD utf16_buf_used = 0; - unsigned int i; - -#define FLUSH_TEXT() \ - do { \ - if (utf16_buf_used > 0) { \ - uv_tty_emit_text(handle, utf16_buf, utf16_buf_used, error); \ - utf16_buf_used = 0; \ - } \ - } while (0) + unsigned int i, len, max_len, pos; + int allocate = 0; + +#define FLUSH_TEXT() \ + do { \ + pos = 0; \ + do { \ + len = utf16_buf_used - pos; \ + if (len > MAX_CONSOLE_CHAR) \ + len = MAX_CONSOLE_CHAR; \ + uv_tty_emit_text(handle, &utf16_buffer[pos], len, error); \ + pos += len; \ + } while (pos < utf16_buf_used); \ + if (allocate) { \ + uv__free(utf16_buffer); \ + allocate = 0; \ + utf16_buffer = utf16_buf; \ + } \ + utf16_buf_used = 0; \ + } while (0) #define ENSURE_BUFFER_SPACE(wchars_needed) \ if (wchars_needed > ARRAY_SIZE(utf16_buf) - utf16_buf_used) { \ @@ -1630,12 +1660,48 @@ static int uv_tty_write_bufs(uv_tty_t* handle, /* state. */ *error = ERROR_SUCCESS; + utf16_buffer = utf16_buf; + uv_sem_wait(&uv_tty_output_lock); for (i = 0; i < nbufs; i++) { uv_buf_t buf = bufs[i]; unsigned int j; + if (uv__vterm_state == UV_SUPPORTED && buf.len > 0) { + utf16_buf_used = MultiByteToWideChar(CP_UTF8, + 0, + buf.base, + buf.len, + NULL, + 0); + + if (utf16_buf_used == 0) { + *error = GetLastError(); + break; + } + + max_len = (utf16_buf_used + 1) * sizeof(WCHAR); + allocate = max_len > MAX_CONSOLE_CHAR; + if (allocate) + utf16_buffer = uv__malloc(max_len); + if (!MultiByteToWideChar(CP_UTF8, + 0, + buf.base, + buf.len, + utf16_buffer, + utf16_buf_used)) { + if (allocate) + uv__free(utf16_buffer); + *error = GetLastError(); + break; + } + + FLUSH_TEXT(); + + continue; + } + for (j = 0; j < buf.len; j++) { unsigned char c = buf.base[j]; @@ -2193,3 +2259,24 @@ int uv_tty_reset_mode(void) { /* Not necessary to do anything. */ return 0; } + +/* Determine whether or not this version of windows supports + * proper ANSI color codes. Should be supported as of windows + * 10 version 1511, build number 10.0.10586. + */ +static void uv__determine_vterm_state(HANDLE handle) { + DWORD dwMode = 0; + + if (!GetConsoleMode(handle, &dwMode)) { + uv__vterm_state = UV_UNSUPPORTED; + return; + } + + dwMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING; + if (!SetConsoleMode(handle, dwMode)) { + uv__vterm_state = UV_UNSUPPORTED; + return; + } + + uv__vterm_state = UV_SUPPORTED; +} diff --git a/deps/uv/test/test-error.c b/deps/uv/test/test-error.c index 4c4efa30cddd4b..ff53eb1d777903 100644 --- a/deps/uv/test/test-error.c +++ b/deps/uv/test/test-error.c @@ -53,6 +53,7 @@ TEST_IMPL(error_message) { TEST_IMPL(sys_error) { #if defined(_WIN32) ASSERT(uv_translate_sys_error(ERROR_NOACCESS) == UV_EACCES); + ASSERT(uv_translate_sys_error(ERROR_ELEVATION_REQUIRED) == UV_EACCES); ASSERT(uv_translate_sys_error(WSAEADDRINUSE) == UV_EADDRINUSE); ASSERT(uv_translate_sys_error(ERROR_BAD_PIPE) == UV_EPIPE); #else diff --git a/deps/uv/test/test-fs.c b/deps/uv/test/test-fs.c index 06718f285ed7ae..70a23999624741 100644 --- a/deps/uv/test/test-fs.c +++ b/deps/uv/test/test-fs.c @@ -1141,11 +1141,15 @@ TEST_IMPL(fs_fstat) { ASSERT(s->st_mtim.tv_nsec == t.st_mtimensec); ASSERT(s->st_ctim.tv_sec == t.st_ctime); ASSERT(s->st_ctim.tv_nsec == t.st_ctimensec); -#elif defined(__sun) || \ - defined(_GNU_SOURCE) || \ - defined(_BSD_SOURCE) || \ - defined(_SVID_SOURCE) || \ - defined(_XOPEN_SOURCE) || \ +#elif defined(__sun) || \ + defined(__DragonFly__) || \ + defined(__FreeBSD__) || \ + defined(__OpenBSD__) || \ + defined(__NetBSD__) || \ + defined(_GNU_SOURCE) || \ + defined(_BSD_SOURCE) || \ + defined(_SVID_SOURCE) || \ + defined(_XOPEN_SOURCE) || \ defined(_DEFAULT_SOURCE) ASSERT(s->st_atim.tv_sec == t.st_atim.tv_sec); ASSERT(s->st_atim.tv_nsec == t.st_atim.tv_nsec); @@ -1153,10 +1157,8 @@ TEST_IMPL(fs_fstat) { ASSERT(s->st_mtim.tv_nsec == t.st_mtim.tv_nsec); ASSERT(s->st_ctim.tv_sec == t.st_ctim.tv_sec); ASSERT(s->st_ctim.tv_nsec == t.st_ctim.tv_nsec); -# if defined(__DragonFly__) || \ - defined(__FreeBSD__) || \ - defined(__OpenBSD__) || \ - defined(__NetBSD__) +# if defined(__FreeBSD__) || \ + defined(__NetBSD__) ASSERT(s->st_birthtim.tv_sec == t.st_birthtim.tv_sec); ASSERT(s->st_birthtim.tv_nsec == t.st_birthtim.tv_nsec); ASSERT(s->st_flags == t.st_flags); diff --git a/deps/uv/test/test-getaddrinfo.c b/deps/uv/test/test-getaddrinfo.c index 6b644a8d442a3a..03dc126956162c 100644 --- a/deps/uv/test/test-getaddrinfo.c +++ b/deps/uv/test/test-getaddrinfo.c @@ -83,6 +83,13 @@ static void getaddrinfo_cuncurrent_cb(uv_getaddrinfo_t* handle, TEST_IMPL(getaddrinfo_fail) { uv_getaddrinfo_t req; + ASSERT(UV_EINVAL == uv_getaddrinfo(uv_default_loop(), + &req, + (uv_getaddrinfo_cb) abort, + NULL, + NULL, + NULL)); + /* Use a FQDN by ending in a period */ ASSERT(0 == uv_getaddrinfo(uv_default_loop(), &req, diff --git a/deps/uv/test/test-list.h b/deps/uv/test/test-list.h index 08886a6f4a5b31..be3f9069cc7779 100644 --- a/deps/uv/test/test-list.h +++ b/deps/uv/test/test-list.h @@ -47,6 +47,8 @@ TEST_DECLARE (semaphore_3) TEST_DECLARE (tty) #ifdef _WIN32 TEST_DECLARE (tty_raw) +TEST_DECLARE (tty_empty_write) +TEST_DECLARE (tty_large_write) #endif TEST_DECLARE (tty_file) TEST_DECLARE (tty_pty) @@ -404,6 +406,8 @@ TASK_LIST_START TEST_ENTRY (tty) #ifdef _WIN32 TEST_ENTRY (tty_raw) + TEST_ENTRY (tty_empty_write) + TEST_ENTRY (tty_large_write) #endif TEST_ENTRY (tty_file) TEST_ENTRY (tty_pty) diff --git a/deps/uv/test/test-tty.c b/deps/uv/test/test-tty.c index d03f07a4418e49..d1f7deb2319e44 100644 --- a/deps/uv/test/test-tty.c +++ b/deps/uv/test/test-tty.c @@ -212,6 +212,93 @@ TEST_IMPL(tty_raw) { MAKE_VALGRIND_HAPPY(); return 0; } + +TEST_IMPL(tty_empty_write) { + int r; + int ttyout_fd; + uv_tty_t tty_out; + char dummy[1]; + uv_buf_t bufs[1]; + uv_loop_t* loop; + + /* Make sure we have an FD that refers to a tty */ + HANDLE handle; + + loop = uv_default_loop(); + + handle = CreateFileA("conout$", + GENERIC_READ | GENERIC_WRITE, + FILE_SHARE_READ | FILE_SHARE_WRITE, + NULL, + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, + NULL); + ASSERT(handle != INVALID_HANDLE_VALUE); + ttyout_fd = _open_osfhandle((intptr_t) handle, 0); + + ASSERT(ttyout_fd >= 0); + + ASSERT(UV_TTY == uv_guess_handle(ttyout_fd)); + + r = uv_tty_init(uv_default_loop(), &tty_out, ttyout_fd, 0); /* Writable. */ + ASSERT(r == 0); + + bufs[0].len = 0; + bufs[0].base = &dummy; + + r = uv_try_write((uv_stream_t*) &tty_out, bufs, 1); + ASSERT(r == 0); + + uv_close((uv_handle_t*) &tty_out, NULL); + + uv_run(loop, UV_RUN_DEFAULT); + + MAKE_VALGRIND_HAPPY(); + return 0; +} + +TEST_IMPL(tty_large_write) { + int r; + int ttyout_fd; + uv_tty_t tty_out; + char dummy[10000]; + uv_buf_t bufs[1]; + uv_loop_t* loop; + + /* Make sure we have an FD that refers to a tty */ + HANDLE handle; + + loop = uv_default_loop(); + + handle = CreateFileA("conout$", + GENERIC_READ | GENERIC_WRITE, + FILE_SHARE_READ | FILE_SHARE_WRITE, + NULL, + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, + NULL); + ASSERT(handle != INVALID_HANDLE_VALUE); + ttyout_fd = _open_osfhandle((intptr_t) handle, 0); + + ASSERT(ttyout_fd >= 0); + + ASSERT(UV_TTY == uv_guess_handle(ttyout_fd)); + + r = uv_tty_init(uv_default_loop(), &tty_out, ttyout_fd, 0); /* Writable. */ + ASSERT(r == 0); + + bufs[0] = uv_buf_init(dummy, sizeof(dummy)); + + r = uv_try_write((uv_stream_t*) &tty_out, bufs, 1); + ASSERT(r == 10000); + + uv_close((uv_handle_t*) &tty_out, NULL); + + uv_run(loop, UV_RUN_DEFAULT); + + MAKE_VALGRIND_HAPPY(); + return 0; +} #endif From 35334273b983c4e678b986d0c679c00952295a68 Mon Sep 17 00:00:00 2001 From: Brian White Date: Wed, 11 Jan 2017 23:30:24 -0500 Subject: [PATCH 095/291] benchmark: don't lint autogenerated modules PR-URL: https://github.com/nodejs/node/pull/10756 Reviewed-By: Rich Trott Reviewed-By: Teddy Katz Reviewed-By: James M Snell Reviewed-By: Gibson Fahnestock Reviewed-By: Luigi Pinca Reviewed-By: Colin Ihrig --- .eslintignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.eslintignore b/.eslintignore index 6791fbf312a08b..1ccb8f831baa0b 100644 --- a/.eslintignore +++ b/.eslintignore @@ -6,3 +6,4 @@ test/disabled test/tmp*/ tools/eslint node_modules +benchmark/tmp/ From ebcf834c140b7fbccc8823013b56cd14a44375b9 Mon Sep 17 00:00:00 2001 From: Sam Roberts Date: Sat, 17 Dec 2016 07:05:45 -0800 Subject: [PATCH 096/291] test: move common tls connect setup into fixtures TLS connection setup boilerplate is common to many TLS tests, factor it into a test fixture so tests are clearer to read and faster to write. PR-URL: https://github.com/nodejs/node/pull/10389 Reviewed-By: James M Snell Reviewed-By: Gibson Fahnestock Reviewed-By: Michael Dawson --- test/fixtures/tls-connect.js | 101 ++++++++++++++++++ test/parallel/test-tls-addca.js | 78 ++++++-------- .../test-tls-connect-secure-context.js | 48 ++++----- test/parallel/test-tls-peer-certificate.js | 72 +++++-------- 4 files changed, 181 insertions(+), 118 deletions(-) create mode 100644 test/fixtures/tls-connect.js diff --git a/test/fixtures/tls-connect.js b/test/fixtures/tls-connect.js new file mode 100644 index 00000000000000..72f83736bf370e --- /dev/null +++ b/test/fixtures/tls-connect.js @@ -0,0 +1,101 @@ +// One shot call to connect a TLS client and server based on options to +// tls.createServer() and tls.connect(), so assertions can be made on both ends +// of the connection. +'use strict'; + +const common = require('../common'); +const fs = require('fs'); +const join = require('path').join; +const tls = require('tls'); +const util = require('util'); + +module.exports = exports = checkCrypto; + +function checkCrypto() { + if (!common.hasCrypto) { + common.skip('missing crypto'); + process.exit(0); + } + return exports; +} + +exports.assert = require('assert'); +exports.debug = util.debuglog('test'); +exports.tls = tls; + +// Pre-load keys from common fixtures for ease of use by tests. +const keys = exports.keys = { + agent1: load('agent1', 'ca1'), + agent2: load('agent2', 'agent2'), + agent3: load('agent3', 'ca2'), + agent4: load('agent4', 'ca2'), + agent5: load('agent5', 'ca2'), + agent6: load('agent6', 'ca1'), + agent7: load('agent7', 'fake-cnnic-root'), + ec: load('ec', 'ec'), +}; + +function load(cert, issuer) { + issuer = issuer || cert; // Assume self-signed if no issuer + const id = { + key: read(cert + '-key.pem'), + cert: read(cert + '-cert.pem'), + ca: read(issuer + '-cert.pem'), + }; + return id; +} + +function read(file) { + return fs.readFileSync(join(common.fixturesDir, 'keys', file), 'binary'); +} + +exports.connect = function connect(options, callback) { + callback = common.mustCall(callback); + + const server = {}; + const client = {}; + const pair = { + server: server, + client: client, + }; + + tls.createServer(options.server, function(conn) { + server.conn = conn; + conn.pipe(conn); + maybeCallback() + }).listen(0, function() { + server.server = this; + + const optClient = util._extend({ + port: this.address().port, + }, options.client); + + tls.connect(optClient) + .on('secureConnect', function() { + client.conn = this; + maybeCallback(); + }) + .on('error', function(err) { + client.err = err; + client.conn = this; + maybeCallback(); + }); + }); + + function maybeCallback() { + if (!callback) + return; + if (server.conn && (client.conn || client.err)) { + const err = pair.client.err || pair.server.err; + callback(err, pair, cleanup); + callback = null; + + function cleanup() { + if (server.server) + server.server.close(); + if (client.conn) + client.conn.end(); + } + } + } +} diff --git a/test/parallel/test-tls-addca.js b/test/parallel/test-tls-addca.js index 0e9571efdf0abf..7a6f9a77516e22 100644 --- a/test/parallel/test-tls-addca.js +++ b/test/parallel/test-tls-addca.js @@ -1,62 +1,50 @@ 'use strict'; const common = require('../common'); -const fs = require('fs'); -if (!common.hasCrypto) { - common.skip('missing crypto'); - return; -} -const tls = require('tls'); - -function filenamePEM(n) { - return require('path').join(common.fixturesDir, 'keys', n + '.pem'); -} +// Adding a CA certificate to contextWithCert should not also add it to +// contextWithoutCert. This is tested by trying to connect to a server that +// depends on that CA using contextWithoutCert. -function loadPEM(n) { - return fs.readFileSync(filenamePEM(n)); -} +const join = require('path').join; +const { + assert, connect, keys, tls +} = require(join(common.fixturesDir, 'tls-connect'))(); -const caCert = loadPEM('ca1-cert'); const contextWithoutCert = tls.createSecureContext({}); const contextWithCert = tls.createSecureContext({}); -// Adding a CA certificate to contextWithCert should not also add it to -// contextWithoutCert. This is tested by trying to connect to a server that -// depends on that CA using contextWithoutCert. -contextWithCert.context.addCACert(caCert); +contextWithCert.context.addCACert(keys.agent1.ca); const serverOptions = { - key: loadPEM('agent1-key'), - cert: loadPEM('agent1-cert'), + key: keys.agent1.key, + cert: keys.agent1.cert, }; -const server = tls.createServer(serverOptions, function() {}); const clientOptions = { - port: undefined, - ca: [caCert], + ca: [keys.agent1.ca], servername: 'agent1', rejectUnauthorized: true, }; -function startTest() { - // This client should fail to connect because it doesn't trust the CA +// This client should fail to connect because it doesn't trust the CA +// certificate. +clientOptions.secureContext = contextWithoutCert; + +connect({ + client: clientOptions, + server: serverOptions, +}, function(err, pair, cleanup) { + assert(err); + assert.strictEqual(err.message, 'unable to verify the first certificate'); + cleanup(); + + // This time it should connect because contextWithCert includes the needed CA // certificate. - clientOptions.secureContext = contextWithoutCert; - clientOptions.port = server.address().port; - const client = tls.connect(clientOptions, common.fail); - client.on('error', common.mustCall(() => { - client.destroy(); - - // This time it should connect because contextWithCert includes the needed - // CA certificate. - clientOptions.secureContext = contextWithCert; - const client2 = tls.connect(clientOptions, common.mustCall(() => { - client2.destroy(); - server.close(); - })); - client2.on('error', (e) => { - console.log(e); - }); - })); -} - -server.listen(0, startTest); + clientOptions.secureContext = contextWithCert; + connect({ + client: clientOptions, + server: serverOptions, + }, function(err, pair, cleanup) { + assert.ifError(err); + cleanup(); + }); +}); diff --git a/test/parallel/test-tls-connect-secure-context.js b/test/parallel/test-tls-connect-secure-context.js index 9e1059f169cf62..d1552a62169207 100644 --- a/test/parallel/test-tls-connect-secure-context.js +++ b/test/parallel/test-tls-connect-secure-context.js @@ -1,37 +1,25 @@ 'use strict'; const common = require('../common'); -if (!common.hasCrypto) { - common.skip('missing crypto'); - return; -} -const tls = require('tls'); +// Verify connection with explicitly created client SecureContext. -const fs = require('fs'); -const path = require('path'); +const join = require('path').join; +const { + assert, connect, keys, tls +} = require(join(common.fixturesDir, 'tls-connect'))(); -const keysDir = path.join(common.fixturesDir, 'keys'); - -const ca = fs.readFileSync(path.join(keysDir, 'ca1-cert.pem')); -const cert = fs.readFileSync(path.join(keysDir, 'agent1-cert.pem')); -const key = fs.readFileSync(path.join(keysDir, 'agent1-key.pem')); - -const server = tls.createServer({ - cert: cert, - key: key -}, function(c) { - c.end(); -}).listen(0, function() { - const secureContext = tls.createSecureContext({ - ca: ca - }); - - const socket = tls.connect({ - secureContext: secureContext, +connect({ + client: { servername: 'agent1', - port: this.address().port - }, common.mustCall(function() { - server.close(); - socket.end(); - })); + secureContext: tls.createSecureContext({ + ca: keys.agent1.ca, + }), + }, + server: { + cert: keys.agent1.cert, + key: keys.agent1.key, + }, +}, function(err, pair, cleanup) { + assert.ifError(err); + return cleanup(); }); diff --git a/test/parallel/test-tls-peer-certificate.js b/test/parallel/test-tls-peer-certificate.js index ddbbf72a6309e7..eb5be6dcb2241b 100644 --- a/test/parallel/test-tls-peer-certificate.js +++ b/test/parallel/test-tls-peer-certificate.js @@ -1,53 +1,39 @@ 'use strict'; const common = require('../common'); -const assert = require('assert'); -if (!common.hasCrypto) { - common.skip('missing crypto'); - return; -} -const tls = require('tls'); +// Verify that detailed getPeerCertificate() return value has all certs. -const fs = require('fs'); -const util = require('util'); const join = require('path').join; +const { + assert, connect, debug, keys +} = require(join(common.fixturesDir, 'tls-connect'))(); -const options = { - key: fs.readFileSync(join(common.fixturesDir, 'keys', 'agent1-key.pem')), - cert: fs.readFileSync(join(common.fixturesDir, 'keys', 'agent1-cert.pem')), - ca: [ fs.readFileSync(join(common.fixturesDir, 'keys', 'ca1-cert.pem')) ] -}; +connect({ + client: {rejectUnauthorized: false}, + server: keys.agent1, +}, function(err, pair, cleanup) { + assert.ifError(err); + const socket = pair.client.conn; + let peerCert = socket.getPeerCertificate(); + assert.ok(!peerCert.issuerCertificate); -const server = tls.createServer(options, function(cleartext) { - cleartext.end('World'); -}); -server.listen(0, common.mustCall(function() { - const socket = tls.connect({ - port: this.address().port, - rejectUnauthorized: false - }, common.mustCall(function() { - let peerCert = socket.getPeerCertificate(); - assert.ok(!peerCert.issuerCertificate); + peerCert = socket.getPeerCertificate(true); + debug('peerCert:\n', peerCert); - // Verify that detailed return value has all certs - peerCert = socket.getPeerCertificate(true); - assert.ok(peerCert.issuerCertificate); + assert.ok(peerCert.issuerCertificate); + assert.strictEqual(peerCert.subject.emailAddress, 'ry@tinyclouds.org'); + assert.strictEqual(peerCert.serialNumber, '9A84ABCFB8A72AC0'); + assert.strictEqual(peerCert.exponent, '0x10001'); + assert.strictEqual( + peerCert.fingerprint, + '8D:06:3A:B3:E5:8B:85:29:72:4F:7D:1B:54:CD:95:19:3C:EF:6F:AA' + ); + assert.deepStrictEqual(peerCert.infoAccess['OCSP - URI'], + [ 'http://ocsp.nodejs.org/' ]); - console.error(util.inspect(peerCert)); - assert.strictEqual(peerCert.subject.emailAddress, 'ry@tinyclouds.org'); - assert.strictEqual(peerCert.serialNumber, '9A84ABCFB8A72AC0'); - assert.strictEqual(peerCert.exponent, '0x10001'); - assert.strictEqual( - peerCert.fingerprint, - '8D:06:3A:B3:E5:8B:85:29:72:4F:7D:1B:54:CD:95:19:3C:EF:6F:AA' - ); - assert.deepStrictEqual(peerCert.infoAccess['OCSP - URI'], - [ 'http://ocsp.nodejs.org/' ]); + const issuer = peerCert.issuerCertificate; + assert.strictEqual(issuer.issuerCertificate, issuer); + assert.strictEqual(issuer.serialNumber, '8DF21C01468AF393'); - const issuer = peerCert.issuerCertificate; - assert.strictEqual(issuer.issuerCertificate, issuer); - assert.strictEqual(issuer.serialNumber, '8DF21C01468AF393'); - server.close(); - })); - socket.end('Hello'); -})); + return cleanup(); +}); From 97a8bd20c626cf395faa21af94f88278bb407603 Mon Sep 17 00:00:00 2001 From: Sam Roberts Date: Tue, 20 Dec 2016 10:52:32 -0800 Subject: [PATCH 097/291] test: check tls server verification with addCACert SecureContext.addCACert() adds to the existing root store, preserving root cert entries. option.ca is applied without calling SecureContext.addRootCerts() so should add to the default, empty, root store. This test confirms that the built-in root CAs are not included when options.ca is used. Based on: https://github.com/shigeki/node/commit/acd5837fd737351dd953b0387695705067cd69cb PR-URL: https://github.com/nodejs/node/pull/10389 Reviewed-By: James M Snell Reviewed-By: Gibson Fahnestock Reviewed-By: Michael Dawson --- test/internet/test-tls-add-ca-cert.js | 55 +++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 test/internet/test-tls-add-ca-cert.js diff --git a/test/internet/test-tls-add-ca-cert.js b/test/internet/test-tls-add-ca-cert.js new file mode 100644 index 00000000000000..d4e85302856969 --- /dev/null +++ b/test/internet/test-tls-add-ca-cert.js @@ -0,0 +1,55 @@ +'use strict'; +const common = require('../common'); + +if (!common.hasCrypto) { + common.skip('missing crypto'); + return; +} + +// Test interaction of compiled-in CAs with user-provided CAs. + +const assert = require('assert'); +const fs = require('fs'); +const tls = require('tls'); + +function filenamePEM(n) { + return require('path').join(common.fixturesDir, 'keys', n + '.pem'); +} + +function loadPEM(n) { + return fs.readFileSync(filenamePEM(n)); +} + +const caCert = loadPEM('ca1-cert'); + +var opts = { + host: 'www.nodejs.org', + port: 443, + rejectUnauthorized: true +}; + +// Success relies on the compiled in well-known root CAs +tls.connect(opts, common.mustCall(end)); + +// The .ca option replaces the well-known roots, so connection fails. +opts.ca = caCert; +tls.connect(opts, fail).on('error', common.mustCall((err) => { + assert.strictEqual(err.message, 'unable to get local issuer certificate'); +})); + +function fail() { + assert(false, 'should fail to connect'); +} + +// New secure contexts have the well-known root CAs. +opts.secureContext = tls.createSecureContext(); +tls.connect(opts, common.mustCall(end)); + +// Explicit calls to addCACert() add to the default well-known roots, instead +// of replacing, so connection still succeeds. +opts.secureContext.context.addCACert(caCert); +tls.connect(opts, common.mustCall(end)); + +function end() { + this.end(); +} From 542f65c66bcc36b0c47492ebf97d034a9725b4d8 Mon Sep 17 00:00:00 2001 From: Sam Roberts Date: Tue, 20 Dec 2016 14:16:29 -0800 Subject: [PATCH 098/291] test: tls cert chain completion scenarios PR-URL: https://github.com/nodejs/node/pull/10389 Reviewed-By: James M Snell Reviewed-By: Gibson Fahnestock Reviewed-By: Michael Dawson --- test/parallel/test-tls-cert-chains-concat.js | 50 ++++++++++++++++++++ test/parallel/test-tls-cert-chains-in-ca.js | 46 ++++++++++++++++++ 2 files changed, 96 insertions(+) create mode 100644 test/parallel/test-tls-cert-chains-concat.js create mode 100644 test/parallel/test-tls-cert-chains-in-ca.js diff --git a/test/parallel/test-tls-cert-chains-concat.js b/test/parallel/test-tls-cert-chains-concat.js new file mode 100644 index 00000000000000..d53edef89842b9 --- /dev/null +++ b/test/parallel/test-tls-cert-chains-concat.js @@ -0,0 +1,50 @@ +'use strict'; +const common = require('../common'); + +// Check cert chain is received by client, and is completed with the ca cert +// known to the client. + +const join = require('path').join; +const { + assert, connect, debug, keys +} = require(join(common.fixturesDir, 'tls-connect'))(); + +// agent6-cert.pem includes cert for agent6 and ca3 +connect({ + client: { + checkServerIdentity: (servername, cert) => { }, + ca: keys.agent6.ca, + }, + server: { + cert: keys.agent6.cert, + key: keys.agent6.key, + }, +}, function(err, pair, cleanup) { + assert.ifError(err); + + const peer = pair.client.conn.getPeerCertificate(); + debug('peer:\n', peer); + assert.strictEqual(peer.subject.emailAddress, 'adam.lippai@tresorit.com'); + assert.strictEqual(peer.subject.CN, 'Ádám Lippai'), + assert.strictEqual(peer.issuer.CN, 'ca3'); + assert.strictEqual(peer.serialNumber, 'C4CD893EF9A75DCC'); + + const next = pair.client.conn.getPeerCertificate(true).issuerCertificate; + const root = next.issuerCertificate; + delete next.issuerCertificate; + debug('next:\n', next); + assert.strictEqual(next.subject.CN, 'ca3'); + assert.strictEqual(next.issuer.CN, 'ca1'); + assert.strictEqual(next.serialNumber, '9A84ABCFB8A72ABF'); + + debug('root:\n', root); + assert.strictEqual(root.subject.CN, 'ca1'); + assert.strictEqual(root.issuer.CN, 'ca1'); + assert.strictEqual(root.serialNumber, '8DF21C01468AF393'); + + // No client cert, so empty object returned. + assert.deepStrictEqual(pair.server.conn.getPeerCertificate(), {}); + assert.deepStrictEqual(pair.server.conn.getPeerCertificate(true), {}); + + return cleanup(); +}); diff --git a/test/parallel/test-tls-cert-chains-in-ca.js b/test/parallel/test-tls-cert-chains-in-ca.js new file mode 100644 index 00000000000000..69f62c3f72d859 --- /dev/null +++ b/test/parallel/test-tls-cert-chains-in-ca.js @@ -0,0 +1,46 @@ +'use strict'; +const common = require('../common'); + +// Check cert chain is received by client, and is completed with the ca cert +// known to the client. + +const join = require('path').join; +const { + assert, connect, debug, keys +} = require(join(common.fixturesDir, 'tls-connect'))(); + + +// agent6-cert.pem includes cert for agent6 and ca3, split it apart and +// provide ca3 in the .ca property. +const agent6Chain = keys.agent6.cert.split('-----END CERTIFICATE-----') + .map((c) => { return c + '-----END CERTIFICATE-----'; }); +const agent6End = agent6Chain[0]; +const agent6Middle = agent6Chain[1]; +connect({ + client: { + checkServerIdentity: (servername, cert) => { }, + ca: keys.agent6.ca, + }, + server: { + cert: agent6End, + key: keys.agent6.key, + ca: agent6Middle, + }, +}, function(err, pair, cleanup) { + assert.ifError(err); + + const peer = pair.client.conn.getPeerCertificate(); + debug('peer:\n', peer); + assert.strictEqual(peer.serialNumber, 'C4CD893EF9A75DCC'); + + const next = pair.client.conn.getPeerCertificate(true).issuerCertificate; + const root = next.issuerCertificate; + delete next.issuerCertificate; + debug('next:\n', next); + assert.strictEqual(next.serialNumber, '9A84ABCFB8A72ABF'); + + debug('root:\n', root); + assert.strictEqual(root.serialNumber, '8DF21C01468AF393'); + + return cleanup(); +}); From 1fca69c263ec10abc03281b13628b9ec541956ba Mon Sep 17 00:00:00 2001 From: Sam Roberts Date: Wed, 21 Dec 2016 09:33:13 -0800 Subject: [PATCH 099/291] doc,test: tls .ca option supports multi-PEM files PR-URL: https://github.com/nodejs/node/pull/10389 Reviewed-By: James M Snell Reviewed-By: Gibson Fahnestock Reviewed-By: Michael Dawson --- doc/api/tls.md | 19 +++++++++++++++---- test/parallel/test-tls-ca-concat.js | 24 ++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 4 deletions(-) create mode 100644 test/parallel/test-tls-ca-concat.js diff --git a/doc/api/tls.md b/doc/api/tls.md index 64fd343c0449d5..f6bc19da78d264 100644 --- a/doc/api/tls.md +++ b/doc/api/tls.md @@ -909,10 +909,21 @@ added: v0.11.13 the same order as their private keys in `key`. If the intermediate certificates are not provided, the peer will not be able to validate the certificate, and the handshake will fail. - * `ca`{string|string[]|Buffer|Buffer[]} Optional CA certificates to trust. - Default is the well-known CAs from Mozilla. When connecting to peers that - use certificates issued privately, or self-signed, the private root CA or - self-signed certificate must be provided to verify the peer. + * `ca` {string|string[]|Buffer|Buffer[]} Optionally override the trusted CA + certificates. Default is to trust the well-known CAs curated by Mozilla. + Mozilla's CAs are completely replaced when CAs are explicitly specified + using this option. The value can be a string or Buffer, or an Array of + strings and/or Buffers. Any string or Buffer can contain multiple PEM CAs + concatenated together. The peer's certificate must be chainable to a CA + trusted by the server for the connection to be authenticated. When using + certificates that are not chainable to a well-known CA, the certificate's CA + must be explicitly specified as a trusted or the connection will fail to + authenticate. + If the peer uses a certificate that doesn't match or chain to one of the + default CAs, use the `ca` option to provide a CA certificate that the peer's + certificate can match or chain to. + For self-signed certificates, the certificate is its own CA, and must be + provided. * `crl` {string|string[]|Buffer|Buffer[]} Optional PEM formatted CRLs (Certificate Revocation Lists). * `ciphers` {string} Optional cipher suite specification, replacing the diff --git a/test/parallel/test-tls-ca-concat.js b/test/parallel/test-tls-ca-concat.js new file mode 100644 index 00000000000000..65c837bed9dc37 --- /dev/null +++ b/test/parallel/test-tls-ca-concat.js @@ -0,0 +1,24 @@ +'use strict'; +const common = require('../common'); + +// Check ca option can contain concatenated certs by prepending an unrelated +// non-CA cert and showing that agent6's CA root is still found. + +const join = require('path').join; +const { + assert, connect, keys +} = require(join(common.fixturesDir, 'tls-connect'))(); + +connect({ + client: { + checkServerIdentity: (servername, cert) => { }, + ca: keys.agent1.cert + '\n' + keys.agent6.ca, + }, + server: { + cert: keys.agent6.cert, + key: keys.agent6.key, + }, +}, function(err, pair, cleanup) { + assert.ifError(err); + return cleanup(); +}); From c6aeb4491b30afe3e5c9f87a41848c2a980b7faf Mon Sep 17 00:00:00 2001 From: Sam Roberts Date: Thu, 12 Jan 2017 11:36:20 -0800 Subject: [PATCH 100/291] test: fix linting for test-tls-add-ca-cert.js Fix lint error introduced in ea72331af PR-URL: https://github.com/nodejs/node/pull/10771 Reviewed-By: Colin Ihrig Reviewed-By: Anna Henningsen --- test/internet/test-tls-add-ca-cert.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/internet/test-tls-add-ca-cert.js b/test/internet/test-tls-add-ca-cert.js index d4e85302856969..05f3b4dc10e36c 100644 --- a/test/internet/test-tls-add-ca-cert.js +++ b/test/internet/test-tls-add-ca-cert.js @@ -22,7 +22,7 @@ function loadPEM(n) { const caCert = loadPEM('ca1-cert'); -var opts = { +const opts = { host: 'www.nodejs.org', port: 443, rejectUnauthorized: true From 6b540243240662484439aa9b0cd09dceb620ac19 Mon Sep 17 00:00:00 2001 From: Gibson Fahnestock Date: Tue, 10 Jan 2017 13:43:08 +0000 Subject: [PATCH 101/291] test: use realpath for NODE_TEST_DIR in common.js If you don't specify NODE_TEST_DIR, common.tmpDir will resolve to the realpath of `node/test`. If you do specify NODE_TEST_DIR (with the environment variable or by running or by running tools/test.py --test-dir=x), common.tmpDir (which is resolved from testRoot) uses the symbolic path (doesn't resolve symlinks). This uses fs.realpathSync() to fix that. PR-URL: https://github.com/nodejs/node/pull/10723 Reviewed-By: Colin Ihrig Reviewed-By: James M Snell Reviewed-By: Sakthipriyan Vairamani Reviewed-By: Michael Dawson --- test/README.md | 2 +- test/common.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/test/README.md b/test/README.md index 8d8cec44919720..a290835cb2d4ac 100644 --- a/test/README.md +++ b/test/README.md @@ -366,7 +366,7 @@ Synchronous version of `spawnPwd`. ### tmpDir * return [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) -Path to the 'tmp' directory. +The realpath of the 'tmp' directory. ### tmpDirName * return [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) diff --git a/test/common.js b/test/common.js index 9d090d6bb786bb..0306cc2ecacbe6 100644 --- a/test/common.js +++ b/test/common.js @@ -10,7 +10,7 @@ const util = require('util'); const Timer = process.binding('timer_wrap').Timer; const testRoot = process.env.NODE_TEST_DIR ? - path.resolve(process.env.NODE_TEST_DIR) : __dirname; + fs.realpathSync(process.env.NODE_TEST_DIR) : __dirname; exports.fixturesDir = path.join(__dirname, 'fixtures'); exports.tmpDirName = 'tmp'; From 7d917dcb27f6bdadf103f932c75ebad48904faf8 Mon Sep 17 00:00:00 2001 From: Gibson Fahnestock Date: Tue, 10 Jan 2017 15:36:07 +0000 Subject: [PATCH 102/291] test: fix temp-dir option in tools/test.py If a temp-dir is specified and already exists, the NODE_TEST_DIR environment variable will never be set. This fixes that. PR-URL: https://github.com/nodejs/node/pull/10723 Reviewed-By: Colin Ihrig Reviewed-By: James M Snell Reviewed-By: Sakthipriyan Vairamani Reviewed-By: Michael Dawson --- tools/test.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/test.py b/tools/test.py index c8edca2b991ad2..b6db2cd68e3f7e 100755 --- a/tools/test.py +++ b/tools/test.py @@ -1628,9 +1628,9 @@ def Main(): tempdir = os.environ.get('NODE_TEST_DIR') or options.temp_dir if tempdir: + os.environ['NODE_TEST_DIR'] = tempdir try: os.makedirs(tempdir) - os.environ['NODE_TEST_DIR'] = tempdir except OSError as exception: if exception.errno != errno.EEXIST: print "Could not create the temporary directory", options.temp_dir From d64e2371f630abd6d14f9cf7fb8bb5d1c3653972 Mon Sep 17 00:00:00 2001 From: Jackson Tian Date: Mon, 18 Jan 2016 17:51:15 +0800 Subject: [PATCH 103/291] readline: refactor construct Interface Remove the dependency on the arguments.length. PR-URL: https://github.com/nodejs/node/pull/4740 Reviewed-By: Colin Ihrig Reviewed-By: James M Snell Reviewed-By: Trevor Norris Reviewed-By: Benjamin Gruenbaum --- lib/readline.js | 15 +++------------ 1 file changed, 3 insertions(+), 12 deletions(-) diff --git a/lib/readline.js b/lib/readline.js index 9b925a6d990d8b..8200771ec4b39f 100644 --- a/lib/readline.js +++ b/lib/readline.js @@ -23,22 +23,13 @@ const stripVTControlCharacters = internalReadline.stripVTControlCharacters; exports.createInterface = function(input, output, completer, terminal) { - var rl; - if (arguments.length === 1) { - rl = new Interface(input); - } else { - rl = new Interface(input, output, completer, terminal); - } - return rl; + return new Interface(input, output, completer, terminal); }; function Interface(input, output, completer, terminal) { if (!(this instanceof Interface)) { - // call the constructor preserving original number of arguments - const self = Object.create(Interface.prototype); - Interface.apply(self, arguments); - return self; + return new Interface(input, output, completer, terminal); } this._sawReturnAt = 0; @@ -51,7 +42,7 @@ function Interface(input, output, completer, terminal) { let crlfDelay; let prompt = '> '; - if (arguments.length === 1) { + if (input && input.input) { // an options object was given output = input.output; completer = input.completer; From fca0da711d0fc6ca56441feb38f04e9a74cc34c4 Mon Sep 17 00:00:00 2001 From: Chase Starr Date: Wed, 11 Jan 2017 19:45:23 -0800 Subject: [PATCH 104/291] test: improve tests in pummel/test-exec * add asset.strictEqual to stdout and stderr. Fixes no-unused-vars. * replace double quotes with single PR-URL: https://github.com/nodejs/node/pull/10757 Reviewed-By: Rich Trott Reviewed-By: James M Snell Reviewed-By: Gibson Fahnestock Reviewed-By: Michael Dawson --- test/pummel/test-exec.js | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/test/pummel/test-exec.js b/test/pummel/test-exec.js index 6f6e1511b14442..18404373318917 100644 --- a/test/pummel/test-exec.js +++ b/test/pummel/test-exec.js @@ -63,6 +63,8 @@ exec(SLEEP3_COMMAND, { timeout: 50 }, function(err, stdout, stderr) { assert.ok(err); assert.ok(err.killed); assert.strictEqual(err.signal, 'SIGTERM'); + assert.strictEqual(stdout, ''); + assert.strictEqual(stderr, ''); }); @@ -85,6 +87,8 @@ function killMeTwiceCallback(err, stdout, stderr) { assert.ok(err); assert.ok(err.killed); assert.strictEqual(err.signal, 'SIGTERM'); + assert.strictEqual(stdout, ''); + assert.strictEqual(stderr, ''); // the timeout should still be in effect console.log('\'sleep 3\' was already killed. Took %d ms', diff); @@ -96,6 +100,8 @@ exec('python -c "print 200000*\'C\'"', {maxBuffer: 1000}, function(err, stdout, stderr) { assert.ok(err); assert.ok(/maxBuffer/.test(err.message)); + assert.strictEqual(stdout, ''); + assert.strictEqual(stderr, ''); }); From 5aad0ccefe70dac334b9a1bdcf479da153c16235 Mon Sep 17 00:00:00 2001 From: istinson Date: Wed, 11 Jan 2017 20:39:15 -0800 Subject: [PATCH 105/291] test: no unused args test-fs-watch-file.js PR-URL: https://github.com/nodejs/node/pull/10758 Reviewed-By: Rich Trott Reviewed-By: James M Snell Reviewed-By: Luigi Pinca Reviewed-By: Colin Ihrig Reviewed-By: Michael Dawson --- test/pummel/test-fs-watch-file.js | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/test/pummel/test-fs-watch-file.js b/test/pummel/test-fs-watch-file.js index 4e08e9e9d1cc9b..fc291cfe64c618 100644 --- a/test/pummel/test-fs-watch-file.js +++ b/test/pummel/test-fs-watch-file.js @@ -41,13 +41,13 @@ assert.throws( fs.watchFile(filepathOne); }, function(e) { - return e.message === 'watchFile requires a listener function'; + return e.message === '"watchFile()" requires a listener function'; } ); assert.doesNotThrow( function() { - fs.watchFile(filepathOne, function(curr, prev) { + fs.watchFile(filepathOne, function() { fs.unwatchFile(filepathOne); ++watchSeenOne; }); @@ -68,17 +68,17 @@ assert.throws( fs.watchFile(filepathTwo); }, function(e) { - return e.message === 'watchFile requires a listener function'; + return e.message === '"watchFile()" requires a listener function'; } ); assert.doesNotThrow( function() { - function a(curr, prev) { + function a() { fs.unwatchFile(filepathTwo, a); ++watchSeenTwo; } - function b(curr, prev) { + function b() { fs.unwatchFile(filepathTwo, b); ++watchSeenTwo; } @@ -93,10 +93,10 @@ setTimeout(function() { assert.doesNotThrow( function() { - function a(curr, prev) { + function a() { assert.ok(0); // should not run } - function b(curr, prev) { + function b() { fs.unwatchFile(filenameThree, b); ++watchSeenThree; } @@ -120,7 +120,7 @@ setTimeout(function() { assert.doesNotThrow( function() { - function a(curr, prev) { + function a() { ++watchSeenFour; assert.equal(1, watchSeenFour); fs.unwatchFile('.' + path.sep + filenameFour, a); From 06acf88117e2f8a511aeeb365c72f81841cbed51 Mon Sep 17 00:00:00 2001 From: Javis Sullivan Date: Wed, 11 Jan 2017 09:48:46 -0500 Subject: [PATCH 106/291] doc: remove duplicate properties bullet in readme PR-URL: https://github.com/nodejs/node/pull/10741 Reviewed-By: Sam Roberts Reviewed-By: James M Snell Reviewed-By: Anna Henningsen Reviewed-By: Luigi Pinca --- tools/doc/README.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/tools/doc/README.md b/tools/doc/README.md index 6985bc130d62c5..0535243e92f63b 100644 --- a/tools/doc/README.md +++ b/tools/doc/README.md @@ -99,10 +99,9 @@ This event is emitted on instances of SomeClass, not on the module itself. ``` -* Modules have (description, Properties, Functions, Classes, Examples) -* Properties have (type, description) -* Functions have (list of arguments, description) * Classes have (description, Properties, Methods, Events) * Events have (list of arguments, description) +* Functions have (list of arguments, description) * Methods have (list of arguments, description) +* Modules have (description, Properties, Functions, Classes, Examples) * Properties have (type, description) From 4de7b03a7dfa73cd76d8d5486171a073c67850e8 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Wed, 11 Jan 2017 16:30:40 -0800 Subject: [PATCH 107/291] lib: refactor bootstrap_node.js regular expression * use `+` instead of `*` where one-or-more is required * switch from String.prototype.match() to RegExp.prototype.test() PR-URL: https://github.com/nodejs/node/pull/10749 Reviewed-By: James M Snell Reviewed-By: Jeremiah Senkpiel Reviewed-By: Jackson Tian --- lib/internal/bootstrap_node.js | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/lib/internal/bootstrap_node.js b/lib/internal/bootstrap_node.js index 4e1e2aa9018b5a..71a6c529041b47 100644 --- a/lib/internal/bootstrap_node.js +++ b/lib/internal/bootstrap_node.js @@ -393,9 +393,7 @@ } function isDebugBreak() { - return process.execArgv.some((arg) => { - return arg.match(/^--debug-brk(=[0-9]*)?$/); - }); + return process.execArgv.some((arg) => /^--debug-brk(=[0-9]+)?$/.test(arg)); } function run(entryFunction) { From 8b02b4ebb4ea339bb0c159b7170b3e53716f1816 Mon Sep 17 00:00:00 2001 From: Irene Li Date: Wed, 11 Jan 2017 20:17:34 -0800 Subject: [PATCH 108/291] test: check error msg test-writeint.js PR-URL: https://github.com/nodejs/node/pull/10755 Reviewed-By: Rich Trott Reviewed-By: Jeremiah Senkpiel Reviewed-By: James M Snell Reviewed-By: Luigi Pinca Reviewed-By: Colin Ihrig --- test/parallel/test-writeint.js | 25 +++++++++++++------------ 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/test/parallel/test-writeint.js b/test/parallel/test-writeint.js index 43784fb390a1f9..9fce2bc410e1be 100644 --- a/test/parallel/test-writeint.js +++ b/test/parallel/test-writeint.js @@ -4,6 +4,7 @@ */ require('../common'); const assert = require('assert'); +const errorOutOfBounds = /^TypeError: "value" argument is out of bounds$/; function test8(clazz) { var buffer = new clazz(2); @@ -17,10 +18,10 @@ function test8(clazz) { /* Make sure we handle truncation correctly */ assert.throws(function() { buffer.writeInt8(0xabc, 0); - }); + }, errorOutOfBounds); assert.throws(function() { buffer.writeInt8(0xabc, 0); - }); + }, errorOutOfBounds); /* Make sure we handle min/max correctly */ buffer.writeInt8(0x7f, 0); @@ -30,10 +31,10 @@ function test8(clazz) { assert.equal(0x80, buffer[1]); assert.throws(function() { buffer.writeInt8(0x7f + 1, 0); - }); + }, errorOutOfBounds); assert.throws(function() { buffer.writeInt8(-0x80 - 1, 0); - }); + }, errorOutOfBounds); } @@ -70,10 +71,10 @@ function test16(clazz) { assert.equal(0x00, buffer[3]); assert.throws(function() { buffer.writeInt16BE(0x7fff + 1, 0); - }); + }, errorOutOfBounds); assert.throws(function() { buffer.writeInt16BE(-0x8000 - 1, 0); - }); + }, errorOutOfBounds); buffer.writeInt16LE(0x7fff, 0); buffer.writeInt16LE(-0x8000, 2); @@ -83,10 +84,10 @@ function test16(clazz) { assert.equal(0x80, buffer[3]); assert.throws(function() { buffer.writeInt16LE(0x7fff + 1, 0); - }); + }, errorOutOfBounds); assert.throws(function() { buffer.writeInt16LE(-0x8000 - 1, 0); - }); + }, errorOutOfBounds); } @@ -139,10 +140,10 @@ function test32(clazz) { assert.equal(0x00, buffer[7]); assert.throws(function() { buffer.writeInt32BE(0x7fffffff + 1, 0); - }); + }, errorOutOfBounds); assert.throws(function() { buffer.writeInt32BE(-0x80000000 - 1, 0); - }); + }, errorOutOfBounds); buffer.writeInt32LE(0x7fffffff, 0); buffer.writeInt32LE(-0x80000000, 4); @@ -156,10 +157,10 @@ function test32(clazz) { assert.equal(0x80, buffer[7]); assert.throws(function() { buffer.writeInt32LE(0x7fffffff + 1, 0); - }); + }, errorOutOfBounds); assert.throws(function() { buffer.writeInt32LE(-0x80000000 - 1, 0); - }); + }, errorOutOfBounds); } From ecf72d8b544a4c04a9975d1375d6e700a13261a0 Mon Sep 17 00:00:00 2001 From: Joyee Cheung Date: Wed, 11 Jan 2017 20:16:25 +0800 Subject: [PATCH 109/291] benchmark: use "confidence" in output of compare.R Use the word "confidence" to indicate the confidence level of the p value so it's easier to understand. With this change more stars in the output of compare.R means higher confidence level (lower significance level). PR-URL: https://github.com/nodejs/node/pull/10737 Refs: https://github.com/nodejs/node/pull/10439 Reviewed-By: Anna Henningsen Reviewed-By: James M Snell Reviewed-By: Andreas Madsen --- benchmark/README.md | 8 ++++---- benchmark/compare.R | 12 ++++++------ 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/benchmark/README.md b/benchmark/README.md index aa198f2b414444..8796e1e7b6ad38 100644 --- a/benchmark/README.md +++ b/benchmark/README.md @@ -161,7 +161,7 @@ For analysing the benchmark results use the `compare.R` tool. ```console $ cat compare-pr-5134.csv | Rscript benchmark/compare.R - improvement significant p.value + improvement confidence p.value string_decoder/string-decoder.js n=250000 chunk=1024 inlen=1024 encoding=ascii 12.46 % *** 1.165345e-04 string_decoder/string-decoder.js n=250000 chunk=1024 inlen=1024 encoding=base64-ascii 24.70 % *** 1.820615e-15 string_decoder/string-decoder.js n=250000 chunk=1024 inlen=1024 encoding=base64-utf8 23.60 % *** 2.105625e-12 @@ -171,7 +171,7 @@ string_decoder/string-decoder.js n=250000 chunk=1024 inlen=128 encoding=ascii ``` In the output, _improvement_ is the relative improvement of the new version, -hopefully this is positive. _significant_ tells if there is enough +hopefully this is positive. _confidence_ tells if there is enough statistical evidence to validate the _improvement_. If there is enough evidence then there will be at least one star (`*`), more stars is just better. **However if there are no stars, then you shouldn't make any conclusions based on the @@ -189,7 +189,7 @@ may require more runs to obtain (can be set with `--runs`). _For the statistically minded, the R script performs an [independent/unpaired 2-group t-test][t-test], with the null hypothesis that the performance is the -same for both versions. The significant field will show a star if the p-value +same for both versions. The confidence field will show a star if the p-value is less than `0.05`._ The `compare.R` tool can also produce a box plot by using the `--plot filename` @@ -202,7 +202,7 @@ keep the first line since that contains the header information. ```console $ cat compare-pr-5134.csv | sed '1p;/encoding=ascii/!d' | Rscript benchmark/compare.R --plot compare-plot.png - improvement significant p.value + improvement confidence p.value string_decoder/string-decoder.js n=250000 chunk=1024 inlen=1024 encoding=ascii 12.46 % *** 1.165345e-04 string_decoder/string-decoder.js n=250000 chunk=1024 inlen=128 encoding=ascii 6.70 % * 2.928003e-02 string_decoder/string-decoder.js n=250000 chunk=1024 inlen=32 encoding=ascii 7.47 % *** 5.780583e-04 diff --git a/benchmark/compare.R b/benchmark/compare.R index b4316ca7f81600..3f37cad74ad847 100644 --- a/benchmark/compare.R +++ b/benchmark/compare.R @@ -46,7 +46,7 @@ statistics = ddply(dat, "name", function(subdat) { improvement = sprintf("%.2f %%", ((new.mu - old.mu) / old.mu * 100)); p.value = NA; - significant = 'NA'; + confidence = 'NA'; # Check if there is enough data to calulate the calculate the p-value if (length(old.rate) > 1 && length(new.rate) > 1) { # Perform a statistics test to see of there actually is a difference in @@ -56,19 +56,19 @@ statistics = ddply(dat, "name", function(subdat) { # Add user friendly stars to the table. There should be at least one star # before you can say that there is an improvement. - significant = ''; + confidence = ''; if (p.value < 0.001) { - significant = '***'; + confidence = '***'; } else if (p.value < 0.01) { - significant = '**'; + confidence = '**'; } else if (p.value < 0.05) { - significant = '*'; + confidence = '*'; } } r = list( improvement = improvement, - significant = significant, + confidence = confidence, p.value = p.value ); return(data.frame(r)); From eac1871c45700e3c11236edfed73f30f713b8db2 Mon Sep 17 00:00:00 2001 From: Joyee Cheung Date: Wed, 11 Jan 2017 01:38:59 +0800 Subject: [PATCH 110/291] benchmark: improve WHATWG URL benchmarks * add benchmark to compare the performance of getting url properties between the WHATWG URL and the legacy implementation * add benchmark to compare the performance of serializing urls between the WHATWG URL and the legacy implementation * refactor the benchmark for comparing parsing performance between the two implementations PR-URL: https://github.com/nodejs/node/pull/10678 Reviewed-By: James M Snell Reviewed-By: Brian White --- .../url/legacy-vs-whatwg-url-get-prop.js | 109 ++++++++++++++++++ benchmark/url/legacy-vs-whatwg-url-parse.js | 69 +++++++++++ .../url/legacy-vs-whatwg-url-serialize.js | 71 ++++++++++++ benchmark/url/new-url-parse.js | 57 --------- 4 files changed, 249 insertions(+), 57 deletions(-) create mode 100644 benchmark/url/legacy-vs-whatwg-url-get-prop.js create mode 100644 benchmark/url/legacy-vs-whatwg-url-parse.js create mode 100644 benchmark/url/legacy-vs-whatwg-url-serialize.js delete mode 100644 benchmark/url/new-url-parse.js diff --git a/benchmark/url/legacy-vs-whatwg-url-get-prop.js b/benchmark/url/legacy-vs-whatwg-url-get-prop.js new file mode 100644 index 00000000000000..f703b75b16f6f7 --- /dev/null +++ b/benchmark/url/legacy-vs-whatwg-url-get-prop.js @@ -0,0 +1,109 @@ +'use strict'; +const common = require('../common.js'); +const url = require('url'); +const URL = url.URL; +const assert = require('assert'); + +const inputs = { + long: 'http://nodejs.org:89/docs/latest/api/url.html#test?' + + 'payload1=true&payload2=false&test=1&benchmark=3&' + + 'foo=38.38.011.293&bar=1234834910480&test=19299&3992&' + + 'key=f5c65e1e98fe07e648249ad41e1cfdb0', + short: 'https://nodejs.org/en/blog/', + idn: 'http://你好你好', + auth: 'https://user:pass@example.com/path?search=1', + special: 'file:///foo/bar/test/node.js', + percent: 'https://%E4%BD%A0/foo', + dot: 'https://example.org/./a/../b/./c' +}; + +const bench = common.createBenchmark(main, { + type: Object.keys(inputs), + method: ['legacy', 'whatwg'], + n: [1e5] +}); + +// At the time of writing, when using a passed property name to index +// the object, Crankshaft would generate a LoadKeyedGeneric even when it +// remains a constant in the function, so here we must use the literal +// instead to get a LoadNamedField. +function useLegacy(n, input) { + var obj = url.parse(input); + var noDead = { + protocol: obj.protocol, + auth: obj.auth, + host: obj.host, + hostname: obj.hostname, + port: obj.port, + pathname: obj.pathname, + search: obj.search, + hash: obj.hash + }; + // It's necessary to assign the values to an object + // to avoid loop invariant code motion. + bench.start(); + for (var i = 0; i < n; i += 1) { + noDead.protocol = obj.protocol; + noDead.auth = obj.auth; + noDead.host = obj.host; + noDead.hostname = obj.hostname; + noDead.port = obj.port; + noDead.pathname = obj.pathname; + noDead.search = obj.search; + noDead.hash = obj.hash; + } + bench.end(n); + return noDead; +} + +function useWHATWG(n, input) { + var obj = new URL(input); + var noDead = { + protocol: obj.protocol, + auth: obj.username + ':' + obj.password, + host: obj.host, + hostname: obj.hostname, + port: obj.port, + pathname: obj.pathname, + search: obj.search, + hash: obj.hash + }; + bench.start(); + for (var i = 0; i < n; i += 1) { + noDead.protocol = obj.protocol; + noDead.auth = obj.username + ':' + obj.password; + noDead.host = obj.host; + noDead.hostname = obj.hostname; + noDead.port = obj.port; + noDead.pathname = obj.pathname; + noDead.search = obj.search; + noDead.hash = obj.hash; + } + bench.end(n); + return noDead; +} + +function main(conf) { + const type = conf.type; + const n = conf.n | 0; + const method = conf.method; + + const input = inputs[type]; + if (!input) { + throw new Error('Unknown input type'); + } + + var noDead; // Avoid dead code elimination. + switch (method) { + case 'legacy': + noDead = useLegacy(n, input); + break; + case 'whatwg': + noDead = useWHATWG(n, input); + break; + default: + throw new Error('Unknown method'); + } + + assert.ok(noDead); +} diff --git a/benchmark/url/legacy-vs-whatwg-url-parse.js b/benchmark/url/legacy-vs-whatwg-url-parse.js new file mode 100644 index 00000000000000..ca7a48466c7dc3 --- /dev/null +++ b/benchmark/url/legacy-vs-whatwg-url-parse.js @@ -0,0 +1,69 @@ +'use strict'; +const common = require('../common.js'); +const url = require('url'); +const URL = url.URL; +const assert = require('assert'); + +const inputs = { + long: 'http://nodejs.org:89/docs/latest/api/url.html#test?' + + 'payload1=true&payload2=false&test=1&benchmark=3&' + + 'foo=38.38.011.293&bar=1234834910480&test=19299&3992&' + + 'key=f5c65e1e98fe07e648249ad41e1cfdb0', + short: 'https://nodejs.org/en/blog/', + idn: 'http://你好你好', + auth: 'https://user:pass@example.com/path?search=1', + special: 'file:///foo/bar/test/node.js', + percent: 'https://%E4%BD%A0/foo', + dot: 'https://example.org/./a/../b/./c' +}; + +const bench = common.createBenchmark(main, { + type: Object.keys(inputs), + method: ['legacy', 'whatwg'], + n: [1e5] +}); + +function useLegacy(n, input) { + var noDead = url.parse(input); + bench.start(); + for (var i = 0; i < n; i += 1) { + noDead = url.parse(input); + } + bench.end(n); + return noDead; +} + +function useWHATWG(n, input) { + var noDead = url.parse(input); + bench.start(); + for (var i = 0; i < n; i += 1) { + noDead = new URL(input); + } + bench.end(n); + return noDead; +} + +function main(conf) { + const type = conf.type; + const n = conf.n | 0; + const method = conf.method; + + const input = inputs[type]; + if (!input) { + throw new Error('Unknown input type'); + } + + var noDead; // Avoid dead code elimination. + switch (method) { + case 'legacy': + noDead = useLegacy(n, input); + break; + case 'whatwg': + noDead = useWHATWG(n, input); + break; + default: + throw new Error('Unknown method'); + } + + assert.ok(noDead); +} diff --git a/benchmark/url/legacy-vs-whatwg-url-serialize.js b/benchmark/url/legacy-vs-whatwg-url-serialize.js new file mode 100644 index 00000000000000..c0b7f5a6ce1565 --- /dev/null +++ b/benchmark/url/legacy-vs-whatwg-url-serialize.js @@ -0,0 +1,71 @@ +'use strict'; +const common = require('../common.js'); +const url = require('url'); +const URL = url.URL; +const assert = require('assert'); + +const inputs = { + long: 'http://nodejs.org:89/docs/latest/api/url.html#test?' + + 'payload1=true&payload2=false&test=1&benchmark=3&' + + 'foo=38.38.011.293&bar=1234834910480&test=19299&3992&' + + 'key=f5c65e1e98fe07e648249ad41e1cfdb0', + short: 'https://nodejs.org/en/blog/', + idn: 'http://你好你好', + auth: 'https://user:pass@example.com/path?search=1', + special: 'file:///foo/bar/test/node.js', + percent: 'https://%E4%BD%A0/foo', + dot: 'https://example.org/./a/../b/./c' +}; + +const bench = common.createBenchmark(main, { + type: Object.keys(inputs), + method: ['legacy', 'whatwg'], + n: [1e5] +}); + +function useLegacy(n, input, prop) { + var obj = url.parse(input); + var noDead = url.format(obj); + bench.start(); + for (var i = 0; i < n; i += 1) { + noDead = url.format(obj); + } + bench.end(n); + return noDead; +} + +function useWHATWG(n, input, prop) { + var obj = new URL(input); + var noDead = obj.toString(); + bench.start(); + for (var i = 0; i < n; i += 1) { + noDead = obj.toString(); + } + bench.end(n); + return noDead; +} + +function main(conf) { + const type = conf.type; + const n = conf.n | 0; + const method = conf.method; + + const input = inputs[type]; + if (!input) { + throw new Error('Unknown input type'); + } + + var noDead; // Avoid dead code elimination. + switch (method) { + case 'legacy': + noDead = useLegacy(n, input); + break; + case 'whatwg': + noDead = useWHATWG(n, input); + break; + default: + throw new Error('Unknown method'); + } + + assert.ok(noDead); +} diff --git a/benchmark/url/new-url-parse.js b/benchmark/url/new-url-parse.js deleted file mode 100644 index ef60e81847682b..00000000000000 --- a/benchmark/url/new-url-parse.js +++ /dev/null @@ -1,57 +0,0 @@ -'use strict'; -const common = require('../common.js'); -const url = require('url'); -const v8 = require('v8'); - -const bench = common.createBenchmark(main, { - type: 'one two three four five'.split(' '), - method: ['old', 'new'], - n: [25e4] -}); - -function useOld(n, input) { - // Force-optimize url.parse() so that the benchmark doesn't get - // disrupted by the optimizer kicking in halfway through. - url.parse(input); - v8.setFlagsFromString('--allow_natives_syntax'); - eval('%OptimizeFunctionOnNextCall(url.parse)'); - - bench.start(); - for (var i = 0; i < n; i += 1) - url.parse(input); - bench.end(n); -} - -function useNew(n, input) { - bench.start(); - for (var i = 0; i < n; i += 1) - new url.URL(input); - bench.end(n); -} - -function main(conf) { - const type = conf.type; - const n = conf.n | 0; - const method = conf.method; - - var inputs = { - one: 'http://nodejs.org/docs/latest/api/url.html#url_url_format_urlobj', - two: 'http://blog.nodejs.org/', - three: 'https://encrypted.google.com/search?q=url&q=site:npmjs.org&hl=en', - four: 'javascript:alert("node is awesome");', - //five: 'some.ran/dom/url.thing?oh=yes#whoo', - five: 'https://user:pass@example.com/', - }; - var input = inputs[type] || ''; - - switch (method) { - case 'old': - useOld(n, input); - break; - case 'new': - useNew(n, input); - break; - default: - throw new Error('Unknown method'); - } -} From 9f6d1f6fc2d099c0fb2a72f1bb2cefd8943bde19 Mon Sep 17 00:00:00 2001 From: Joyee Cheung Date: Sun, 25 Dec 2016 03:32:26 +0800 Subject: [PATCH 111/291] util: improve readability of normalizeEncoding * Improve readability of util.normalizeEncoding and add some comments * Add a benchmark for util.normalizeEncoding PR-URL: https://github.com/nodejs/node/pull/10439 Reviewed-By: James M Snell Reviewed-By: Andreas Madsen --- benchmark/util/normalize-encoding.js | 65 ++++++++++++++++++++++++++++ lib/internal/util.js | 14 ++++-- 2 files changed, 75 insertions(+), 4 deletions(-) create mode 100644 benchmark/util/normalize-encoding.js diff --git a/benchmark/util/normalize-encoding.js b/benchmark/util/normalize-encoding.js new file mode 100644 index 00000000000000..8c4d03478104b0 --- /dev/null +++ b/benchmark/util/normalize-encoding.js @@ -0,0 +1,65 @@ +'use strict'; + +const common = require('../common.js'); +const assert = require('assert'); + +const groupedInputs = { + group_common: ['undefined', 'utf8', 'utf-8', 'base64', 'binary', 'latin1'], + group_upper: ['UTF-8', 'UTF8', 'UCS2', 'UTF-16LE', 'UTF16LE', 'BASE64'], + group_uncommon: [ 'foo', '1', 'false', 'undefined', '[]'], + group_misc: ['', 'utf16le', 'usc2', 'hex', 'HEX', 'BINARY'] +}; + +const inputs = [ + '', 'utf8', 'utf-8', 'UTF-8', + 'UTF8', 'Utf8', 'uTf-8', 'utF-8', 'ucs2', + 'UCS2', 'utf16le', 'utf-16le', 'UTF-16LE', 'UTF16LE', + 'binary', 'BINARY', 'latin1', 'base64', 'BASE64', + 'hex', 'HEX', 'foo', '1', 'false', 'undefined', '[]']; + +const bench = common.createBenchmark(main, { + input: inputs.concat(Object.keys(groupedInputs)), + n: [1e5] +}, { + flags: '--expose-internals' +}); + +function getInput(input) { + switch (input) { + case 'group_common': + return groupedInputs.group_common; + case 'group_upper': + return groupedInputs.group_upper; + case 'group_uncommon': + return groupedInputs.group_uncommon; + case 'group_misc': + return groupedInputs.group_misc; + case '1': + return [1]; + case 'false': + return [false]; + case 'undefined': + return [undefined]; + case '[]': + return [[]]; + default: + return [input]; + } +} + +function main(conf) { + const normalizeEncoding = require('internal/util').normalizeEncoding; + + const n = conf.n | 0; + const inputs = getInput(conf.input); + var noDead = ''; + + bench.start(); + for (var i = 0; i < n; i += 1) { + for (var j = 0; j < inputs.length; ++j) { + noDead = normalizeEncoding(inputs[j]); + } + } + bench.end(n); + assert.ok(noDead === undefined || noDead.length > 0); +} diff --git a/lib/internal/util.js b/lib/internal/util.js index 0c7f391eb1fad1..b7facfbbbfda68 100644 --- a/lib/internal/util.js +++ b/lib/internal/util.js @@ -103,10 +103,16 @@ exports.assertCrypto = function(exports) { }; exports.kIsEncodingSymbol = Symbol('node.isEncoding'); + +// The loop should only run at most twice, retrying with lowercased enc +// if there is no match in the first pass. +// We use a loop instead of branching to retry with a helper +// function in order to avoid the performance hit. +// Return undefined if there is no match. exports.normalizeEncoding = function normalizeEncoding(enc) { if (!enc) return 'utf8'; - var low; - for (;;) { + var retried; + while (true) { switch (enc) { case 'utf8': case 'utf-8': @@ -124,9 +130,9 @@ exports.normalizeEncoding = function normalizeEncoding(enc) { case 'hex': return enc; default: - if (low) return; // undefined + if (retried) return; // undefined enc = ('' + enc).toLowerCase(); - low = true; + retried = true; } } }; From fc2db50021870d933036b0e652c885bcb23bfedb Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Thu, 12 Jan 2017 12:52:20 -0800 Subject: [PATCH 112/291] test,repl: add coverage for repl .clear+useGlobal Add a test to cover situation where REPL is initialized with `useGlobal` set to `true` and `.clear` is called. This adds coverage for code in repl.js that is not currently covered. Includes minor refactor of rocket functions in repl.js for concision. PR-URL: https://github.com/nodejs/node/pull/10777 Reviewed-By: James M Snell --- lib/repl.js | 11 +++++------ test/parallel/test-repl-underscore.js | 27 +++++++++++++++++++++++++-- 2 files changed, 30 insertions(+), 8 deletions(-) diff --git a/lib/repl.js b/lib/repl.js index b3258e75e56733..5667bd350a949e 100644 --- a/lib/repl.js +++ b/lib/repl.js @@ -721,9 +721,7 @@ REPLServer.prototype.createContext = function() { Object.defineProperty(context, '_', { configurable: true, - get: () => { - return this.last; - }, + get: () => this.last, set: (value) => { this.last = value; if (!this.underscoreAssigned) { @@ -1265,9 +1263,10 @@ function defineDefaultCommands(repl) { help: 'Print this help message', action: function() { const names = Object.keys(this.commands).sort(); - const longestNameLength = names.reduce((max, name) => { - return Math.max(max, name.length); - }, 0); + const longestNameLength = names.reduce( + (max, name) => Math.max(max, name.length), + 0 + ); names.forEach((name) => { const cmd = this.commands[name]; const spaces = ' '.repeat(longestNameLength - name.length + 3); diff --git a/test/parallel/test-repl-underscore.js b/test/parallel/test-repl-underscore.js index 97fc508ad9eee4..91f32223e180b9 100644 --- a/test/parallel/test-repl-underscore.js +++ b/test/parallel/test-repl-underscore.js @@ -8,6 +8,7 @@ const stream = require('stream'); testSloppyMode(); testStrictMode(); testResetContext(); +testResetContextGlobal(); testMagicMode(); function testSloppyMode() { @@ -131,7 +132,28 @@ function testResetContext() { ]); } -function initRepl(mode) { +function testResetContextGlobal() { + const r = initRepl(repl.REPL_MODE_STRICT, true); + + r.write(`_ = 10; // explicitly set to 10 + _; // 10 from user input + .clear // No output because useGlobal is true + _; // remains 10 + `); + + assertOutput(r.output, [ + 'Expression assignment to _ now disabled.', + '10', + '10', + '10', + ]); + + // delete globals leaked by REPL when `useGlobal` is `true` + delete global.module; + delete global.require; +} + +function initRepl(mode, useGlobal) { const inputStream = new stream.PassThrough(); const outputStream = new stream.PassThrough(); outputStream.accum = ''; @@ -146,7 +168,8 @@ function initRepl(mode) { useColors: false, terminal: false, prompt: '', - replMode: mode + replMode: mode, + useGlobal: useGlobal }); } From 2f339e7200b560595fe26171f7c9705bcec62b9b Mon Sep 17 00:00:00 2001 From: Yuya Tanaka Date: Sun, 1 Jan 2017 00:09:59 +0900 Subject: [PATCH 113/291] benchmark: cleanup child_process IPC benchmark Squashed from: - child_process: fix IPC bench to obey send() ret val - child_process: fix IPC benchmark message has two more bytes - child_process: use setImmediate for IPC bench PR-URL: https://github.com/nodejs/node/pull/10557 Reviewed-By: Ben Noordhuis Reviewed-By: Anna Henningsen --- .../child_process/child-process-read-ipc.js | 21 ++++++++++++------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/benchmark/child_process/child-process-read-ipc.js b/benchmark/child_process/child-process-read-ipc.js index 28f2b6f9272772..30dead18032f98 100644 --- a/benchmark/child_process/child-process-read-ipc.js +++ b/benchmark/child_process/child-process-read-ipc.js @@ -1,14 +1,20 @@ 'use strict'; if (process.argv[2] === 'child') { const len = +process.argv[3]; - const msg = `"${'.'.repeat(len)}"`; - while (true) { - process.send(msg); - } + const msg = '.'.repeat(len); + const send = () => { + while (process.send(msg)); + // Wait: backlog of unsent messages exceeds threshold + setImmediate(send); + }; + send(); } else { const common = require('../common.js'); const bench = common.createBenchmark(main, { - len: [64, 256, 1024, 4096, 32768], + len: [ + 64, 256, 1024, 4096, 16384, 65536, + 65536 << 4, 65536 << 8 + ], dur: [5] }); const spawn = require('child_process').spawn; @@ -18,7 +24,7 @@ if (process.argv[2] === 'child') { const dur = +conf.dur; const len = +conf.len; - const options = { 'stdio': ['ignore', 'ignore', 'ignore', 'ipc'] }; + const options = { 'stdio': ['ignore', 1, 2, 'ipc'] }; const child = spawn(process.argv[0], [process.argv[1], 'child', len], options); @@ -29,8 +35,7 @@ if (process.argv[2] === 'child') { setTimeout(function() { child.kill(); - const gbits = (bytes * 8) / (1024 * 1024 * 1024); - bench.end(gbits); + bench.end(bytes); }, dur * 1000); } } From ddcd1a202faa486223e6f3391102e1502bae783d Mon Sep 17 00:00:00 2001 From: Yuya Tanaka Date: Sun, 1 Jan 2017 01:09:52 +0900 Subject: [PATCH 114/291] child_process: optimize IPC for large data Squashed from: - child_process: stop indexOf() on whole IPC buffer - child_process: get rid of forEach() and slice() in IPC - child_process: get rid of another forEach() in IPC Fixes: https://github.com/nodejs/node/issues/3145 PR-URL: https://github.com/nodejs/node/pull/10557 Reviewed-By: Ben Noordhuis Reviewed-By: Anna Henningsen --- lib/internal/child_process.js | 29 +++++++++++++++++------------ 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/lib/internal/child_process.js b/lib/internal/child_process.js index 5bdc53fd192073..3017cd5889a037 100644 --- a/lib/internal/child_process.js +++ b/lib/internal/child_process.js @@ -446,14 +446,20 @@ function setupChannel(target, channel) { channel.onread = function(nread, pool, recvHandle) { // TODO(bnoordhuis) Check that nread > 0. if (pool) { - jsonBuffer += decoder.write(pool); - - var i, start = 0; + // Linebreak is used as a message end sign + var chunks = decoder.write(pool).split('\n'); + var numCompleteChunks = chunks.length - 1; + // Last line does not have trailing linebreak + var incompleteChunk = chunks[numCompleteChunks]; + if (numCompleteChunks === 0) { + jsonBuffer += incompleteChunk; + this.buffering = jsonBuffer.length !== 0; + return; + } + chunks[0] = jsonBuffer + chunks[0]; - //Linebreak is used as a message end sign - while ((i = jsonBuffer.indexOf('\n', start)) >= 0) { - var json = jsonBuffer.slice(start, i); - var message = JSON.parse(json); + for (var i = 0; i < numCompleteChunks; i++) { + var message = JSON.parse(chunks[i]); // There will be at most one NODE_HANDLE message in every chunk we // read because SCM_RIGHTS messages don't get coalesced. Make sure @@ -462,10 +468,8 @@ function setupChannel(target, channel) { handleMessage(target, message, recvHandle); else handleMessage(target, message, undefined); - - start = i + 1; } - jsonBuffer = jsonBuffer.slice(start); + jsonBuffer = incompleteChunk; this.buffering = jsonBuffer.length !== 0; } else { @@ -494,9 +498,10 @@ function setupChannel(target, channel) { var queue = target._handleQueue; target._handleQueue = null; - queue.forEach(function(args) { + for (var i = 0; i < queue.length; i++) { + var args = queue[i]; target._send(args.message, args.handle, args.options, args.callback); - }); + } // Process a pending disconnect (if any). if (!target.connected && target.channel && !target._handleQueue) From 31d3a22989854e5313874be697f191084c20258e Mon Sep 17 00:00:00 2001 From: Daijiro Wachi Date: Mon, 9 Jan 2017 16:40:04 +0100 Subject: [PATCH 115/291] test: skip test-icu-transcode if Intl is not present use common.hasIntl to make sure Intl object is present or not. PR-URL: https://github.com/nodejs/node/pull/10707 Reviewed-By: James M Snell Reviewed-By: Italo A. Casas Reviewed-By: Steven R Loomis --- test/parallel/test-icu-transcode.js | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/test/parallel/test-icu-transcode.js b/test/parallel/test-icu-transcode.js index c099e754ca55d6..87f32a745a35cb 100644 --- a/test/parallel/test-icu-transcode.js +++ b/test/parallel/test-icu-transcode.js @@ -1,9 +1,14 @@ 'use strict'; -require('../common'); +const common = require('../common'); const buffer = require('buffer'); const assert = require('assert'); +if (!common.hasIntl) { + common.skip('icu punycode tests because ICU is not present.'); + return; +} + const orig = Buffer.from('tést €', 'utf8'); // Test Transcoding From 36db5a663ac6e6daaffcd14580d61b5701ff1814 Mon Sep 17 00:00:00 2001 From: abouthiroppy Date: Sun, 15 Jan 2017 05:50:42 +0900 Subject: [PATCH 116/291] test: add http_incoming's matchKnownFields test https://github.com/nodejs/node/blob/master/lib/_http_incoming.js#L136 Coverage: https://coverage.nodejs.org/coverage-57f6a106fbc69a47/root/_http_incoming.js.html PR-URL: https://github.com/nodejs/node/pull/10811 Reviewed-By: James M Snell Reviewed-By: Santiago Gimeno Reviewed-By: Italo A. Casas --- .../test-http-incoming-matchKnownFields.js | 90 +++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 test/parallel/test-http-incoming-matchKnownFields.js diff --git a/test/parallel/test-http-incoming-matchKnownFields.js b/test/parallel/test-http-incoming-matchKnownFields.js new file mode 100644 index 00000000000000..7411be4e847d73 --- /dev/null +++ b/test/parallel/test-http-incoming-matchKnownFields.js @@ -0,0 +1,90 @@ +'use strict'; +require('../common'); +const assert = require('assert'); +const IncomingMessage = require('http').IncomingMessage; + +function checkDest(field, result, value) { + const dest = {}; + + if (value) dest[field] = 'test'; + const incomingMessage = new IncomingMessage(field); + // dest is changed by IncomingMessage._addHeaderLine + incomingMessage._addHeaderLine(field, value, dest); + assert.deepStrictEqual(dest, result); +} + +checkDest('', {'': undefined}); +checkDest('Content-Type', {'content-type': undefined}); +checkDest('content-type', {'content-type': 'test'}, 'value'); +checkDest('User-Agent', {'user-agent': undefined}); +checkDest('user-agent', {'user-agent': 'test'}, 'value'); +checkDest('Referer', {referer: undefined}); +checkDest('referer', {referer: 'test'}, 'value'); +checkDest('Host', {host: undefined}); +checkDest('host', {host: 'test'}, 'value'); +checkDest('Authorization', {authorization: undefined}, undefined); +checkDest('authorization', {authorization: 'test'}, 'value'); +checkDest('Proxy-Authorization', {'proxy-authorization': undefined}); +checkDest('proxy-authorization', {'proxy-authorization': 'test'}, 'value'); +checkDest('If-Modified-Since', {'if-modified-since': undefined}); +checkDest('if-modified-since', {'if-modified-since': 'test'}, 'value'); +checkDest('If-Unmodified-Since', {'if-unmodified-since': undefined}); +checkDest('if-unmodified-since', {'if-unmodified-since': 'test'}, 'value'); +checkDest('Form', {form: undefined}); +checkDest('form', {form: 'test, value'}, 'value'); +checkDest('Location', {location: undefined}); +checkDest('location', {location: 'test'}, 'value'); +checkDest('Max-Forwards', {'max-forwards': undefined}); +checkDest('max-forwards', {'max-forwards': 'test'}, 'value'); +checkDest('Retry-After', {'retry-after': undefined}); +checkDest('retry-after', {'retry-after': 'test'}, 'value'); +checkDest('Etag', {etag: undefined}); +checkDest('etag', {etag: 'test'}, 'value'); +checkDest('Last-Modified', {'last-modified': undefined}); +checkDest('last-modified', {'last-modified': 'test'}, 'value'); +checkDest('Server', {server: undefined}); +checkDest('server', {server: 'test'}, 'value'); +checkDest('Age', {age: undefined}); +checkDest('age', {age: 'test'}, 'value'); +checkDest('Expires', {expires: undefined}); +checkDest('expires', {expires: 'test'}, 'value'); +checkDest('Set-Cookie', {'set-cookie': [undefined]}); +checkDest('set-cookie', {'set-cookie': [undefined]}); +checkDest('Transfer-Encoding', {'transfer-encoding': undefined}); +checkDest('transfer-encoding', {'transfer-encoding': 'test, value'}, 'value'); +checkDest('Date', {date: undefined}); +checkDest('date', {date: 'test, value'}, 'value'); +checkDest('Connection', {connection: undefined}); +checkDest('connection', {connection: 'test, value'}, 'value'); +checkDest('Cache-Control', {'cache-control': undefined}); +checkDest('cache-control', {'cache-control': 'test, value'}, 'value'); +checkDest('Transfer-Encoding', {'transfer-encoding': undefined}); +checkDest('transfer-encoding', {'transfer-encoding': 'test, value'}, 'value'); +checkDest('Vary', {vary: undefined}); +checkDest('vary', {vary: 'test, value'}, 'value'); +checkDest('Content-Encoding', {'content-encoding': undefined}, undefined); +checkDest('content-encoding', {'content-encoding': 'test, value'}, 'value'); +checkDest('Cookies', {cookies: undefined}); +checkDest('cookies', {cookies: 'test, value'}, 'value'); +checkDest('Origin', {origin: undefined}); +checkDest('origin', {origin: 'test, value'}, 'value'); +checkDest('Upgrade', {upgrade: undefined}); +checkDest('upgrade', {upgrade: 'test, value'}, 'value'); +checkDest('Expect', {expect: undefined}); +checkDest('expect', {expect: 'test, value'}, 'value'); +checkDest('If-Match', {'if-match': undefined}); +checkDest('if-match', {'if-match': 'test, value'}, 'value'); +checkDest('If-None-Match', {'if-none-match': undefined}); +checkDest('if-none-match', {'if-none-match': 'test, value'}, 'value'); +checkDest('Accept', {accept: undefined}); +checkDest('accept', {accept: 'test, value'}, 'value'); +checkDest('Accept-Encoding', {'accept-encoding': undefined}); +checkDest('accept-encoding', {'accept-encoding': 'test, value'}, 'value'); +checkDest('Accept-Language', {'accept-language': undefined}); +checkDest('accept-language', {'accept-language': 'test, value'}, 'value'); +checkDest('X-Forwarded-For', {'x-forwarded-for': undefined}); +checkDest('x-forwarded-for', {'x-forwarded-for': 'test, value'}, 'value'); +checkDest('X-Forwarded-Host', {'x-forwarded-host': undefined}); +checkDest('x-forwarded-host', {'x-forwarded-host': 'test, value'}, 'value'); +checkDest('X-Forwarded-Proto', {'x-forwarded-proto': undefined}); +checkDest('x-forwarded-proto', {'x-forwarded-proto': 'test, value'}, 'value'); From 77cbc26a9635e743d1976066f3f3b444e669b077 Mon Sep 17 00:00:00 2001 From: larissayvette Date: Fri, 13 Jan 2017 18:45:25 +0100 Subject: [PATCH 117/291] test: delete duplicate test of noAssert in readUInt* PR-URL: https://github.com/nodejs/node/pull/10791 Reviewed-By: Rich Trott Reviewed-By: James M Snell Reviewed-By: Sakthipriyan Vairamani --- test/parallel/test-buffer-readuintbe.js | 24 ------------------------ test/parallel/test-buffer-readuintle.js | 24 ------------------------ 2 files changed, 48 deletions(-) delete mode 100644 test/parallel/test-buffer-readuintbe.js delete mode 100644 test/parallel/test-buffer-readuintle.js diff --git a/test/parallel/test-buffer-readuintbe.js b/test/parallel/test-buffer-readuintbe.js deleted file mode 100644 index 162e9fea27a14f..00000000000000 --- a/test/parallel/test-buffer-readuintbe.js +++ /dev/null @@ -1,24 +0,0 @@ -'use strict'; -require('../common'); -const assert = require('assert'); - -// testing basic functionality of readUIntBE() - -const buf = Buffer.from([42, 84, 168, 127]); -const result = buf.readUIntBE(2); - -assert.strictEqual(result, 84); - -assert.throws( - () => { - buf.readUIntBE(5); - }, - /Index out of range/ -); - -assert.doesNotThrow( - () => { - buf.readUIntBE(5, 0, true); - }, - 'readUIntBE() should not throw if noAssert is true' -); diff --git a/test/parallel/test-buffer-readuintle.js b/test/parallel/test-buffer-readuintle.js deleted file mode 100644 index 982adb8607eaa1..00000000000000 --- a/test/parallel/test-buffer-readuintle.js +++ /dev/null @@ -1,24 +0,0 @@ -'use strict'; -require('../common'); -const assert = require('assert'); - -// testing basic functionality of readUIntLE() - -const buf = Buffer.from([42, 84, 168, 127]); -const result = buf.readUIntLE(2); - -assert.strictEqual(result, 168); - -assert.throws( - () => { - buf.readUIntLE(5); - }, - /Index out of range/ -); - -assert.doesNotThrow( - () => { - buf.readUIntLE(5, 0, true); - }, - 'readUIntLE() should not throw if noAssert is true' -); From 84bf04b0c1bf4c8eb38e507c2253d4e6697e1381 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Thu, 12 Jan 2017 22:45:23 -0800 Subject: [PATCH 118/291] test,util: remove lint workarounds Remove assignments to `SIMD` that are only to pacify ESLint. Instead, use either `global.SIMD` or provide an comment letting ESLint know in cases where `SIMD` is guaranteed to be a defined global identifier. PR-URL: https://github.com/nodejs/node/pull/10785 Reviewed-By: Luigi Pinca Reviewed-By: Teddy Katz Reviewed-By: James M Snell Reviewed-By: Michael Dawson --- lib/util.js | 9 +++------ test/parallel/test-util-inspect-simd.js | 3 +-- 2 files changed, 4 insertions(+), 8 deletions(-) diff --git a/lib/util.js b/lib/util.js index 85af547ebb81f7..4069fc3b4872de 100644 --- a/lib/util.js +++ b/lib/util.js @@ -27,16 +27,13 @@ var simdFormatters; if (typeof global.SIMD === 'object' && global.SIMD !== null) { simdFormatters = new Map(); - const make = (extractLane, count) => { - return (ctx, value, recurseTimes, visibleKeys, keys) => { + const make = + (extractLane, count) => (ctx, value, recurseTimes, visibleKeys, keys) => { const output = new Array(count); for (var i = 0; i < count; i += 1) output[i] = formatPrimitive(ctx, extractLane(value, i)); return output; }; - }; - - const SIMD = global.SIMD; // Pacify eslint. const countPerType = { Bool16x8: 8, @@ -52,7 +49,7 @@ if (typeof global.SIMD === 'object' && global.SIMD !== null) { }; for (const key in countPerType) { - const type = SIMD[key]; + const type = global.SIMD[key]; simdFormatters.set(type, make(type.extractLane, countPerType[key])); } } diff --git a/test/parallel/test-util-inspect-simd.js b/test/parallel/test-util-inspect-simd.js index ec4ccc1875a817..5e0a2740840c93 100644 --- a/test/parallel/test-util-inspect-simd.js +++ b/test/parallel/test-util-inspect-simd.js @@ -1,12 +1,11 @@ // Flags: --harmony_simd +/* global SIMD */ 'use strict'; require('../common'); const assert = require('assert'); const inspect = require('util').inspect; -const SIMD = global.SIMD; // Pacify eslint. - assert.strictEqual( inspect(SIMD.Bool16x8()), 'Bool16x8 [ false, false, false, false, false, false, false, false ]'); From d818cfaaadb7b8c3e5bfef73f1e093d1e97d707d Mon Sep 17 00:00:00 2001 From: Adrian Estrada Date: Thu, 12 Jan 2017 19:27:01 -0500 Subject: [PATCH 119/291] test: improve test-fs-write-stream-throw-type * validate the errors for all assert.throws * use arrow functions PR-URL: https://github.com/nodejs/node/pull/10779 Reviewed-By: James M Snell Reviewed-By: Colin Ihrig Reviewed-By: Michael Dawson --- .../test-fs-write-stream-throw-type-error.js | 36 ++++++++++++------- 1 file changed, 24 insertions(+), 12 deletions(-) diff --git a/test/parallel/test-fs-write-stream-throw-type-error.js b/test/parallel/test-fs-write-stream-throw-type-error.js index 996b22119cda5e..940def65b30b01 100644 --- a/test/parallel/test-fs-write-stream-throw-type-error.js +++ b/test/parallel/test-fs-write-stream-throw-type-error.js @@ -4,32 +4,44 @@ const assert = require('assert'); const fs = require('fs'); const path = require('path'); +const numberError = new RegExp('^TypeError: "options" must be a string ' + + 'or an object, got number instead.$'); + +const booleanError = new RegExp('^TypeError: "options" must be a string ' + + 'or an object, got boolean instead.$'); + const example = path.join(common.tmpDir, 'dummy'); common.refreshTmpDir(); -assert.doesNotThrow(function() { +assert.doesNotThrow(() => { fs.createWriteStream(example, undefined); }); -assert.doesNotThrow(function() { + +assert.doesNotThrow(() => { fs.createWriteStream(example, null); }); -assert.doesNotThrow(function() { + +assert.doesNotThrow(() => { fs.createWriteStream(example, 'utf8'); }); -assert.doesNotThrow(function() { + +assert.doesNotThrow(() => { fs.createWriteStream(example, {encoding: 'utf8'}); }); -assert.throws(function() { +assert.throws(() => { fs.createWriteStream(example, 123); -}, /"options" must be a string or an object/); -assert.throws(function() { +}, numberError); + +assert.throws(() => { fs.createWriteStream(example, 0); -}, /"options" must be a string or an object/); -assert.throws(function() { +}, numberError); + +assert.throws(() => { fs.createWriteStream(example, true); -}, /"options" must be a string or an object/); -assert.throws(function() { +}, booleanError); + +assert.throws(() => { fs.createWriteStream(example, false); -}, /"options" must be a string or an object/); +}, booleanError); From b5c0b43efaea8a99489e650d995f9754f278bd4c Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Thu, 12 Jan 2017 22:16:21 -0800 Subject: [PATCH 120/291] test: increase test-crypto.js strictness Confirm that `getCiphers()` contains no duplicates. PR-URL: https://github.com/nodejs/node/pull/10784 Reviewed-By: Sam Roberts Reviewed-By: Colin Ihrig --- test/parallel/test-crypto.js | 30 ++++++++++++++++++++---------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/test/parallel/test-crypto.js b/test/parallel/test-crypto.js index 13401e4ac594ab..eff9a5092eced6 100644 --- a/test/parallel/test-crypto.js +++ b/test/parallel/test-crypto.js @@ -53,23 +53,33 @@ assert.throws(function() { }, /^TypeError: Data must be a string or a buffer$/); -function assertSorted(list) { +function validateList(list) { + // The list must not be empty + assert(list.length > 0); + + // The list should be sorted. // Array#sort() modifies the list in place so make a copy. - const sorted = list.slice().sort(); + const sorted = [...list].sort(); assert.deepStrictEqual(list, sorted); + + // Each element should be unique. + assert.strictEqual([...new Set(list)].length, list.length); + + // Each element should be a string. + assert(list.every((value) => typeof value === 'string')); } // Assume that we have at least AES-128-CBC. -assert.notStrictEqual(0, crypto.getCiphers().length); +const cryptoCiphers = crypto.getCiphers(); assert(crypto.getCiphers().includes('aes-128-cbc')); -assert(!crypto.getCiphers().includes('AES-128-CBC')); -assertSorted(crypto.getCiphers()); +validateList(cryptoCiphers); // Assume that we have at least AES256-SHA. -assert.notStrictEqual(0, tls.getCiphers().length); +const tlsCiphers = tls.getCiphers(); assert(tls.getCiphers().includes('aes256-sha')); -assert(!tls.getCiphers().includes('AES256-SHA')); -assertSorted(tls.getCiphers()); +// There should be no capital letters in any element. +assert(tlsCiphers.every((value) => /^[^A-Z]+$/.test(value))); +validateList(tlsCiphers); // Assert that we have sha and sha1 but not SHA and SHA1. assert.notStrictEqual(0, crypto.getHashes().length); @@ -79,13 +89,13 @@ assert(!crypto.getHashes().includes('SHA1')); assert(!crypto.getHashes().includes('SHA')); assert(crypto.getHashes().includes('RSA-SHA1')); assert(!crypto.getHashes().includes('rsa-sha1')); -assertSorted(crypto.getHashes()); +validateList(crypto.getHashes()); // Assume that we have at least secp384r1. assert.notStrictEqual(0, crypto.getCurves().length); assert(crypto.getCurves().includes('secp384r1')); assert(!crypto.getCurves().includes('SECP384R1')); -assertSorted(crypto.getCurves()); +validateList(crypto.getCurves()); // Regression tests for #5725: hex input that's not a power of two should // throw, not assert in C++ land. From 7165f1d40920e31289457cf1bde24dc1bc019b40 Mon Sep 17 00:00:00 2001 From: Adrian Estrada Date: Wed, 11 Jan 2017 21:10:18 -0500 Subject: [PATCH 121/291] test: improve the code in test-process-cpuUsage * validate the errors for assert.throws * use arrow functions PR-URL: https://github.com/nodejs/node/pull/10714 Reviewed-By: Colin Ihrig Reviewed-By: James M Snell --- test/parallel/test-process-cpuUsage.js | 54 ++++++++++++++++++++------ 1 file changed, 42 insertions(+), 12 deletions(-) diff --git a/test/parallel/test-process-cpuUsage.js b/test/parallel/test-process-cpuUsage.js index 92dc71918585c3..0c553c576a1f25 100644 --- a/test/parallel/test-process-cpuUsage.js +++ b/test/parallel/test-process-cpuUsage.js @@ -33,27 +33,57 @@ for (let i = 0; i < 10; i++) { assert(diffUsage.system >= 0); } +const invalidUserArgument = + /^TypeError: value of user property of argument is invalid$/; +const invalidSystemArgument = + /^TypeError: value of system property of argument is invalid$/; + // Ensure that an invalid shape for the previous value argument throws an error. -assert.throws(function() { process.cpuUsage(1); }); -assert.throws(function() { process.cpuUsage({}); }); -assert.throws(function() { process.cpuUsage({ user: 'a' }); }); -assert.throws(function() { process.cpuUsage({ system: 'b' }); }); -assert.throws(function() { process.cpuUsage({ user: null, system: 'c' }); }); -assert.throws(function() { process.cpuUsage({ user: 'd', system: null }); }); -assert.throws(function() { process.cpuUsage({ user: -1, system: 2 }); }); -assert.throws(function() { process.cpuUsage({ user: 3, system: -2 }); }); -assert.throws(function() { +assert.throws(() => { + process.cpuUsage(1); +}, invalidUserArgument); + +assert.throws(() => { + process.cpuUsage({}); +}, invalidUserArgument); + +assert.throws(() => { + process.cpuUsage({ user: 'a' }); +}, invalidUserArgument); + +assert.throws(() => { + process.cpuUsage({ system: 'b' }); +}, invalidUserArgument); + +assert.throws(() => { + process.cpuUsage({ user: null, system: 'c' }); +}, invalidUserArgument); + +assert.throws(() => { + process.cpuUsage({ user: 'd', system: null }); +}, invalidUserArgument); + +assert.throws(() => { + process.cpuUsage({ user: -1, system: 2 }); +}, invalidUserArgument); + +assert.throws(() => { + process.cpuUsage({ user: 3, system: -2 }); +}, invalidSystemArgument); + +assert.throws(() => { process.cpuUsage({ user: Number.POSITIVE_INFINITY, system: 4 }); -}); -assert.throws(function() { +}, invalidUserArgument); + +assert.throws(() => { process.cpuUsage({ user: 5, system: Number.NEGATIVE_INFINITY }); -}); +}, invalidSystemArgument); // Ensure that the return value is the expected shape. function validateResult(result) { From 4e7a31b3a0f66965d2fc73b5c78197edb6a5c87e Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Fri, 13 Jan 2017 14:28:35 -0800 Subject: [PATCH 122/291] crypto,tls: fix mutability of return values MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit If you alter the array returned by `tls.getCiphers()`, `crypto.getCiphers()`, `crypto.getHashes()`, or `crypto.getCurves()`, it will alter subsequent return values from those functions. ```js 'use strict'; const crypto = require('crypto'); var hashes = crypto.getHashes(); hashes.splice(0, hashes.length); hashes.push('some-arbitrary-value'); console.log(crypto.getHashes()); // "['some-arbitrary-value']" ``` This is surprising. Change functions to return copy of array instead. PR-URL: https://github.com/nodejs/node/pull/10795 Reviewed-By: Anna Henningsen Reviewed-By: Сковорода Никита Андреевич Reviewed-By: Sakthipriyan Vairamani Reviewed-By: James M Snell Reviewed-By: Sam Roberts --- lib/internal/util.js | 2 +- lib/tls.js | 6 +++--- test/parallel/test-crypto.js | 14 ++++++++++++++ 3 files changed, 18 insertions(+), 4 deletions(-) diff --git a/lib/internal/util.js b/lib/internal/util.js index b7facfbbbfda68..5384d59fc58396 100644 --- a/lib/internal/util.js +++ b/lib/internal/util.js @@ -158,7 +158,7 @@ exports.cachedResult = function cachedResult(fn) { return () => { if (result === undefined) result = fn(); - return result; + return result.slice(); }; }; diff --git a/lib/tls.js b/lib/tls.js index 32c0319754be2a..56da56029fc94b 100644 --- a/lib/tls.js +++ b/lib/tls.js @@ -22,9 +22,9 @@ exports.DEFAULT_CIPHERS = exports.DEFAULT_ECDH_CURVE = 'prime256v1'; -exports.getCiphers = internalUtil.cachedResult(() => { - return internalUtil.filterDuplicateStrings(binding.getSSLCiphers(), true); -}); +exports.getCiphers = internalUtil.cachedResult( + () => internalUtil.filterDuplicateStrings(binding.getSSLCiphers(), true) +); // Convert protocols array into valid OpenSSL protocols list // ("\x06spdy/2\x08http/1.1\x08http/1.0") diff --git a/test/parallel/test-crypto.js b/test/parallel/test-crypto.js index eff9a5092eced6..2e94397c8f22f9 100644 --- a/test/parallel/test-crypto.js +++ b/test/parallel/test-crypto.js @@ -97,6 +97,20 @@ assert(crypto.getCurves().includes('secp384r1')); assert(!crypto.getCurves().includes('SECP384R1')); validateList(crypto.getCurves()); +// Modifying return value from get* functions should not mutate subsequent +// return values. +function testImmutability(fn) { + const list = fn(); + const copy = [...list]; + list.push('some-arbitrary-value'); + assert.deepStrictEqual(fn(), copy); +} + +testImmutability(crypto.getCiphers); +testImmutability(tls.getCiphers); +testImmutability(crypto.getHashes); +testImmutability(crypto.getCurves); + // Regression tests for #5725: hex input that's not a power of two should // throw, not assert in C++ land. assert.throws(function() { From a408ba64541714ef4c3fa153105f57bbf1f2efd1 Mon Sep 17 00:00:00 2001 From: Stewart X Addison Date: Fri, 30 Dec 2016 12:44:46 +0000 Subject: [PATCH 123/291] build: don't squash signal handlers with --shared An application using node built as a shared library may legitimately implement its own signal handling routines. Current behaviour is to squash all signal handlers on node startup. This change will stop that behaviour when node is built as a shared library. PR-URL: https://github.com/nodejs/node/pull/10539 Fixes: https://github.com/nodejs/node/issues/10520 Refs: https://github.com/nodejs/node/pull/615 Reviewed-By: Sam Roberts Reviewed-By: Gibson Fahnestock Reviewed-By: James M Snell Reviewed-By: Ben Noordhuis --- src/node.cc | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/node.cc b/src/node.cc index 0280eb696c1b84..75f3078db5b4f9 100644 --- a/src/node.cc +++ b/src/node.cc @@ -2198,7 +2198,7 @@ static void WaitForInspectorDisconnect(Environment* env) { if (env->inspector_agent()->IsConnected()) { // Restore signal dispositions, the app is done and is no longer // capable of handling signals. -#ifdef __POSIX__ +#if defined(__POSIX__) && !defined(NODE_SHARED_MODE) struct sigaction act; memset(&act, 0, sizeof(act)); for (unsigned nr = 1; nr < kMaxSignal; nr += 1) { @@ -4166,6 +4166,7 @@ inline void PlatformInit() { CHECK_EQ(err, 0); +#ifndef NODE_SHARED_MODE // Restore signal dispositions, the parent process may have changed them. struct sigaction act; memset(&act, 0, sizeof(act)); @@ -4179,6 +4180,7 @@ inline void PlatformInit() { act.sa_handler = (nr == SIGPIPE) ? SIG_IGN : SIG_DFL; CHECK_EQ(0, sigaction(nr, &act, nullptr)); } +#endif // !NODE_SHARED_MODE RegisterSignalHandler(SIGINT, SignalExit, true); RegisterSignalHandler(SIGTERM, SignalExit, true); From a3abba0b1a31926260e8ca5dc044c13c93ab5412 Mon Sep 17 00:00:00 2001 From: Jackson Tian Date: Mon, 16 Jan 2017 17:19:32 +0800 Subject: [PATCH 124/291] lib: remove unnecessary parameter for assertCrypto() The `exports` parameter is unnecessary. PR-URL: https://github.com/nodejs/node/pull/10834 Reviewed-By: Anna Henningsen Reviewed-By: Colin Ihrig Reviewed-By: Brian White Reviewed-By: James M Snell Reviewed-By: Sam Roberts --- lib/_tls_legacy.js | 2 +- lib/_tls_wrap.js | 2 +- lib/crypto.js | 2 +- lib/https.js | 2 +- lib/internal/util.js | 2 +- lib/tls.js | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/lib/_tls_legacy.js b/lib/_tls_legacy.js index f974b0cfc05575..e765b2507e7502 100644 --- a/lib/_tls_legacy.js +++ b/lib/_tls_legacy.js @@ -1,6 +1,6 @@ 'use strict'; -require('internal/util').assertCrypto(exports); +require('internal/util').assertCrypto(); const assert = require('assert'); const EventEmitter = require('events'); diff --git a/lib/_tls_wrap.js b/lib/_tls_wrap.js index 434384cec81595..721cdde142519c 100644 --- a/lib/_tls_wrap.js +++ b/lib/_tls_wrap.js @@ -1,6 +1,6 @@ 'use strict'; -require('internal/util').assertCrypto(exports); +require('internal/util').assertCrypto(); const assert = require('assert'); const crypto = require('crypto'); diff --git a/lib/crypto.js b/lib/crypto.js index c33728ac88c91f..9180ce70dce12e 100644 --- a/lib/crypto.js +++ b/lib/crypto.js @@ -4,7 +4,7 @@ 'use strict'; const internalUtil = require('internal/util'); -internalUtil.assertCrypto(exports); +internalUtil.assertCrypto(); exports.DEFAULT_ENCODING = 'buffer'; diff --git a/lib/https.js b/lib/https.js index 3b4e4294c23259..e05be20b4d6d5a 100644 --- a/lib/https.js +++ b/lib/https.js @@ -1,6 +1,6 @@ 'use strict'; -require('internal/util').assertCrypto(exports); +require('internal/util').assertCrypto(); const tls = require('tls'); const url = require('url'); diff --git a/lib/internal/util.js b/lib/internal/util.js index 5384d59fc58396..42a0922d304970 100644 --- a/lib/internal/util.js +++ b/lib/internal/util.js @@ -97,7 +97,7 @@ exports.objectToString = function objectToString(o) { }; const noCrypto = !process.versions.openssl; -exports.assertCrypto = function(exports) { +exports.assertCrypto = function() { if (noCrypto) throw new Error('Node.js is not compiled with openssl crypto support'); }; diff --git a/lib/tls.js b/lib/tls.js index 56da56029fc94b..bb4719d9b02c93 100644 --- a/lib/tls.js +++ b/lib/tls.js @@ -1,7 +1,7 @@ 'use strict'; const internalUtil = require('internal/util'); -internalUtil.assertCrypto(exports); +internalUtil.assertCrypto(); const net = require('net'); const url = require('url'); From 74f9cc9f0a9d152f522abdc0d4b8e3d7630e6fc3 Mon Sep 17 00:00:00 2001 From: Daniel Bevenius Date: Tue, 17 Jan 2017 07:51:25 +0100 Subject: [PATCH 125/291] build: move source files from headers section Currently, the sources list contains sources and headers which are separated by a comment. I noticed two .cc files after the headers comment and this commit moves those files the start of the list where the rest of source files are. PR-URL: https://github.com/nodejs/node/pull/10850 Reviewed-By: Colin Ihrig Reviewed-By: James M Snell Reviewed-By: Italo A. Casas --- node.gyp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/node.gyp b/node.gyp index 2b720a46791b73..3da08d5187f8e9 100644 --- a/node.gyp +++ b/node.gyp @@ -171,6 +171,7 @@ 'src/signal_wrap.cc', 'src/spawn_sync.cc', 'src/string_bytes.cc', + 'src/string_search.cc', 'src/stream_base.cc', 'src/stream_wrap.cc', 'src/tcp_wrap.cc', @@ -178,6 +179,7 @@ 'src/tty_wrap.cc', 'src/process_wrap.cc', 'src/udp_wrap.cc', + 'src/util.cc', 'src/uv.cc', # headers to make for a more pleasant IDE experience 'src/async-wrap.h', @@ -218,8 +220,6 @@ 'src/tree.h', 'src/util.h', 'src/util-inl.h', - 'src/util.cc', - 'src/string_search.cc', 'deps/http_parser/http_parser.h', 'deps/v8/include/v8.h', 'deps/v8/include/v8-debug.h', From 96babb20900236a030ded81e1739f0ec2e874760 Mon Sep 17 00:00:00 2001 From: Mark Date: Tue, 17 Jan 2017 12:58:37 +0200 Subject: [PATCH 126/291] test: tests for _readableStream.awaitDrain Fixes: https://github.com/nodejs/node/issues/8684 PR-URL: https://github.com/nodejs/node/pull/8914 Reviewed-By: Matteo Collina --- ...t-stream-pipe-await-drain-manual-resume.js | 16 ++++++++++++++ ...tream-pipe-await-drain-push-while-write.js | 22 +++++++++++++++++-- test/parallel/test-stream-pipe-await-drain.js | 19 ++++++++++++++++ 3 files changed, 55 insertions(+), 2 deletions(-) diff --git a/test/parallel/test-stream-pipe-await-drain-manual-resume.js b/test/parallel/test-stream-pipe-await-drain-manual-resume.js index 33540b47b3d5e3..96360429e58856 100644 --- a/test/parallel/test-stream-pipe-await-drain-manual-resume.js +++ b/test/parallel/test-stream-pipe-await-drain-manual-resume.js @@ -1,6 +1,7 @@ 'use strict'; const common = require('../common'); const stream = require('stream'); +const assert = require('assert'); // A consumer stream with a very low highWaterMark, which starts in a state // where it buffers the chunk it receives rather than indicating that they @@ -26,6 +27,11 @@ const readable = new stream.Readable({ readable.pipe(writable); readable.once('pause', common.mustCall(() => { + assert.strictEqual( + readable._readableState.awaitDrain, + 1, + 'awaitDrain doesn\'t increase' + ); // First pause, resume manually. The next write() to writable will still // return false, because chunks are still being buffered, so it will increase // the awaitDrain counter again. @@ -34,6 +40,11 @@ readable.once('pause', common.mustCall(() => { })); readable.once('pause', common.mustCall(() => { + assert.strictEqual( + readable._readableState.awaitDrain, + 1, + '.resume() does not reset counter' + ); // Second pause, handle all chunks from now on. Once all callbacks that // are currently queued up are handled, the awaitDrain drain counter should // fall back to 0 and all chunks that are pending on the readable side @@ -50,5 +61,10 @@ readable.push(Buffer.alloc(100)); // Should get through to the writable. readable.push(null); writable.on('finish', common.mustCall(() => { + assert.strictEqual( + readable._readableState.awaitDrain, + 0, + 'awaitDrain not 0 after all chunks are written' + ); // Everything okay, all chunks were written. })); diff --git a/test/parallel/test-stream-pipe-await-drain-push-while-write.js b/test/parallel/test-stream-pipe-await-drain-push-while-write.js index 1dfdfdb80c8d71..67a8f304c31614 100644 --- a/test/parallel/test-stream-pipe-await-drain-push-while-write.js +++ b/test/parallel/test-stream-pipe-await-drain-push-while-write.js @@ -1,16 +1,34 @@ 'use strict'; const common = require('../common'); const stream = require('stream'); +const assert = require('assert'); + +const awaitDrainStates = [ + 1, // after first chunk before callback + 1, // after second chunk before callback + 0 // resolving chunk pushed after first chunk, awaitDrain is decreased +]; // A writable stream which pushes data onto the stream which pipes into it, // but only the first time it's written to. Since it's not paused at this time, // a second write will occur. If the pipe increases awaitDrain twice, we'll // never get subsequent chunks because 'drain' is only emitted once. const writable = new stream.Writable({ - write: common.mustCall((chunk, encoding, cb) => { + write: common.mustCall(function(chunk, encoding, cb) { if (chunk.length === 32 * 1024) { // first chunk - readable.push(new Buffer(33 * 1024)); // above hwm + const beforePush = readable._readableState.awaitDrain; + readable.push(new Buffer(34 * 1024)); // above hwm + // We should check if awaitDrain counter is increased. + const afterPush = readable._readableState.awaitDrain; + assert.strictEqual(afterPush - beforePush, 1, + 'Counter is not increased for awaitDrain'); } + + assert.strictEqual( + awaitDrainStates.shift(), + readable._readableState.awaitDrain, + 'State variable awaitDrain is not correct.' + ); cb(); }, 3) }); diff --git a/test/parallel/test-stream-pipe-await-drain.js b/test/parallel/test-stream-pipe-await-drain.js index fba99ed4563c14..fc822bb60b7aa8 100644 --- a/test/parallel/test-stream-pipe-await-drain.js +++ b/test/parallel/test-stream-pipe-await-drain.js @@ -1,12 +1,14 @@ 'use strict'; const common = require('../common'); const stream = require('stream'); +const assert = require('assert'); // This is very similar to test-stream-pipe-cleanup-pause.js. const reader = new stream.Readable(); const writer1 = new stream.Writable(); const writer2 = new stream.Writable(); +const writer3 = new stream.Writable(); // 560000 is chosen here because it is larger than the (default) highWaterMark // and will cause `.write()` to return false @@ -19,7 +21,10 @@ writer1._write = common.mustCall(function(chunk, encoding, cb) { this.emit('chunk-received'); cb(); }, 1); + writer1.once('chunk-received', function() { + assert.strictEqual(reader._readableState.awaitDrain, 0, + 'initial value is not 0'); setImmediate(function() { // This one should *not* get through to writer1 because writer2 is not // "done" processing. @@ -29,12 +34,26 @@ writer1.once('chunk-received', function() { // A "slow" consumer: writer2._write = common.mustCall(function(chunk, encoding, cb) { + assert.strictEqual( + reader._readableState.awaitDrain, 1, + 'awaitDrain isn\'t 1 after first push' + ); // Not calling cb here to "simulate" slow stream. + // This should be called exactly once, since the first .write() call + // will return false. +}, 1); +writer3._write = common.mustCall(function(chunk, encoding, cb) { + assert.strictEqual( + reader._readableState.awaitDrain, 2, + 'awaitDrain isn\'t 2 after second push' + ); + // Not calling cb here to "simulate" slow stream. // This should be called exactly once, since the first .write() call // will return false. }, 1); reader.pipe(writer1); reader.pipe(writer2); +reader.pipe(writer3); reader.push(buffer); From d047f8e8f84d99f5424691d3837334dc351ead14 Mon Sep 17 00:00:00 2001 From: Jackson Tian Date: Wed, 18 Jan 2017 11:50:33 +0800 Subject: [PATCH 127/291] fs: remove unused parameter for encodeRealpathResult The third parameter `err` is not used anywhere. PR-URL: https://github.com/nodejs/node/pull/10862 Reviewed-By: Anna Henningsen Reviewed-By: Rich Trott Reviewed-By: Brian White Reviewed-By: Luigi Pinca Reviewed-By: Colin Ihrig --- lib/fs.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/fs.js b/lib/fs.js index d407cf1479eac0..da67f2742cb892 100644 --- a/lib/fs.js +++ b/lib/fs.js @@ -1453,8 +1453,8 @@ const splitRootRe = isWindows ? /^(?:[a-zA-Z]:|[\\/]{2}[^\\/]+[\\/][^\\/]+)?[\\/]*/ : /^[/]*/; -function encodeRealpathResult(result, options, err) { - if (!options || !options.encoding || options.encoding === 'utf8' || err) +function encodeRealpathResult(result, options) { + if (!options || !options.encoding || options.encoding === 'utf8') return result; const asBuffer = Buffer.from(result); if (options.encoding === 'buffer') { From 5b38776243593dbfd7c029eda2b8e6987203858d Mon Sep 17 00:00:00 2001 From: abouthiroppy Date: Mon, 16 Jan 2017 15:49:48 +0900 Subject: [PATCH 128/291] test: add http-common's test PR-URL: https://github.com/nodejs/node/pull/10832 Reviewed-By: James M Snell Reviewed-By: Colin Ihrig Reviewed-By: Luigi Pinca --- test/parallel/test-http-common.js | 33 +++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 test/parallel/test-http-common.js diff --git a/test/parallel/test-http-common.js b/test/parallel/test-http-common.js new file mode 100644 index 00000000000000..1629856ce57d09 --- /dev/null +++ b/test/parallel/test-http-common.js @@ -0,0 +1,33 @@ +'use strict'; +require('../common'); +const assert = require('assert'); +const httpCommon = require('_http_common'); +const checkIsHttpToken = httpCommon._checkIsHttpToken; +const checkInvalidHeaderChar = httpCommon._checkInvalidHeaderChar; + +// checkIsHttpToken +assert(checkIsHttpToken('t')); +assert(checkIsHttpToken('tt')); +assert(checkIsHttpToken('ttt')); +assert(checkIsHttpToken('tttt')); +assert(checkIsHttpToken('ttttt')); + +assert.strictEqual(checkIsHttpToken(''), false); +assert.strictEqual(checkIsHttpToken(' '), false); +assert.strictEqual(checkIsHttpToken('あ'), false); +assert.strictEqual(checkIsHttpToken('あa'), false); +assert.strictEqual(checkIsHttpToken('aaaaあaaaa'), false); + +// checkInvalidHeaderChar +assert(checkInvalidHeaderChar('あ')); +assert(checkInvalidHeaderChar('aaaaあaaaa')); + +assert.strictEqual(checkInvalidHeaderChar(''), false); +assert.strictEqual(checkInvalidHeaderChar(1), false); +assert.strictEqual(checkInvalidHeaderChar(' '), false); +assert.strictEqual(checkInvalidHeaderChar(false), false); +assert.strictEqual(checkInvalidHeaderChar('t'), false); +assert.strictEqual(checkInvalidHeaderChar('tt'), false); +assert.strictEqual(checkInvalidHeaderChar('ttt'), false); +assert.strictEqual(checkInvalidHeaderChar('tttt'), false); +assert.strictEqual(checkInvalidHeaderChar('ttttt'), false); From 9d91bf9788a41290b9c2582a482ca3c444ffe096 Mon Sep 17 00:00:00 2001 From: Faiz Halde Date: Sun, 15 Jan 2017 18:16:53 +0530 Subject: [PATCH 129/291] doc: HTTP response getHeader doc fix According to https://github.com/nodejs/node/issues/10803 getHeader need not be called only before it is flushed implicitly. PR-URL: https://github.com/nodejs/node/pull/10817 Reviewed-By: James M Snell Reviewed-By: Sakthipriyan Vairamani Reviewed-By: Luigi Pinca --- doc/api/http.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/doc/api/http.md b/doc/api/http.md index fb90123330458c..ea23dad33a8bd8 100644 --- a/doc/api/http.md +++ b/doc/api/http.md @@ -907,9 +907,8 @@ added: v0.4.0 * `name` {String} * Returns: {String} -Reads out a header that's already been queued but not sent to the client. Note -that the name is case insensitive. This can only be called before headers get -implicitly flushed. +Reads out a header that's already been queued but not sent to the client. +Note that the name is case insensitive. Example: From 47c0953b1281c88d6a0703febeced4468371f0af Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Sat, 14 Jan 2017 19:43:08 -0800 Subject: [PATCH 130/291] benchmark: add benchmark for vm.runIn*() Introduce benchmarks for vm.runInContext() and vm.runInThisContext(). PR-URL: https://github.com/nodejs/node/pull/10816 Reviewed-By: James M Snell Reviewed-By: Anna Henningsen Reviewed-By: Ben Noordhuis Reviewed-By: Brian White --- benchmark/vm/run-in-context.js | 32 +++++++++++++++++++++++++++++ benchmark/vm/run-in-this-context.js | 29 ++++++++++++++++++++++++++ 2 files changed, 61 insertions(+) create mode 100644 benchmark/vm/run-in-context.js create mode 100644 benchmark/vm/run-in-this-context.js diff --git a/benchmark/vm/run-in-context.js b/benchmark/vm/run-in-context.js new file mode 100644 index 00000000000000..62ebe29146e705 --- /dev/null +++ b/benchmark/vm/run-in-context.js @@ -0,0 +1,32 @@ +'use strict'; + +const common = require('../common.js'); + +const bench = common.createBenchmark(main, { + n: [1], + breakOnSigint: [0, 1], + withSigintListener: [0, 1] +}); + +const vm = require('vm'); + +function main(conf) { + const n = +conf.n; + const options = conf.breakOnSigint ? {breakOnSigint: true} : {}; + const withSigintListener = !!conf.withSigintListener; + + process.removeAllListeners('SIGINT'); + if (withSigintListener) + process.on('SIGINT', () => {}); + + var i = 0; + + const contextifiedSandbox = vm.createContext(); + + common.v8ForceOptimization(vm.runInContext, + '0', contextifiedSandbox, options); + bench.start(); + for (; i < n; i++) + vm.runInContext('0', contextifiedSandbox, options); + bench.end(n); +} diff --git a/benchmark/vm/run-in-this-context.js b/benchmark/vm/run-in-this-context.js new file mode 100644 index 00000000000000..f66fd31a1a949e --- /dev/null +++ b/benchmark/vm/run-in-this-context.js @@ -0,0 +1,29 @@ +'use strict'; + +const common = require('../common.js'); + +const bench = common.createBenchmark(main, { + n: [1], + breakOnSigint: [0, 1], + withSigintListener: [0, 1] +}); + +const vm = require('vm'); + +function main(conf) { + const n = +conf.n; + const options = conf.breakOnSigint ? {breakOnSigint: true} : {}; + const withSigintListener = !!conf.withSigintListener; + + process.removeAllListeners('SIGINT'); + if (withSigintListener) + process.on('SIGINT', () => {}); + + var i = 0; + + common.v8ForceOptimization(vm.runInThisContext, '0', options); + bench.start(); + for (; i < n; i++) + vm.runInThisContext('0', options); + bench.end(n); +} From 2641cd496d110c1a2a5a8ba97e6ad1120e9c919f Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Sat, 14 Jan 2017 19:43:33 -0800 Subject: [PATCH 131/291] vm: improve performance of vm.runIn*() Optimize for common cases in vm.runInContext() and vm.runInThisContext(). PR-URL: https://github.com/nodejs/node/pull/10816 Reviewed-By: James M Snell Reviewed-By: Anna Henningsen Reviewed-By: Ben Noordhuis Reviewed-By: Brian White --- lib/vm.js | 26 +++++++++++--------------- 1 file changed, 11 insertions(+), 15 deletions(-) diff --git a/lib/vm.js b/lib/vm.js index 4869d368807665..cf672fbbc14871 100644 --- a/lib/vm.js +++ b/lib/vm.js @@ -17,22 +17,17 @@ const realRunInThisContext = Script.prototype.runInThisContext; const realRunInContext = Script.prototype.runInContext; Script.prototype.runInThisContext = function(options) { - if (options && options.breakOnSigint) { - const realRunInThisContextScript = () => { - return realRunInThisContext.call(this, options); - }; - return sigintHandlersWrap(realRunInThisContextScript); + if (options && options.breakOnSigint && process._events.SIGINT) { + return sigintHandlersWrap(realRunInThisContext, this, [options]); } else { return realRunInThisContext.call(this, options); } }; Script.prototype.runInContext = function(contextifiedSandbox, options) { - if (options && options.breakOnSigint) { - const realRunInContextScript = () => { - return realRunInContext.call(this, contextifiedSandbox, options); - }; - return sigintHandlersWrap(realRunInContextScript); + if (options && options.breakOnSigint && process._events.SIGINT) { + return sigintHandlersWrap(realRunInContext, this, + [contextifiedSandbox, options]); } else { return realRunInContext.call(this, contextifiedSandbox, options); } @@ -83,19 +78,20 @@ exports.isContext = binding.isContext; // Remove all SIGINT listeners and re-attach them after the wrapped function // has executed, so that caught SIGINT are handled by the listeners again. -function sigintHandlersWrap(fn) { +function sigintHandlersWrap(fn, thisArg, argsArray) { // Using the internal list here to make sure `.once()` wrappers are used, // not the original ones. let sigintListeners = process._events.SIGINT; - if (!Array.isArray(sigintListeners)) - sigintListeners = sigintListeners ? [sigintListeners] : []; - else + + if (Array.isArray(sigintListeners)) sigintListeners = sigintListeners.slice(); + else + sigintListeners = [sigintListeners]; process.removeAllListeners('SIGINT'); try { - return fn(); + return fn.apply(thisArg, argsArray); } finally { // Add using the public methods so that the `newListener` handler of // process can re-attach the listeners. From aa8771f84204b17adb843518a5814b1afdc6a0c6 Mon Sep 17 00:00:00 2001 From: Daijiro Wachi Date: Mon, 16 Jan 2017 22:34:04 +0100 Subject: [PATCH 132/291] test: use common.hasIntl in tests related to ICU We should use `common.hasIntl` in tests for test cases which are related to ICU. This way we can easily find the test cases that are Intl dependent. Plus, it will be able to make the tests a little faster if we check hasIntl first. Also, this tweaks the log messages to unify the message. Refs: https://github.com/nodejs/node/pull/10707 PR-URL: https://github.com/nodejs/node/pull/10841 Reviewed-By: Anna Henningsen Reviewed-By: James M Snell Reviewed-By: Colin Ihrig Reviewed-By: Luigi Pinca --- test/parallel/test-icu-punycode.js | 12 ++++++------ test/parallel/test-icu-stringwidth.js | 10 +++++----- test/parallel/test-icu-transcode.js | 6 +++--- test/parallel/test-intl-v8BreakIterator.js | 4 ++-- test/parallel/test-whatwg-url-parsing.js | 2 +- test/parallel/test-whatwg-url-setters.js | 2 +- 6 files changed, 18 insertions(+), 18 deletions(-) diff --git a/test/parallel/test-icu-punycode.js b/test/parallel/test-icu-punycode.js index d9b36e7df78882..62508bc9f78f49 100644 --- a/test/parallel/test-icu-punycode.js +++ b/test/parallel/test-icu-punycode.js @@ -1,6 +1,11 @@ 'use strict'; - const common = require('../common'); + +if (!common.hasIntl) { + common.skip('missing Intl'); + return; +} + const icu = getPunycode(); const assert = require('assert'); @@ -12,11 +17,6 @@ function getPunycode() { } } -if (!icu) { - common.skip('icu punycode tests because ICU is not present.'); - return; -} - // Credit for list: http://www.i18nguy.com/markup/idna-examples.html const tests = [ 'افغانستا.icom.museum', diff --git a/test/parallel/test-icu-stringwidth.js b/test/parallel/test-icu-stringwidth.js index 5b66f00c32840c..80e798b13af154 100644 --- a/test/parallel/test-icu-stringwidth.js +++ b/test/parallel/test-icu-stringwidth.js @@ -1,15 +1,15 @@ // Flags: --expose_internals 'use strict'; - const common = require('../common'); -const assert = require('assert'); -const readline = require('internal/readline'); -if (!process.binding('config').hasIntl) { - common.skip('missing intl... skipping test'); +if (!common.hasIntl) { + common.skip('missing Intl'); return; } +const assert = require('assert'); +const readline = require('internal/readline'); + // Test column width assert.strictEqual(readline.getStringWidth('a'), 1); assert.strictEqual(readline.getStringWidth('丁'), 2); diff --git a/test/parallel/test-icu-transcode.js b/test/parallel/test-icu-transcode.js index 87f32a745a35cb..463b2fca9188ba 100644 --- a/test/parallel/test-icu-transcode.js +++ b/test/parallel/test-icu-transcode.js @@ -1,14 +1,14 @@ 'use strict'; const common = require('../common'); -const buffer = require('buffer'); -const assert = require('assert'); if (!common.hasIntl) { - common.skip('icu punycode tests because ICU is not present.'); + common.skip('missing Intl'); return; } +const buffer = require('buffer'); +const assert = require('assert'); const orig = Buffer.from('tést €', 'utf8'); // Test Transcoding diff --git a/test/parallel/test-intl-v8BreakIterator.js b/test/parallel/test-intl-v8BreakIterator.js index 4af3452b576f84..70f0f782bbc7e7 100644 --- a/test/parallel/test-intl-v8BreakIterator.js +++ b/test/parallel/test-intl-v8BreakIterator.js @@ -1,11 +1,11 @@ 'use strict'; const common = require('../common'); -const assert = require('assert'); if (!common.hasIntl || Intl.v8BreakIterator === undefined) { - return common.skip('no Intl'); + return common.skip('missing Intl'); } +const assert = require('assert'); const warning = 'Intl.v8BreakIterator is deprecated and will be removed soon.'; common.expectWarning('DeprecationWarning', warning); diff --git a/test/parallel/test-whatwg-url-parsing.js b/test/parallel/test-whatwg-url-parsing.js index c83d30da414571..9ea6cc74bff5e6 100644 --- a/test/parallel/test-whatwg-url-parsing.js +++ b/test/parallel/test-whatwg-url-parsing.js @@ -4,7 +4,7 @@ const common = require('../common'); if (!common.hasIntl) { // A handful of the tests fail when ICU is not included. - common.skip('missing Intl... skipping test'); + common.skip('missing Intl'); return; } diff --git a/test/parallel/test-whatwg-url-setters.js b/test/parallel/test-whatwg-url-setters.js index 3b2aca2afd89d7..236737e18177fe 100644 --- a/test/parallel/test-whatwg-url-setters.js +++ b/test/parallel/test-whatwg-url-setters.js @@ -4,7 +4,7 @@ const common = require('../common'); if (!common.hasIntl) { // A handful of the tests fail when ICU is not included. - common.skip('missing Intl... skipping test'); + common.skip('missing Intl'); return; } From d24491c6a726f7094e87cd6d38ddf615c198c99f Mon Sep 17 00:00:00 2001 From: cjihrig Date: Mon, 16 Jan 2017 16:57:36 -0500 Subject: [PATCH 133/291] process: add NODE_NO_WARNINGS environment variable This commit adds support for a NODE_NO_WARNINGS environment variable, which duplicates the functionality of the --no-warnings command line flag. Fixes: https://github.com/nodejs/node/issues/10802 PR-URL: https://github.com/nodejs/node/pull/10842 Reviewed-By: James M Snell Reviewed-By: Anna Henningsen Reviewed-By: Evan Lucas Reviewed-By: Sam Roberts Reviewed-By: Italo A. Casas --- doc/api/cli.md | 7 ++++ doc/node.1 | 4 +++ lib/internal/process/warning.js | 2 +- test/parallel/test-env-var-no-warnings.js | 41 +++++++++++++++++++++++ 4 files changed, 53 insertions(+), 1 deletion(-) create mode 100644 test/parallel/test-env-var-no-warnings.js diff --git a/doc/api/cli.md b/doc/api/cli.md index 3f51c97b818d8d..30d4c62e52b8a1 100644 --- a/doc/api/cli.md +++ b/doc/api/cli.md @@ -287,6 +287,13 @@ added: v0.11.15 Data path for ICU (Intl object) data. Will extend linked-in data when compiled with small-icu support. +### `NODE_NO_WARNINGS=1` + + +When set to `1`, process warnings are silenced. + ### `NODE_PRESERVE_SYMLINKS=1` The default curve name to use for ECDH key agreement in a tls server. The default value is `'prime256v1'` (NIST P-256). Consult [RFC 4492] and From fb35ca35988c50d9f32aeb37e5615646c504ddc2 Mon Sep 17 00:00:00 2001 From: Sam Roberts Date: Fri, 20 Jan 2017 11:11:45 -0800 Subject: [PATCH 166/291] test: test hmac binding robustness The Hmac binding layer is not documented as part of the API, and is not intended to be used, but it should be robust to misuse, and contains defensive checks for misuse. This test checks that updates without init throw (as opposed to abort or misbehave in some other way). PR-URL: https://github.com/nodejs/node/pull/10923 Reviewed-By: Colin Ihrig Reviewed-By: Rich Trott Reviewed-By: James M Snell --- test/parallel/test-crypto-hmac.js | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/test/parallel/test-crypto-hmac.js b/test/parallel/test-crypto-hmac.js index 5307ea4f6f9e05..da532d7657cb61 100644 --- a/test/parallel/test-crypto-hmac.js +++ b/test/parallel/test-crypto-hmac.js @@ -8,6 +8,14 @@ if (!common.hasCrypto) { } var crypto = require('crypto'); +// Test for binding layer robustness +{ + const binding = process.binding('crypto'); + const h = new binding.Hmac(); + // Fail to init the Hmac with an algorithm. + assert.throws(() => h.update('hello'), /^TypeError: HmacUpdate fail$/); +} + // Test HMAC var h1 = crypto.createHmac('sha1', 'Node') .update('some data') From 1438d0011942880f53536877303f4c595fbe1357 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Sat, 31 Dec 2016 21:39:57 -0800 Subject: [PATCH 167/291] benchmark,lib,test: adjust for linting Formatting changes for upcoming linter update. PR-URL: https://github.com/nodejs/node/pull/10561 Reviewed-By: Teddy Katz Reviewed-By: James M Snell Reviewed-By: Sam Roberts --- benchmark/url/whatwg-url-properties.js | 4 +- lib/internal/module.js | 10 +- lib/os.js | 5 +- lib/repl.js | 27 ++-- lib/util.js | 6 +- test/common.js | 2 +- test/inspector/test-inspector.js | 8 +- test/internet/test-dns-ipv4.js | 92 +++++++------- test/internet/test-dns-ipv6.js | 62 ++++----- test/parallel/test-assert.js | 8 +- test/parallel/test-buffer-fill.js | 14 +-- test/parallel/test-buffer-includes.js | 4 +- test/parallel/test-buffer-slice.js | 62 ++++----- test/parallel/test-cli-eval.js | 69 +++++----- test/parallel/test-cluster-worker-exit.js | 5 +- test/parallel/test-crypto-authenticated.js | 15 ++- test/parallel/test-crypto-hash.js | 4 +- test/parallel/test-crypto-hmac.js | 26 ++-- test/parallel/test-crypto-rsa-dsa.js | 8 +- test/parallel/test-dns.js | 2 +- ...n-throw-from-uncaught-exception-handler.js | 33 ++--- .../test-fs-non-number-arguments-throw.js | 6 +- test/parallel/test-fs-realpath.js | 28 ++--- .../test-http-double-content-length.js | 6 +- test/parallel/test-http-localaddress.js | 8 +- test/parallel/test-http-proxy.js | 4 +- test/parallel/test-os.js | 8 +- test/parallel/test-preload.js | 83 ++++++------ test/parallel/test-punycode.js | 18 ++- test/parallel/test-querystring.js | 10 +- test/parallel/test-readline-interface.js | 2 +- test/parallel/test-repl-tab-complete.js | 2 +- test/parallel/test-require-symlink.js | 10 +- test/parallel/test-spawn-cmd-named-pipe.js | 2 +- test/parallel/test-tls-client-verify.js | 38 +++--- test/parallel/test-tls-no-sslv3.js | 4 +- ...rver-failed-handshake-emits-clienterror.js | 2 +- test/parallel/test-tls-server-verify.js | 118 +++++++++--------- ...tls-socket-failed-handshake-emits-error.js | 2 +- test/parallel/test-util-inspect.js | 11 +- test/parallel/test-util-sigint-watchdog.js | 64 +++++----- test/parallel/test-whatwg-url-properties.js | 6 +- test/parallel/test-zerolengthbufferbug.js | 2 +- test/parallel/test-zlib-invalid-input.js | 6 +- test/parallel/test-zlib.js | 6 +- .../test-crypto-timing-safe-equal.js | 6 +- 46 files changed, 471 insertions(+), 447 deletions(-) diff --git a/benchmark/url/whatwg-url-properties.js b/benchmark/url/whatwg-url-properties.js index a3c4d886bd3c90..375939c601d363 100644 --- a/benchmark/url/whatwg-url-properties.js +++ b/benchmark/url/whatwg-url-properties.js @@ -11,8 +11,8 @@ var bench = common.createBenchmark(main, { 'http://user:pass@foo.bar.com:21/aaa/zzz?l=24#test' ], prop: ['toString', 'href', 'origin', 'protocol', - 'username', 'password', 'host', 'hostname', 'port', - 'pathname', 'search', 'searchParams', 'hash'], + 'username', 'password', 'host', 'hostname', 'port', + 'pathname', 'search', 'searchParams', 'hash'], n: [1e4] }); diff --git a/lib/internal/module.js b/lib/internal/module.js index a12af12f3e3d7e..2f38618daac5f7 100644 --- a/lib/internal/module.js +++ b/lib/internal/module.js @@ -51,10 +51,12 @@ function stripBOM(content) { return content; } -exports.builtinLibs = ['assert', 'buffer', 'child_process', 'cluster', - 'crypto', 'dgram', 'dns', 'domain', 'events', 'fs', 'http', 'https', 'net', - 'os', 'path', 'punycode', 'querystring', 'readline', 'repl', 'stream', - 'string_decoder', 'tls', 'tty', 'url', 'util', 'v8', 'vm', 'zlib']; +exports.builtinLibs = [ + 'assert', 'buffer', 'child_process', 'cluster', 'crypto', 'dgram', 'dns', + 'domain', 'events', 'fs', 'http', 'https', 'net', 'os', 'path', 'punycode', + 'querystring', 'readline', 'repl', 'stream', 'string_decoder', 'tls', 'tty', + 'url', 'util', 'v8', 'vm', 'zlib' +]; function addBuiltinLibsToObject(object) { // Make built-in modules available directly (loaded lazily). diff --git a/lib/os.js b/lib/os.js index cab148581a9db3..a59cc49bae8c51 100644 --- a/lib/os.js +++ b/lib/os.js @@ -51,8 +51,9 @@ exports.tmpdir = function() { return path; }; -exports.tmpDir = internalUtil.deprecate(exports.tmpdir, - 'os.tmpDir() is deprecated. Use os.tmpdir() instead.'); +const tmpDirDeprecationMsg = + 'os.tmpDir() is deprecated. Use os.tmpdir() instead.'; +exports.tmpDir = internalUtil.deprecate(exports.tmpdir, tmpDirDeprecationMsg); exports.getNetworkInterfaces = internalUtil.deprecate(function() { return exports.networkInterfaces(); diff --git a/lib/repl.js b/lib/repl.js index 5667bd350a949e..302e79f9a2752c 100644 --- a/lib/repl.js +++ b/lib/repl.js @@ -39,13 +39,13 @@ const debug = util.debuglog('repl'); const parentModule = module; const replMap = new WeakMap(); -const GLOBAL_OBJECT_PROPERTIES = ['NaN', 'Infinity', 'undefined', - 'eval', 'parseInt', 'parseFloat', 'isNaN', 'isFinite', 'decodeURI', - 'decodeURIComponent', 'encodeURI', 'encodeURIComponent', - 'Object', 'Function', 'Array', 'String', 'Boolean', 'Number', - 'Date', 'RegExp', 'Error', 'EvalError', 'RangeError', - 'ReferenceError', 'SyntaxError', 'TypeError', 'URIError', - 'Math', 'JSON']; +const GLOBAL_OBJECT_PROPERTIES = [ + 'NaN', 'Infinity', 'undefined', 'eval', 'parseInt', 'parseFloat', 'isNaN', + 'isFinite', 'decodeURI', 'decodeURIComponent', 'encodeURI', + 'encodeURIComponent', 'Object', 'Function', 'Array', 'String', 'Boolean', + 'Number', 'Date', 'RegExp', 'Error', 'EvalError', 'RangeError', + 'ReferenceError', 'SyntaxError', 'TypeError', 'URIError', 'Math', 'JSON' +]; const GLOBAL_OBJECT_PROPERTY_MAP = {}; GLOBAL_OBJECT_PROPERTIES.forEach((p) => GLOBAL_OBJECT_PROPERTY_MAP[p] = p); @@ -1214,12 +1214,13 @@ function addStandardGlobals(completionGroups, filter) { // Common keywords. Exclude for completion on the empty string, b/c // they just get in the way. if (filter) { - completionGroups.push(['break', 'case', 'catch', 'const', - 'continue', 'debugger', 'default', 'delete', 'do', 'else', - 'export', 'false', 'finally', 'for', 'function', 'if', - 'import', 'in', 'instanceof', 'let', 'new', 'null', 'return', - 'switch', 'this', 'throw', 'true', 'try', 'typeof', 'undefined', - 'var', 'void', 'while', 'with', 'yield']); + completionGroups.push([ + 'break', 'case', 'catch', 'const', 'continue', 'debugger', 'default', + 'delete', 'do', 'else', 'export', 'false', 'finally', 'for', 'function', + 'if', 'import', 'in', 'instanceof', 'let', 'new', 'null', 'return', + 'switch', 'this', 'throw', 'true', 'try', 'typeof', 'undefined', 'var', + 'void', 'while', 'with', 'yield' + ]); } } diff --git a/lib/util.js b/lib/util.js index 4069fc3b4872de..9d5909cdc7ce30 100644 --- a/lib/util.js +++ b/lib/util.js @@ -404,7 +404,7 @@ function formatValue(ctx, value, recurseTimes) { if (keys.length === 0) { if (typeof value === 'function') { return ctx.stylize(`[Function${value.name ? `: ${value.name}` : ''}]`, - 'special'); + 'special'); } if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); @@ -664,7 +664,7 @@ function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { for (var i = 0; i < maxLength; ++i) { if (hasOwnProperty(value, String(i))) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - String(i), true)); + String(i), true)); } else { output.push(''); } @@ -675,7 +675,7 @@ function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { keys.forEach(function(key) { if (typeof key === 'symbol' || !key.match(/^\d+$/)) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - key, true)); + key, true)); } }); return output; diff --git a/test/common.js b/test/common.js index 13c9c1127f6dcd..5ee9a5ce314793 100644 --- a/test/common.js +++ b/test/common.js @@ -470,7 +470,7 @@ exports.canCreateSymLink = function() { // If unix tools are in the path, they can shadow the one we want, // so use the full path while executing whoami const whoamiPath = path.join(process.env['SystemRoot'], - 'System32', 'whoami.exe'); + 'System32', 'whoami.exe'); let err = false; let output = ''; diff --git a/test/inspector/test-inspector.js b/test/inspector/test-inspector.js index 7e53eaa55fffb7..a1c69cb6fbb2fe 100644 --- a/test/inspector/test-inspector.js +++ b/test/inspector/test-inspector.js @@ -114,10 +114,10 @@ function testSetBreakpointAndResume(session) { const commands = [ { 'method': 'Debugger.setBreakpointByUrl', 'params': { 'lineNumber': 5, - 'url': session.mainScriptPath, - 'columnNumber': 0, - 'condition': '' - } + 'url': session.mainScriptPath, + 'columnNumber': 0, + 'condition': '' + } }, { 'method': 'Debugger.resume'}, [ { 'method': 'Debugger.getScriptSource', diff --git a/test/internet/test-dns-ipv4.js b/test/internet/test-dns-ipv4.js index a86c863cc443c9..c4f2d00df886d9 100644 --- a/test/internet/test-dns-ipv4.js +++ b/test/internet/test-dns-ipv4.js @@ -36,61 +36,61 @@ function checkWrap(req) { TEST(function test_resolve4(done) { const req = dns.resolve4('www.google.com', - common.mustCall((err, ips) => { - assert.ifError(err); + common.mustCall((err, ips) => { + assert.ifError(err); - assert.ok(ips.length > 0); + assert.ok(ips.length > 0); - for (let i = 0; i < ips.length; i++) { - assert.ok(isIPv4(ips[i])); - } + for (let i = 0; i < ips.length; i++) { + assert.ok(isIPv4(ips[i])); + } - done(); - })); + done(); + })); checkWrap(req); }); TEST(function test_reverse_ipv4(done) { const req = dns.reverse('8.8.8.8', - common.mustCall((err, domains) => { - assert.ifError(err); + common.mustCall((err, domains) => { + assert.ifError(err); - assert.ok(domains.length > 0); + assert.ok(domains.length > 0); - for (let i = 0; i < domains.length; i++) { - assert.ok(domains[i]); - assert.ok(typeof domains[i] === 'string'); - } + for (let i = 0; i < domains.length; i++) { + assert.ok(domains[i]); + assert.ok(typeof domains[i] === 'string'); + } - done(); - })); + done(); + })); checkWrap(req); }); TEST(function test_lookup_ipv4_explicit(done) { const req = dns.lookup('www.google.com', 4, - common.mustCall((err, ip, family) => { - assert.ifError(err); - assert.ok(net.isIPv4(ip)); - assert.strictEqual(family, 4); + common.mustCall((err, ip, family) => { + assert.ifError(err); + assert.ok(net.isIPv4(ip)); + assert.strictEqual(family, 4); - done(); - })); + done(); + })); checkWrap(req); }); TEST(function test_lookup_ipv4_implicit(done) { const req = dns.lookup('www.google.com', - common.mustCall((err, ip, family) => { - assert.ifError(err); - assert.ok(net.isIPv4(ip)); - assert.strictEqual(family, 4); + common.mustCall((err, ip, family) => { + assert.ifError(err); + assert.ok(net.isIPv4(ip)); + assert.strictEqual(family, 4); - done(); - })); + done(); + })); checkWrap(req); }); @@ -125,26 +125,26 @@ TEST(function test_lookup_ipv4_hint_addrconfig(done) { TEST(function test_lookup_ip_ipv4(done) { const req = dns.lookup('127.0.0.1', - common.mustCall((err, ip, family) => { - assert.ifError(err); - assert.strictEqual(ip, '127.0.0.1'); - assert.strictEqual(family, 4); + common.mustCall((err, ip, family) => { + assert.ifError(err); + assert.strictEqual(ip, '127.0.0.1'); + assert.strictEqual(family, 4); - done(); - })); + done(); + })); checkWrap(req); }); TEST(function test_lookup_localhost_ipv4(done) { const req = dns.lookup('localhost', 4, - common.mustCall((err, ip, family) => { - assert.ifError(err); - assert.strictEqual(ip, '127.0.0.1'); - assert.strictEqual(family, 4); + common.mustCall((err, ip, family) => { + assert.ifError(err); + assert.strictEqual(ip, '127.0.0.1'); + assert.strictEqual(family, 4); - done(); - })); + done(); + })); checkWrap(req); }); @@ -164,21 +164,23 @@ TEST(function test_lookup_all_ipv4(done) { }); done(); - } - )); + }) + ); checkWrap(req); }); TEST(function test_lookupservice_ip_ipv4(done) { - const req = dns.lookupService('127.0.0.1', 80, + const req = dns.lookupService( + '127.0.0.1', 80, common.mustCall((err, host, service) => { assert.ifError(err); assert.strictEqual(typeof host, 'string'); assert(host); assert(['http', 'www', '80'].includes(service)); done(); - })); + }) + ); checkWrap(req); }); diff --git a/test/internet/test-dns-ipv6.js b/test/internet/test-dns-ipv6.js index 90d2a19a7f6c9e..34382660f24423 100644 --- a/test/internet/test-dns-ipv6.js +++ b/test/internet/test-dns-ipv6.js @@ -41,45 +41,45 @@ function checkWrap(req) { TEST(function test_resolve6(done) { const req = dns.resolve6('ipv6.google.com', - common.mustCall((err, ips) => { - assert.ifError(err); + common.mustCall((err, ips) => { + assert.ifError(err); - assert.ok(ips.length > 0); + assert.ok(ips.length > 0); - for (let i = 0; i < ips.length; i++) - assert.ok(isIPv6(ips[i])); + for (let i = 0; i < ips.length; i++) + assert.ok(isIPv6(ips[i])); - done(); - })); + done(); + })); checkWrap(req); }); TEST(function test_reverse_ipv6(done) { const req = dns.reverse('2001:4860:4860::8888', - common.mustCall((err, domains) => { - assert.ifError(err); + common.mustCall((err, domains) => { + assert.ifError(err); - assert.ok(domains.length > 0); + assert.ok(domains.length > 0); - for (let i = 0; i < domains.length; i++) - assert.ok(typeof domains[i] === 'string'); + for (let i = 0; i < domains.length; i++) + assert.ok(typeof domains[i] === 'string'); - done(); - })); + done(); + })); checkWrap(req); }); TEST(function test_lookup_ipv6_explicit(done) { const req = dns.lookup('ipv6.google.com', 6, - common.mustCall((err, ip, family) => { - assert.ifError(err); - assert.ok(isIPv6(ip)); - assert.strictEqual(family, 6); + common.mustCall((err, ip, family) => { + assert.ifError(err); + assert.ok(isIPv6(ip)); + assert.strictEqual(family, 6); - done(); - })); + done(); + })); checkWrap(req); }); @@ -142,13 +142,13 @@ TEST(function test_lookup_ipv6_hint(done) { TEST(function test_lookup_ip_ipv6(done) { const req = dns.lookup('::1', - common.mustCall((err, ip, family) => { - assert.ifError(err); - assert.ok(isIPv6(ip)); - assert.strictEqual(family, 6); + common.mustCall((err, ip, family) => { + assert.ifError(err); + assert.ok(isIPv6(ip)); + assert.strictEqual(family, 6); - done(); - })); + done(); + })); checkWrap(req); }); @@ -169,14 +169,15 @@ TEST(function test_lookup_all_ipv6(done) { }); done(); - } - )); + }) + ); checkWrap(req); }); TEST(function test_lookupservice_ip_ipv6(done) { - const req = dns.lookupService('::1', 80, + const req = dns.lookupService( + '::1', 80, common.mustCall((err, host, service) => { if (err) { // Not skipping the test, rather checking an alternative result, @@ -188,7 +189,8 @@ TEST(function test_lookupservice_ip_ipv6(done) { assert(host); assert(['http', 'www', '80'].includes(service)); done(); - })); + }) + ); checkWrap(req); }); diff --git a/test/parallel/test-assert.js b/test/parallel/test-assert.js index ca78f89011215e..3d2481ef4ec49b 100644 --- a/test/parallel/test-assert.js +++ b/test/parallel/test-assert.js @@ -64,7 +64,7 @@ assert.doesNotThrow(makeBlock(a.notStrictEqual, 2, '2'), // deepEqual joy! // 7.2 assert.doesNotThrow(makeBlock(a.deepEqual, new Date(2000, 3, 14), - new Date(2000, 3, 14)), + new Date(2000, 3, 14)), 'deepEqual(new Date(2000, 3, 14), new Date(2000, 3, 14))'); assert.throws(makeBlock(a.deepEqual, new Date(), new Date(2000, 3, 14)), @@ -81,7 +81,7 @@ assert.doesNotThrow(makeBlock( a.notDeepEqual, new Date(), new Date(2000, 3, 14)), - 'notDeepEqual(new Date(), new Date(2000, 3, 14))' + 'notDeepEqual(new Date(), new Date(2000, 3, 14))' ); // 7.3 @@ -385,7 +385,7 @@ assert.doesNotThrow(function() { assert.ifError(); }); assert.throws(() => { assert.doesNotThrow(makeBlock(thrower, Error), 'user message'); }, /Got unwanted exception. user message/, - 'a.doesNotThrow ignores user message'); + 'a.doesNotThrow ignores user message'); // make sure that validating using constructor really works threw = false; @@ -509,7 +509,7 @@ testAssertionMessage({}, '{}'); testAssertionMessage(circular, '{ y: 1, x: [Circular] }'); testAssertionMessage({a: undefined, b: null}, '{ a: undefined, b: null }'); testAssertionMessage({a: NaN, b: Infinity, c: -Infinity}, - '{ a: NaN, b: Infinity, c: -Infinity }'); + '{ a: NaN, b: Infinity, c: -Infinity }'); // #2893 try { diff --git a/test/parallel/test-buffer-fill.js b/test/parallel/test-buffer-fill.js index eecb14abb06001..8cfeeabe91eebe 100644 --- a/test/parallel/test-buffer-fill.js +++ b/test/parallel/test-buffer-fill.js @@ -184,20 +184,20 @@ deepStrictEqualValues(genBuffer(4, [hexBufFill, 1, -1]), [0, 0, 0, 0]); assert.throws(() => buf1.fill(0, -1), /^RangeError: Out of range index$/); assert.throws(() => buf1.fill(0, 0, buf1.length + 1), - /^RangeError: Out of range index$/); + /^RangeError: Out of range index$/); assert.throws(() => buf1.fill('', -1), /^RangeError: Out of range index$/); assert.throws(() => buf1.fill('', 0, buf1.length + 1), - /^RangeError: Out of range index$/); + /^RangeError: Out of range index$/); assert.throws(() => buf1.fill('a', 0, buf1.length, 'node rocks!'), - /^TypeError: Unknown encoding: node rocks!$/); + /^TypeError: Unknown encoding: node rocks!$/); assert.throws(() => buf1.fill('a', 0, 0, NaN), - /^TypeError: encoding must be a string$/); + /^TypeError: encoding must be a string$/); assert.throws(() => buf1.fill('a', 0, 0, null), - /^TypeError: encoding must be a string$/); + /^TypeError: encoding must be a string$/); assert.throws(() => buf1.fill('a', 0, 0, 'foo'), /^TypeError: Unknown encoding: foo$/); @@ -271,10 +271,10 @@ function testBufs(string, offset, length, encoding) { // Make sure these throw. assert.throws(() => Buffer.allocUnsafe(8).fill('a', -1), - /^RangeError: Out of range index$/); + /^RangeError: Out of range index$/); assert.throws(() => Buffer.allocUnsafe(8).fill('a', 0, 9), - /^RangeError: Out of range index$/); + /^RangeError: Out of range index$/); // Make sure this doesn't hang indefinitely. Buffer.allocUnsafe(8).fill(''); diff --git a/test/parallel/test-buffer-includes.js b/test/parallel/test-buffer-includes.js index 22ba1e6b7e1735..15e1eedeb54d15 100644 --- a/test/parallel/test-buffer-includes.js +++ b/test/parallel/test-buffer-includes.js @@ -159,10 +159,10 @@ assert( 6, mixedByteStringUcs2.includes(Buffer.from('bc', 'ucs2'), 0, 'ucs2')); assert( 10, mixedByteStringUcs2.includes(Buffer.from('\u03a3', 'ucs2'), - 0, 'ucs2')); + 0, 'ucs2')); assert( -1, mixedByteStringUcs2.includes(Buffer.from('\u0396', 'ucs2'), - 0, 'ucs2')); + 0, 'ucs2')); twoByteString = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2'); diff --git a/test/parallel/test-buffer-slice.js b/test/parallel/test-buffer-slice.js index 2489420c33e6e9..b43654b952de0b 100644 --- a/test/parallel/test-buffer-slice.js +++ b/test/parallel/test-buffer-slice.js @@ -8,54 +8,54 @@ assert.strictEqual(0, Buffer('hello', 'utf8').slice(0, 0).length); const buf = Buffer.from('0123456789', 'utf8'); assert.strictEqual(0, Buffer.compare(buf.slice(-10, 10), - Buffer.from('0123456789', 'utf8'))); + Buffer.from('0123456789', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice(-20, 10), - Buffer.from('0123456789', 'utf8'))); + Buffer.from('0123456789', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice(-20, -10), - Buffer.from('', 'utf8'))); + Buffer.from('', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice(), - Buffer.from('0123456789', 'utf8'))); + Buffer.from('0123456789', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice(0), - Buffer.from('0123456789', 'utf8'))); + Buffer.from('0123456789', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice(0, 0), - Buffer.from('', 'utf8'))); + Buffer.from('', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice(undefined), - Buffer.from('0123456789', 'utf8'))); + Buffer.from('0123456789', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice('foobar'), - Buffer.from('0123456789', 'utf8'))); + Buffer.from('0123456789', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice(undefined, undefined), - Buffer.from('0123456789', 'utf8'))); + Buffer.from('0123456789', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice(2), - Buffer.from('23456789', 'utf8'))); + Buffer.from('23456789', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice(5), - Buffer.from('56789', 'utf8'))); + Buffer.from('56789', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice(10), - Buffer.from('', 'utf8'))); + Buffer.from('', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice(5, 8), - Buffer.from('567', 'utf8'))); + Buffer.from('567', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice(8, -1), - Buffer.from('8', 'utf8'))); + Buffer.from('8', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice(-10), - Buffer.from('0123456789', 'utf8'))); + Buffer.from('0123456789', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice(0, -9), - Buffer.from('0', 'utf8'))); + Buffer.from('0', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice(0, -10), - Buffer.from('', 'utf8'))); + Buffer.from('', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice(0, -1), - Buffer.from('012345678', 'utf8'))); + Buffer.from('012345678', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice(2, -2), - Buffer.from('234567', 'utf8'))); + Buffer.from('234567', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice(0, 65536), - Buffer.from('0123456789', 'utf8'))); + Buffer.from('0123456789', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice(65536, 0), - Buffer.from('', 'utf8'))); + Buffer.from('', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice(-5, -8), - Buffer.from('', 'utf8'))); + Buffer.from('', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice(-5, -3), - Buffer.from('56', 'utf8'))); + Buffer.from('56', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice(-10, 10), - Buffer.from('0123456789', 'utf8'))); + Buffer.from('0123456789', 'utf8'))); for (let i = 0, s = buf; i < buf.length; ++i) { assert.strictEqual(0, Buffer.compare(buf.slice(i), s.slice(i))); assert.strictEqual(0, Buffer.compare(buf.slice(0, i), s.slice(0, i))); @@ -67,19 +67,19 @@ const utf16Buf = Buffer.from('0123456789', 'utf16le'); assert.deepStrictEqual(utf16Buf.slice(0, 6), Buffer.from('012', 'utf16le')); assert.strictEqual(0, Buffer.compare(buf.slice('0', '1'), - Buffer.from('0', 'utf8'))); + Buffer.from('0', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice('-5', '10'), - Buffer.from('56789', 'utf8'))); + Buffer.from('56789', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice('-10', '10'), - Buffer.from('0123456789', 'utf8'))); + Buffer.from('0123456789', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice('-10', '-5'), - Buffer.from('01234', 'utf8'))); + Buffer.from('01234', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice('-10', '-0'), - Buffer.from('', 'utf8'))); + Buffer.from('', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice('111'), - Buffer.from('', 'utf8'))); + Buffer.from('', 'utf8'))); assert.strictEqual(0, Buffer.compare(buf.slice('0', '-111'), - Buffer.from('', 'utf8'))); + Buffer.from('', 'utf8'))); // try to slice a zero length Buffer // see https://github.com/joyent/node/issues/5881 diff --git a/test/parallel/test-cli-eval.js b/test/parallel/test-cli-eval.js index 0198a0f1beda48..8db7ad30872223 100644 --- a/test/parallel/test-cli-eval.js +++ b/test/parallel/test-cli-eval.js @@ -18,27 +18,27 @@ var filename = __filename.replace(/\\/g, '/'); // assert that nothing is written to stdout child.exec(nodejs + ' --eval 42', - function(err, stdout, stderr) { - assert.strictEqual(stdout, ''); - assert.strictEqual(stderr, ''); - }); + function(err, stdout, stderr) { + assert.strictEqual(stdout, ''); + assert.strictEqual(stderr, ''); + }); // assert that "42\n" is written to stderr child.exec(nodejs + ' --eval "console.error(42)"', - function(err, stdout, stderr) { - assert.strictEqual(stdout, ''); - assert.strictEqual(stderr, '42\n'); - }); + function(err, stdout, stderr) { + assert.strictEqual(stdout, ''); + assert.strictEqual(stderr, '42\n'); + }); // assert that the expected output is written to stdout ['--print', '-p -e', '-pe', '-p'].forEach(function(s) { var cmd = nodejs + ' ' + s + ' '; child.exec(cmd + '42', - function(err, stdout, stderr) { - assert.strictEqual(stdout, '42\n'); - assert.strictEqual(stderr, ''); - }); + function(err, stdout, stderr) { + assert.strictEqual(stdout, '42\n'); + assert.strictEqual(stderr, ''); + }); child.exec(cmd + "'[]'", common.mustCall( function(err, stdout, stderr) { @@ -49,22 +49,22 @@ child.exec(nodejs + ' --eval "console.error(42)"', // assert that module loading works child.exec(nodejs + ' --eval "require(\'' + filename + '\')"', - function(status, stdout, stderr) { - assert.strictEqual(status.code, 42); - }); + function(status, stdout, stderr) { + assert.strictEqual(status.code, 42); + }); // Check that builtin modules are pre-defined. child.exec(nodejs + ' --print "os.platform()"', - function(status, stdout, stderr) { - assert.strictEqual(stderr, ''); - assert.strictEqual(stdout.trim(), require('os').platform()); - }); + function(status, stdout, stderr) { + assert.strictEqual(stderr, ''); + assert.strictEqual(stdout.trim(), require('os').platform()); + }); // module path resolve bug, regression test child.exec(nodejs + ' --eval "require(\'./test/parallel/test-cli-eval.js\')"', - function(status, stdout, stderr) { - assert.strictEqual(status.code, 42); - }); + function(status, stdout, stderr) { + assert.strictEqual(status.code, 42); + }); // Missing argument should not crash child.exec(nodejs + ' -e', common.mustCall(function(status, stdout, stderr) { @@ -80,24 +80,25 @@ child.exec(nodejs + ' -e ""', function(status, stdout, stderr) { // "\\-42" should be interpreted as an escaped expression, not a switch child.exec(nodejs + ' -p "\\-42"', - function(err, stdout, stderr) { - assert.strictEqual(stdout, '-42\n'); - assert.strictEqual(stderr, ''); - }); + function(err, stdout, stderr) { + assert.strictEqual(stdout, '-42\n'); + assert.strictEqual(stderr, ''); + }); child.exec(nodejs + ' --use-strict -p process.execArgv', - function(status, stdout, stderr) { - assert.strictEqual(stdout, - "[ '--use-strict', '-p', 'process.execArgv' ]\n"); - }); + function(status, stdout, stderr) { + assert.strictEqual( + stdout, "[ '--use-strict', '-p', 'process.execArgv' ]\n" + ); + }); // Regression test for https://github.com/nodejs/node/issues/3574 const emptyFile = path.join(common.fixturesDir, 'empty.js'); child.exec(nodejs + ` -e 'require("child_process").fork("${emptyFile}")'`, - function(status, stdout, stderr) { - assert.strictEqual(stdout, ''); - assert.strictEqual(stderr, ''); - }); + function(status, stdout, stderr) { + assert.strictEqual(stdout, ''); + assert.strictEqual(stderr, ''); + }); // Regression test for https://github.com/nodejs/node/issues/8534. { diff --git a/test/parallel/test-cluster-worker-exit.js b/test/parallel/test-cluster-worker-exit.js index 1c0ec509c468ad..1cd7b1d0f222c7 100644 --- a/test/parallel/test-cluster-worker-exit.js +++ b/test/parallel/test-cluster-worker-exit.js @@ -32,8 +32,9 @@ if (cluster.isWorker) { worker_emitExit: [1, "the worker did not emit 'exit'"], worker_state: ['disconnected', 'the worker state is incorrect'], worker_suicideMode: [false, 'the worker.suicide flag is incorrect'], - worker_exitedAfterDisconnect: [false, - 'the .exitedAfterDisconnect flag is incorrect'], + worker_exitedAfterDisconnect: [ + false, 'the .exitedAfterDisconnect flag is incorrect' + ], worker_died: [true, 'the worker is still running'], worker_exitCode: [EXIT_CODE, 'the worker exited w/ incorrect exitCode'], worker_signalCode: [null, 'the worker exited w/ incorrect signalCode'] diff --git a/test/parallel/test-crypto-authenticated.js b/test/parallel/test-crypto-authenticated.js index ee67250ff35223..245783fb1b4275 100644 --- a/test/parallel/test-crypto-authenticated.js +++ b/test/parallel/test-crypto-authenticated.js @@ -324,7 +324,8 @@ for (const i in TEST_CASES) { { const encrypt = crypto.createCipheriv(test.algo, - Buffer.from(test.key, 'hex'), Buffer.from(test.iv, 'hex')); + Buffer.from(test.key, 'hex'), + Buffer.from(test.iv, 'hex')); if (test.aad) encrypt.setAAD(Buffer.from(test.aad, 'hex')); @@ -342,7 +343,8 @@ for (const i in TEST_CASES) { { const decrypt = crypto.createDecipheriv(test.algo, - Buffer.from(test.key, 'hex'), Buffer.from(test.iv, 'hex')); + Buffer.from(test.key, 'hex'), + Buffer.from(test.iv, 'hex')); decrypt.setAuthTag(Buffer.from(test.tag, 'hex')); if (test.aad) decrypt.setAAD(Buffer.from(test.aad, 'hex')); @@ -401,7 +403,8 @@ for (const i in TEST_CASES) { { // trying to get tag before inputting all data: const encrypt = crypto.createCipheriv(test.algo, - Buffer.from(test.key, 'hex'), Buffer.from(test.iv, 'hex')); + Buffer.from(test.key, 'hex'), + Buffer.from(test.iv, 'hex')); encrypt.update('blah', 'ascii'); assert.throws(function() { encrypt.getAuthTag(); }, / state/); } @@ -409,7 +412,8 @@ for (const i in TEST_CASES) { { // trying to set tag on encryption object: const encrypt = crypto.createCipheriv(test.algo, - Buffer.from(test.key, 'hex'), Buffer.from(test.iv, 'hex')); + Buffer.from(test.key, 'hex'), + Buffer.from(test.iv, 'hex')); assert.throws(() => { encrypt.setAuthTag(Buffer.from(test.tag, 'hex')); }, / state/); } @@ -417,7 +421,8 @@ for (const i in TEST_CASES) { { // trying to read tag from decryption object: const decrypt = crypto.createDecipheriv(test.algo, - Buffer.from(test.key, 'hex'), Buffer.from(test.iv, 'hex')); + Buffer.from(test.key, 'hex'), + Buffer.from(test.iv, 'hex')); assert.throws(function() { decrypt.getAuthTag(); }, / state/); } diff --git a/test/parallel/test-crypto-hash.js b/test/parallel/test-crypto-hash.js index 9e212443453203..79353ede3b49dc 100644 --- a/test/parallel/test-crypto-hash.js +++ b/test/parallel/test-crypto-hash.js @@ -109,9 +109,9 @@ h3.digest(); assert.throws(function() { h3.digest(); }, - /Digest already called/); + /Digest already called/); assert.throws(function() { h3.update('foo'); }, - /Digest already called/); + /Digest already called/); diff --git a/test/parallel/test-crypto-hmac.js b/test/parallel/test-crypto-hmac.js index da532d7657cb61..eeb8cd152567f8 100644 --- a/test/parallel/test-crypto-hmac.js +++ b/test/parallel/test-crypto-hmac.js @@ -123,7 +123,7 @@ var rfc4231 = [ key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'), data: Buffer.from('ddddddddddddddddddddddddddddddddddddddddddddddddd' + 'ddddddddddddddddddddddddddddddddddddddddddddddddddd', - 'hex'), + 'hex'), hmac: { sha224: '7fb3cb3588c6c1f6ffa9694d7d6ad2649365b0c1f65d69d1ec8333ea', sha256: @@ -140,10 +140,10 @@ var rfc4231 = [ }, { key: Buffer.from('0102030405060708090a0b0c0d0e0f10111213141516171819', - 'hex'), + 'hex'), data: Buffer.from('cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdc' + 'dcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd', - 'hex'), + 'hex'), hmac: { sha224: '6c11506874013cac6a2abc1bb382627cec6a90d86efc012de7afec5a', sha256: @@ -264,16 +264,16 @@ var rfc2202_md5 = [ key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'), data: Buffer.from('ddddddddddddddddddddddddddddddddddddddddddddddddd' + 'ddddddddddddddddddddddddddddddddddddddddddddddddddd', - 'hex'), + 'hex'), hmac: '56be34521d144c88dbb8c733f0e8b3f6' }, { key: Buffer.from('0102030405060708090a0b0c0d0e0f10111213141516171819', - 'hex'), + 'hex'), data: Buffer.from('cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdc' + 'dcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd' + 'cdcdcdcdcd', - 'hex'), + 'hex'), hmac: '697eaf0aca3a3aea3a75164746ffaa79' }, { @@ -286,7 +286,7 @@ var rfc2202_md5 = [ 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaa', - 'hex'), + 'hex'), data: 'Test Using Larger Than Block-Size Key - Hash Key First', hmac: '6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd' }, @@ -295,7 +295,7 @@ var rfc2202_md5 = [ 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaa', - 'hex'), + 'hex'), data: 'Test Using Larger Than Block-Size Key and Larger Than One ' + 'Block-Size Data', @@ -318,16 +318,16 @@ var rfc2202_sha1 = [ data: Buffer.from('ddddddddddddddddddddddddddddddddddddddddddddd' + 'ddddddddddddddddddddddddddddddddddddddddddddd' + 'dddddddddd', - 'hex'), + 'hex'), hmac: '125d7342b9ac11cd91a39af48aa17b4f63f175d3' }, { key: Buffer.from('0102030405060708090a0b0c0d0e0f10111213141516171819', - 'hex'), + 'hex'), data: Buffer.from('cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdc' + 'dcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd' + 'cdcdcdcdcd', - 'hex'), + 'hex'), hmac: '4c9007f4026250c6bc8414f9bf50c86c2d7235da' }, { @@ -340,7 +340,7 @@ var rfc2202_sha1 = [ 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaa', - 'hex'), + 'hex'), data: 'Test Using Larger Than Block-Size Key - Hash Key First', hmac: 'aa4ae5e15272d00e95705637ce8a3b55ed402112' }, @@ -349,7 +349,7 @@ var rfc2202_sha1 = [ 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaa', - 'hex'), + 'hex'), data: 'Test Using Larger Than Block-Size Key and Larger Than One ' + 'Block-Size Data', diff --git a/test/parallel/test-crypto-rsa-dsa.js b/test/parallel/test-crypto-rsa-dsa.js index 396717ef742a95..118117547cae32 100644 --- a/test/parallel/test-crypto-rsa-dsa.js +++ b/test/parallel/test-crypto-rsa-dsa.js @@ -14,15 +14,15 @@ var crypto = require('crypto'); var certPem = fs.readFileSync(common.fixturesDir + '/test_cert.pem', 'ascii'); var keyPem = fs.readFileSync(common.fixturesDir + '/test_key.pem', 'ascii'); var rsaPubPem = fs.readFileSync(common.fixturesDir + '/test_rsa_pubkey.pem', - 'ascii'); + 'ascii'); var rsaKeyPem = fs.readFileSync(common.fixturesDir + '/test_rsa_privkey.pem', - 'ascii'); + 'ascii'); var rsaKeyPemEncrypted = fs.readFileSync( common.fixturesDir + '/test_rsa_privkey_encrypted.pem', 'ascii'); var dsaPubPem = fs.readFileSync(common.fixturesDir + '/test_dsa_pubkey.pem', - 'ascii'); + 'ascii'); var dsaKeyPem = fs.readFileSync(common.fixturesDir + '/test_dsa_privkey.pem', - 'ascii'); + 'ascii'); var dsaKeyPemEncrypted = fs.readFileSync( common.fixturesDir + '/test_dsa_privkey_encrypted.pem', 'ascii'); diff --git a/test/parallel/test-dns.js b/test/parallel/test-dns.js index 9ee2e9f974f625..27b9b81d7d14a2 100644 --- a/test/parallel/test-dns.js +++ b/test/parallel/test-dns.js @@ -112,7 +112,7 @@ assert.doesNotThrow(() => dns.lookup(NaN, noop)); */ assert.throws(() => { dns.lookup('www.google.com', { hints: (dns.V4MAPPED | dns.ADDRCONFIG) + 1 }, - noop); + noop); }, /^TypeError: Invalid argument: hints must use valid flags$/); assert.throws(() => dns.lookup('www.google.com'), diff --git a/test/parallel/test-domain-throw-error-then-throw-from-uncaught-exception-handler.js b/test/parallel/test-domain-throw-error-then-throw-from-uncaught-exception-handler.js index fc6a93ccdca8ef..a45f7d17a83a2c 100644 --- a/test/parallel/test-domain-throw-error-then-throw-from-uncaught-exception-handler.js +++ b/test/parallel/test-domain-throw-error-then-throw-from-uncaught-exception-handler.js @@ -49,22 +49,23 @@ if (process.argv[2] === 'child') { } function runTestWithoutAbortOnUncaughtException() { - child_process.exec(createTestCmdLine(), - function onTestDone(err, stdout, stderr) { - // When _not_ passing --abort-on-uncaught-exception, the process' - // uncaughtException handler _must_ be called, and thus the error - // message must include only the message of the error thrown from the - // process' uncaughtException handler. - assert(stderr.includes(uncaughtExceptionHandlerErrMsg), - 'stderr output must include proper uncaughtException ' + - 'handler\'s error\'s message'); - assert(!stderr.includes(domainErrMsg), 'stderr output must not ' + - 'include domain\'s error\'s message'); - - assert.notEqual(err.code, 0, - 'child process should have exited with a non-zero ' + - 'exit code, but did not'); - }); + child_process.exec( + createTestCmdLine(), + function onTestDone(err, stdout, stderr) { + // When _not_ passing --abort-on-uncaught-exception, the process' + // uncaughtException handler _must_ be called, and thus the error + // message must include only the message of the error thrown from the + // process' uncaughtException handler. + assert(stderr.includes(uncaughtExceptionHandlerErrMsg), + 'stderr output must include proper uncaughtException ' + + 'handler\'s error\'s message'); + assert(!stderr.includes(domainErrMsg), + 'stderr output must not include domain\'s error\'s message'); + assert.notStrictEqual(err.code, 0, + 'child process should have exited with a ' + + 'non-zero exit code, but did not'); + } + ); } function runTestWithAbortOnUncaughtException() { diff --git a/test/parallel/test-fs-non-number-arguments-throw.js b/test/parallel/test-fs-non-number-arguments-throw.js index b13041ca3eecb6..3e40a5fd41be38 100644 --- a/test/parallel/test-fs-non-number-arguments-throw.js +++ b/test/parallel/test-fs-non-number-arguments-throw.js @@ -16,17 +16,17 @@ const saneEmitter = fs.createReadStream(tempFile, { start: 4, end: 6 }); assert.throws(function() { fs.createReadStream(tempFile, { start: '4', end: 6 }); }, /^TypeError: "start" option must be a Number$/, - "start as string didn't throw an error for createReadStream"); + "start as string didn't throw an error for createReadStream"); assert.throws(function() { fs.createReadStream(tempFile, { start: 4, end: '6' }); }, /^TypeError: "end" option must be a Number$/, - "end as string didn't throw an error for createReadStream"); + "end as string didn't throw an error for createReadStream"); assert.throws(function() { fs.createWriteStream(tempFile, { start: '4' }); }, /^TypeError: "start" option must be a Number$/, - "start as string didn't throw an error for createWriteStream"); + "start as string didn't throw an error for createWriteStream"); saneEmitter.on('data', common.mustCall(function(data) { assert.strictEqual(sanity, data.toString('utf8'), 'read ' + diff --git a/test/parallel/test-fs-realpath.js b/test/parallel/test-fs-realpath.js index 5f2fae26ec8d4a..986e2089b44ab9 100644 --- a/test/parallel/test-fs-realpath.js +++ b/test/parallel/test-fs-realpath.js @@ -137,13 +137,13 @@ function test_deep_relative_file_symlink(callback) { .relative(path.join(targetsAbsDir, 'nested-index', 'one'), expected); const linkPath1 = path.join(targetsAbsDir, - 'nested-index', 'one', 'symlink1.js'); + 'nested-index', 'one', 'symlink1.js'); try { fs.unlinkSync(linkPath1); } catch (e) {} fs.symlinkSync(linkData1, linkPath1, 'file'); const linkData2 = '../one/symlink1.js'; const entry = path.join(targetsAbsDir, - 'nested-index', 'two', 'symlink1-b.js'); + 'nested-index', 'two', 'symlink1-b.js'); try { fs.unlinkSync(entry); } catch (e) {} fs.symlinkSync(linkData2, entry, 'file'); unlink.push(linkPath1); @@ -170,7 +170,7 @@ function test_deep_relative_dir_symlink(callback) { const linkData2b = '../one/symlink1-dir'; const entry = path.join(targetsAbsDir, - 'nested-index', 'two', 'symlink12-dir'); + 'nested-index', 'two', 'symlink12-dir'); try { fs.unlinkSync(entry); } catch (e) {} fs.symlinkSync(linkData2b, entry, 'dir'); unlink.push(linkPath1b); @@ -237,7 +237,7 @@ function test_relative_input_cwd(callback) { // we need to calculate the relative path to the tmp dir from cwd const entrydir = process.cwd(); const entry = path.relative(entrydir, - path.join(common.tmpDir + '/cycles/realpath-3a')); + path.join(common.tmpDir + '/cycles/realpath-3a')); const expected = common.tmpDir + '/cycles/root.js'; [ [entry, '../cycles/realpath-3b'], @@ -292,14 +292,14 @@ function test_deep_symlink_mix(callback) { [ [entry, common.tmpDir + '/node-test-realpath-d1/foo'], [tmp('node-test-realpath-d1'), - common.tmpDir + '/node-test-realpath-d2'], + common.tmpDir + '/node-test-realpath-d2'], [tmp('node-test-realpath-d2/foo'), '../node-test-realpath-f2'], [tmp('node-test-realpath-f2'), targetsAbsDir + '/nested-index/one/realpath-c'], [targetsAbsDir + '/nested-index/one/realpath-c', targetsAbsDir + '/nested-index/two/realpath-c'], [targetsAbsDir + '/nested-index/two/realpath-c', - common.tmpDir + '/cycles/root.js'] + common.tmpDir + '/cycles/root.js'] ].forEach(function(t) { try { fs.unlinkSync(t[0]); } catch (e) {} fs.symlinkSync(t[1], t[0]); @@ -361,7 +361,7 @@ function test_up_multiple(cb) { } function cleanup() { ['a/b', - 'a' + 'a' ].forEach(function(folder) { try { fs.rmdirSync(tmp(folder)); } catch (ex) {} }); @@ -418,14 +418,14 @@ function test_abs_with_kids(cb) { const root = tmpAbsDir + '/node-test-realpath-abs-kids'; function cleanup() { ['/a/b/c/x.txt', - '/a/link' + '/a/link' ].forEach(function(file) { try { fs.unlinkSync(root + file); } catch (ex) {} }); ['/a/b/c', - '/a/b', - '/a', - '' + '/a/b', + '/a', + '' ].forEach(function(folder) { try { fs.rmdirSync(root + folder); } catch (ex) {} }); @@ -433,9 +433,9 @@ function test_abs_with_kids(cb) { function setup() { cleanup(); ['', - '/a', - '/a/b', - '/a/b/c' + '/a', + '/a/b', + '/a/b/c' ].forEach(function(folder) { console.log('mkdir ' + root + folder); fs.mkdirSync(root + folder, 0o700); diff --git a/test/parallel/test-http-double-content-length.js b/test/parallel/test-http-double-content-length.js index a73cf49854ed35..f6c13becfd83dd 100644 --- a/test/parallel/test-http-double-content-length.js +++ b/test/parallel/test-http-double-content-length.js @@ -22,9 +22,9 @@ server.listen(0, () => { port: server.address().port, // Send two content-length header values. headers: {'Content-Length': [1, 2]}}, - (res) => { - common.fail('an error should have occurred'); - } + (res) => { + common.fail('an error should have occurred'); + } ); req.on('error', common.mustCall(() => { server.close(); diff --git a/test/parallel/test-http-localaddress.js b/test/parallel/test-http-localaddress.js index fd38f8a901fe81..d507d12ec89e25 100644 --- a/test/parallel/test-http-localaddress.js +++ b/test/parallel/test-http-localaddress.js @@ -21,10 +21,10 @@ var server = http.createServer(function(req, res) { server.listen(0, '127.0.0.1', function() { var options = { host: 'localhost', - port: this.address().port, - path: '/', - method: 'GET', - localAddress: '127.0.0.2' }; + port: this.address().port, + path: '/', + method: 'GET', + localAddress: '127.0.0.2' }; var req = http.request(options, function(res) { res.on('end', function() { diff --git a/test/parallel/test-http-proxy.js b/test/parallel/test-http-proxy.js index 43feb1e3b3838c..48367caaa7d89e 100644 --- a/test/parallel/test-http-proxy.js +++ b/test/parallel/test-http-proxy.js @@ -10,8 +10,8 @@ var cookies = [ ]; var headers = {'content-type': 'text/plain', - 'set-cookie': cookies, - 'hello': 'world' }; + 'set-cookie': cookies, + 'hello': 'world' }; var backend = http.createServer(function(req, res) { console.error('backend request'); diff --git a/test/parallel/test-os.js b/test/parallel/test-os.js index 5a0a9f6ad14cbc..ce0d2ee054d1f9 100644 --- a/test/parallel/test-os.js +++ b/test/parallel/test-os.js @@ -107,8 +107,8 @@ switch (platform) { const filter = function(e) { return e.address === '127.0.0.1'; }; const actual = interfaces.lo.filter(filter); const expected = [{ address: '127.0.0.1', netmask: '255.0.0.0', - mac: '00:00:00:00:00:00', family: 'IPv4', - internal: true }]; + mac: '00:00:00:00:00:00', family: 'IPv4', + internal: true }]; assert.deepStrictEqual(actual, expected); break; } @@ -117,8 +117,8 @@ switch (platform) { const filter = function(e) { return e.address === '127.0.0.1'; }; const actual = interfaces['Loopback Pseudo-Interface 1'].filter(filter); const expected = [{ address: '127.0.0.1', netmask: '255.0.0.0', - mac: '00:00:00:00:00:00', family: 'IPv4', - internal: true }]; + mac: '00:00:00:00:00:00', family: 'IPv4', + internal: true }]; assert.deepStrictEqual(actual, expected); break; } diff --git a/test/parallel/test-preload.js b/test/parallel/test-preload.js index 3fbdac9c4d363b..bf3c4a09cf5600 100644 --- a/test/parallel/test-preload.js +++ b/test/parallel/test-preload.js @@ -32,43 +32,41 @@ const fixtureD = fixture('define-global.js'); const fixtureThrows = fixture('throws_error4.js'); // test preloading a single module works -childProcess.exec(nodeBinary + ' ' + - preloadOption([fixtureA]) + ' ' + - fixtureB, - function(err, stdout, stderr) { - assert.ifError(err); - assert.strictEqual(stdout, 'A\nB\n'); - }); +childProcess.exec(nodeBinary + ' ' + preloadOption([fixtureA]) + ' ' + fixtureB, + function(err, stdout, stderr) { + if (err) throw err; + assert.strictEqual(stdout, 'A\nB\n'); + }); // test preloading multiple modules works -childProcess.exec(nodeBinary + ' ' + - preloadOption([fixtureA, fixtureB]) + ' ' + - fixtureC, +childProcess.exec( + nodeBinary + ' ' + preloadOption([fixtureA, fixtureB]) + ' ' + fixtureC, function(err, stdout, stderr) { - assert.ifError(err); + if (err) throw err; assert.strictEqual(stdout, 'A\nB\nC\n'); - }); + } +); // test that preloading a throwing module aborts -childProcess.exec(nodeBinary + ' ' + - preloadOption([fixtureA, fixtureThrows]) + ' ' + - fixtureB, +childProcess.exec( + nodeBinary + ' ' + preloadOption([fixtureA, fixtureThrows]) + ' ' + fixtureB, function(err, stdout, stderr) { if (err) { assert.strictEqual(stdout, 'A\n'); } else { throw new Error('Preload should have failed'); } - }); + } +); // test that preload can be used with --eval -childProcess.exec(nodeBinary + ' ' + - preloadOption([fixtureA]) + - '-e "console.log(\'hello\');"', +childProcess.exec( + nodeBinary + ' ' + preloadOption([fixtureA]) + '-e "console.log(\'hello\');"', function(err, stdout, stderr) { - assert.ifError(err); + if (err) throw err; assert.strictEqual(stdout, 'A\nhello\n'); - }); + } +); // test that preload can be used with stdin const stdinProc = childProcess.spawn( @@ -108,42 +106,43 @@ replProc.on('close', function(code) { // test that preload placement at other points in the cmdline // also test that duplicated preload only gets loaded once -childProcess.exec(nodeBinary + ' ' + - preloadOption([fixtureA]) + - '-e "console.log(\'hello\');" ' + - preloadOption([fixtureA, fixtureB]), +childProcess.exec( + nodeBinary + ' ' + preloadOption([fixtureA]) + + '-e "console.log(\'hello\');" ' + preloadOption([fixtureA, fixtureB]), function(err, stdout, stderr) { - assert.ifError(err); + if (err) throw err; assert.strictEqual(stdout, 'A\nB\nhello\n'); - }); + } +); // test that preload works with -i -const interactive = childProcess.exec(nodeBinary + ' ' + - preloadOption([fixtureD]) + - '-i', +const interactive = childProcess.exec( + nodeBinary + ' ' + preloadOption([fixtureD]) + '-i', common.mustCall(function(err, stdout, stderr) { assert.ifError(err); assert.strictEqual(stdout, "> 'test'\n> "); - })); + }) +); interactive.stdin.write('a\n'); interactive.stdin.write('process.exit()\n'); -childProcess.exec(nodeBinary + ' ' + - '--require ' + fixture('cluster-preload.js') + ' ' + - fixture('cluster-preload-test.js'), +childProcess.exec( + nodeBinary + ' ' + '--require ' + fixture('cluster-preload.js') + ' ' + + fixture('cluster-preload-test.js'), function(err, stdout, stderr) { - assert.ifError(err); + if (err) throw err; assert.ok(/worker terminated with code 43/.test(stdout)); - }); + } +); // https://github.com/nodejs/node/issues/1691 process.chdir(common.fixturesDir); -childProcess.exec(nodeBinary + ' ' + - '--expose_debug_as=v8debug ' + - '--require ' + fixture('cluster-preload.js') + ' ' + - 'cluster-preload-test.js', +childProcess.exec( + nodeBinary + ' ' + '--expose_debug_as=v8debug ' + '--require ' + + fixture('cluster-preload.js') + ' ' + 'cluster-preload-test.js', function(err, stdout, stderr) { - assert.ifError(err); + if (err) throw err; assert.ok(/worker terminated with code 43/.test(stdout)); - }); + } +); diff --git a/test/parallel/test-punycode.js b/test/parallel/test-punycode.js index 2918202326bf98..60175557042ff9 100644 --- a/test/parallel/test-punycode.js +++ b/test/parallel/test-punycode.js @@ -6,17 +6,23 @@ const assert = require('assert'); assert.strictEqual(punycode.encode('ü'), 'tda'); assert.strictEqual(punycode.encode('Goethe'), 'Goethe-'); assert.strictEqual(punycode.encode('Bücher'), 'Bcher-kva'); -assert.strictEqual(punycode.encode( - 'Willst du die Blüthe des frühen, die Früchte des späteren Jahres'), - 'Willst du die Blthe des frhen, die Frchte des spteren Jahres-x9e96lkal'); +assert.strictEqual( + punycode.encode( + 'Willst du die Blüthe des frühen, die Früchte des späteren Jahres' + ), + 'Willst du die Blthe des frhen, die Frchte des spteren Jahres-x9e96lkal' +); assert.strictEqual(punycode.encode('日本語'), 'wgv71a119e'); assert.strictEqual(punycode.decode('tda'), 'ü'); assert.strictEqual(punycode.decode('Goethe-'), 'Goethe'); assert.strictEqual(punycode.decode('Bcher-kva'), 'Bücher'); -assert.strictEqual(punycode.decode( - 'Willst du die Blthe des frhen, die Frchte des spteren Jahres-x9e96lkal'), - 'Willst du die Blüthe des frühen, die Früchte des späteren Jahres'); +assert.strictEqual( + punycode.decode( + 'Willst du die Blthe des frhen, die Frchte des spteren Jahres-x9e96lkal' + ), + 'Willst du die Blüthe des frühen, die Früchte des späteren Jahres' +); assert.strictEqual(punycode.decode('wgv71a119e'), '日本語'); assert.throws(() => { punycode.decode(' '); diff --git a/test/parallel/test-querystring.js b/test/parallel/test-querystring.js index 37cf66705d56d7..ced2b3a3e6d9c3 100644 --- a/test/parallel/test-querystring.js +++ b/test/parallel/test-querystring.js @@ -44,11 +44,11 @@ var qsTestCases = [ ['foo=%EF%BF%BD', 'foo=%EF%BF%BD', {'foo': '\ufffd' }], // See: https://github.com/joyent/node/issues/1707 ['hasOwnProperty=x&toString=foo&valueOf=bar&__defineGetter__=baz', - 'hasOwnProperty=x&toString=foo&valueOf=bar&__defineGetter__=baz', - { hasOwnProperty: 'x', - toString: 'foo', - valueOf: 'bar', - __defineGetter__: 'baz' }], + 'hasOwnProperty=x&toString=foo&valueOf=bar&__defineGetter__=baz', + { hasOwnProperty: 'x', + toString: 'foo', + valueOf: 'bar', + __defineGetter__: 'baz' }], // See: https://github.com/joyent/node/issues/3058 ['foo&bar=baz', 'foo=&bar=baz', { foo: '', bar: 'baz' }], [null, '', {}], diff --git a/test/parallel/test-readline-interface.js b/test/parallel/test-readline-interface.js index 59b75cd0a86231..509995bc9ad619 100644 --- a/test/parallel/test-readline-interface.js +++ b/test/parallel/test-readline-interface.js @@ -62,7 +62,7 @@ function isWarned(emitter) { // disable history fi = new FakeInput(); rli = new readline.Interface({ input: fi, output: fi, terminal: terminal, - historySize: 0 }); + historySize: 0 }); assert.strictEqual(rli.historySize, 0); fi.emit('data', 'asdf\n'); diff --git a/test/parallel/test-repl-tab-complete.js b/test/parallel/test-repl-tab-complete.js index add8eea730ae72..4e05714ab5fc56 100644 --- a/test/parallel/test-repl-tab-complete.js +++ b/test/parallel/test-repl-tab-complete.js @@ -291,7 +291,7 @@ const testNonGlobal = repl.start({ }); const builtins = [['Infinity', '', 'Int16Array', 'Int32Array', - 'Int8Array'], 'I']; + 'Int8Array'], 'I']; if (common.hasIntl) { builtins[0].push('Intl'); diff --git a/test/parallel/test-require-symlink.js b/test/parallel/test-require-symlink.js index 0792bc13bb70a7..4e74606bedeed6 100644 --- a/test/parallel/test-require-symlink.js +++ b/test/parallel/test-require-symlink.js @@ -11,13 +11,15 @@ const util = require('util'); common.refreshTmpDir(); const linkTarget = path.join(common.fixturesDir, - '/module-require-symlink/node_modules/dep2/'); + '/module-require-symlink/node_modules/dep2/'); -const linkDir = path.join(common.fixturesDir, - '/module-require-symlink/node_modules/dep1/node_modules/dep2'); +const linkDir = path.join( + common.fixturesDir, + '/module-require-symlink/node_modules/dep1/node_modules/dep2' +); const linkScriptTarget = path.join(common.fixturesDir, - '/module-require-symlink/symlinked.js'); + '/module-require-symlink/symlinked.js'); const linkScript = path.join(common.tmpDir, 'module-require-symlink.js'); diff --git a/test/parallel/test-spawn-cmd-named-pipe.js b/test/parallel/test-spawn-cmd-named-pipe.js index c463bf6140053f..b4264880165d39 100644 --- a/test/parallel/test-spawn-cmd-named-pipe.js +++ b/test/parallel/test-spawn-cmd-named-pipe.js @@ -43,7 +43,7 @@ if (!process.argv[2]) { } const args = ['/c', process.execPath, __filename, 'child', - '<', stdinPipeName, '>', stdoutPipeName]; + '<', stdinPipeName, '>', stdoutPipeName]; const child = spawn(comspec, args); diff --git a/test/parallel/test-tls-client-verify.js b/test/parallel/test-tls-client-verify.js index 983d88296eb26f..a1fa35acf3c124 100644 --- a/test/parallel/test-tls-client-verify.js +++ b/test/parallel/test-tls-client-verify.js @@ -12,36 +12,36 @@ const fs = require('fs'); const hosterr = /Hostname\/IP doesn't match certificate's altnames/g; const testCases = - [{ ca: ['ca1-cert'], - key: 'agent2-key', - cert: 'agent2-cert', - servers: [ + [{ ca: ['ca1-cert'], + key: 'agent2-key', + cert: 'agent2-cert', + servers: [ { ok: true, key: 'agent1-key', cert: 'agent1-cert' }, { ok: false, key: 'agent2-key', cert: 'agent2-cert' }, { ok: false, key: 'agent3-key', cert: 'agent3-cert' } - ] - }, + ] + }, - { ca: [], - key: 'agent2-key', - cert: 'agent2-cert', - servers: [ + { ca: [], + key: 'agent2-key', + cert: 'agent2-cert', + servers: [ { ok: false, key: 'agent1-key', cert: 'agent1-cert' }, { ok: false, key: 'agent2-key', cert: 'agent2-cert' }, { ok: false, key: 'agent3-key', cert: 'agent3-cert' } - ] - }, + ] + }, - { ca: ['ca1-cert', 'ca2-cert'], - key: 'agent2-key', - cert: 'agent2-cert', - servers: [ + { ca: ['ca1-cert', 'ca2-cert'], + key: 'agent2-key', + cert: 'agent2-cert', + servers: [ { ok: true, key: 'agent1-key', cert: 'agent1-cert' }, { ok: false, key: 'agent2-key', cert: 'agent2-cert' }, { ok: true, key: 'agent3-key', cert: 'agent3-cert' } - ] - } - ]; + ] + } + ]; function filenamePEM(n) { return require('path').join(common.fixturesDir, 'keys', n + '.pem'); diff --git a/test/parallel/test-tls-no-sslv3.js b/test/parallel/test-tls-no-sslv3.js index 16a722ef85b9da..fbc7a629611b0d 100644 --- a/test/parallel/test-tls-no-sslv3.js +++ b/test/parallel/test-tls-no-sslv3.js @@ -25,8 +25,8 @@ let stderr = ''; server.listen(0, '127.0.0.1', function() { const address = this.address().address + ':' + this.address().port; const args = ['s_client', - '-ssl3', - '-connect', address]; + '-ssl3', + '-connect', address]; // for the performance and stability issue in s_client on Windows if (common.isWindows) diff --git a/test/parallel/test-tls-server-failed-handshake-emits-clienterror.js b/test/parallel/test-tls-server-failed-handshake-emits-clienterror.js index bd92dc28904183..1ff7decf3cf9cc 100644 --- a/test/parallel/test-tls-server-failed-handshake-emits-clienterror.js +++ b/test/parallel/test-tls-server-failed-handshake-emits-clienterror.js @@ -23,7 +23,7 @@ const server = tls.createServer({}) 'Instance of Error should be passed to error handler'); assert.ok(e.message.match( /SSL routines:SSL23_GET_CLIENT_HELLO:unknown protocol/), - 'Expecting SSL unknown protocol'); + 'Expecting SSL unknown protocol'); server.close(); })); diff --git a/test/parallel/test-tls-server-verify.js b/test/parallel/test-tls-server-verify.js index 6850ddd7102e6b..58a58324fb383f 100644 --- a/test/parallel/test-tls-server-verify.js +++ b/test/parallel/test-tls-server-verify.js @@ -15,88 +15,88 @@ if (!common.opensslCli) { // - accepted and "authorized". const testCases = - [{ title: 'Do not request certs. Everyone is unauthorized.', - requestCert: false, - rejectUnauthorized: false, - renegotiate: false, - CAs: ['ca1-cert'], - clients: - [{ name: 'agent1', shouldReject: false, shouldAuth: false }, + [{ title: 'Do not request certs. Everyone is unauthorized.', + requestCert: false, + rejectUnauthorized: false, + renegotiate: false, + CAs: ['ca1-cert'], + clients: + [{ name: 'agent1', shouldReject: false, shouldAuth: false }, { name: 'agent2', shouldReject: false, shouldAuth: false }, { name: 'agent3', shouldReject: false, shouldAuth: false }, { name: 'nocert', shouldReject: false, shouldAuth: false } - ] - }, - - { title: 'Allow both authed and unauthed connections with CA1', - requestCert: true, - rejectUnauthorized: false, - renegotiate: false, - CAs: ['ca1-cert'], - clients: - [{ name: 'agent1', shouldReject: false, shouldAuth: true }, + ] + }, + + { title: 'Allow both authed and unauthed connections with CA1', + requestCert: true, + rejectUnauthorized: false, + renegotiate: false, + CAs: ['ca1-cert'], + clients: + [{ name: 'agent1', shouldReject: false, shouldAuth: true }, { name: 'agent2', shouldReject: false, shouldAuth: false }, { name: 'agent3', shouldReject: false, shouldAuth: false }, { name: 'nocert', shouldReject: false, shouldAuth: false } - ] - }, - - { title: 'Do not request certs at connection. Do that later', - requestCert: false, - rejectUnauthorized: false, - renegotiate: true, - CAs: ['ca1-cert'], - clients: - [{ name: 'agent1', shouldReject: false, shouldAuth: true }, + ] + }, + + { title: 'Do not request certs at connection. Do that later', + requestCert: false, + rejectUnauthorized: false, + renegotiate: true, + CAs: ['ca1-cert'], + clients: + [{ name: 'agent1', shouldReject: false, shouldAuth: true }, { name: 'agent2', shouldReject: false, shouldAuth: false }, { name: 'agent3', shouldReject: false, shouldAuth: false }, { name: 'nocert', shouldReject: false, shouldAuth: false } - ] - }, - - { title: 'Allow only authed connections with CA1', - requestCert: true, - rejectUnauthorized: true, - renegotiate: false, - CAs: ['ca1-cert'], - clients: - [{ name: 'agent1', shouldReject: false, shouldAuth: true }, + ] + }, + + { title: 'Allow only authed connections with CA1', + requestCert: true, + rejectUnauthorized: true, + renegotiate: false, + CAs: ['ca1-cert'], + clients: + [{ name: 'agent1', shouldReject: false, shouldAuth: true }, { name: 'agent2', shouldReject: true }, { name: 'agent3', shouldReject: true }, { name: 'nocert', shouldReject: true } - ] - }, - - { title: 'Allow only authed connections with CA1 and CA2', - requestCert: true, - rejectUnauthorized: true, - renegotiate: false, - CAs: ['ca1-cert', 'ca2-cert'], - clients: - [{ name: 'agent1', shouldReject: false, shouldAuth: true }, + ] + }, + + { title: 'Allow only authed connections with CA1 and CA2', + requestCert: true, + rejectUnauthorized: true, + renegotiate: false, + CAs: ['ca1-cert', 'ca2-cert'], + clients: + [{ name: 'agent1', shouldReject: false, shouldAuth: true }, { name: 'agent2', shouldReject: true }, { name: 'agent3', shouldReject: false, shouldAuth: true }, { name: 'nocert', shouldReject: true } - ] - }, + ] + }, - { title: 'Allow only certs signed by CA2 but not in the CRL', - requestCert: true, - rejectUnauthorized: true, - renegotiate: false, - CAs: ['ca2-cert'], - crl: 'ca2-crl', - clients: [ + { title: 'Allow only certs signed by CA2 but not in the CRL', + requestCert: true, + rejectUnauthorized: true, + renegotiate: false, + CAs: ['ca2-cert'], + crl: 'ca2-crl', + clients: [ { name: 'agent1', shouldReject: true, shouldAuth: false }, { name: 'agent2', shouldReject: true, shouldAuth: false }, { name: 'agent3', shouldReject: false, shouldAuth: true }, // Agent4 has a cert in the CRL. { name: 'agent4', shouldReject: true, shouldAuth: false }, { name: 'nocert', shouldReject: true } - ] - } - ]; + ] + } + ]; if (!common.hasCrypto) { common.skip('missing crypto'); diff --git a/test/parallel/test-tls-socket-failed-handshake-emits-error.js b/test/parallel/test-tls-socket-failed-handshake-emits-error.js index f655dc97b5a99b..ffeb42c8ebd8da 100644 --- a/test/parallel/test-tls-socket-failed-handshake-emits-error.js +++ b/test/parallel/test-tls-socket-failed-handshake-emits-error.js @@ -23,7 +23,7 @@ const server = net.createServer(function(c) { 'Instance of Error should be passed to error handler'); assert.ok(e.message.match( /SSL routines:SSL23_GET_CLIENT_HELLO:unknown protocol/), - 'Expecting SSL unknown protocol'); + 'Expecting SSL unknown protocol'); })); s.on('close', function() { diff --git a/test/parallel/test-util-inspect.js b/test/parallel/test-util-inspect.js index 1118065f1a09da..b0f89333d25a9b 100644 --- a/test/parallel/test-util-inspect.js +++ b/test/parallel/test-util-inspect.js @@ -42,7 +42,7 @@ assert.strictEqual(util.inspect({'a': {'b': { 'c': 2}}}, false, 1), '{ a: { b: [Object] } }'); assert.strictEqual(util.inspect(Object.create({}, {visible: {value: 1, enumerable: true}, hidden: {value: 2}})), - '{ visible: 1 }' + '{ visible: 1 }' ); { @@ -206,8 +206,9 @@ for (const showHidden of [true, false]) { // Objects without prototype { const out = util.inspect(Object.create(null, - { name: {value: 'Tim', enumerable: true}, - hidden: {value: 'secret'}}), true); + { name: {value: 'Tim', + enumerable: true}, + hidden: {value: 'secret'}}), true); if (out !== "{ [hidden]: 'secret', name: 'Tim' }" && out !== "{ name: 'Tim', [hidden]: 'secret' }") { common.fail(`unexpected value for out ${out}`); @@ -216,8 +217,8 @@ for (const showHidden of [true, false]) { assert.strictEqual( util.inspect(Object.create(null, - {name: {value: 'Tim', enumerable: true}, - hidden: {value: 'secret'}})), + {name: {value: 'Tim', enumerable: true}, + hidden: {value: 'secret'}})), '{ name: \'Tim\' }' ); diff --git a/test/parallel/test-util-sigint-watchdog.js b/test/parallel/test-util-sigint-watchdog.js index 42e4048bd74a36..207f44b011c3a2 100644 --- a/test/parallel/test-util-sigint-watchdog.js +++ b/test/parallel/test-util-sigint-watchdog.js @@ -16,41 +16,41 @@ if (common.isWindows) { assert.strictEqual(hadPendingSignals, false); next(); }, -(next) => { + (next) => { // Test with one call to the watchdog, one signal. - binding.startSigintWatchdog(); - process.kill(process.pid, 'SIGINT'); - waitForPendingSignal(common.mustCall(() => { - const hadPendingSignals = binding.stopSigintWatchdog(); - assert.strictEqual(hadPendingSignals, true); - next(); - })); -}, -(next) => { + binding.startSigintWatchdog(); + process.kill(process.pid, 'SIGINT'); + waitForPendingSignal(common.mustCall(() => { + const hadPendingSignals = binding.stopSigintWatchdog(); + assert.strictEqual(hadPendingSignals, true); + next(); + })); + }, + (next) => { // Nested calls are okay. - binding.startSigintWatchdog(); - binding.startSigintWatchdog(); - process.kill(process.pid, 'SIGINT'); - waitForPendingSignal(common.mustCall(() => { - const hadPendingSignals1 = binding.stopSigintWatchdog(); - const hadPendingSignals2 = binding.stopSigintWatchdog(); - assert.strictEqual(hadPendingSignals1, true); - assert.strictEqual(hadPendingSignals2, false); - next(); - })); -}, -() => { + binding.startSigintWatchdog(); + binding.startSigintWatchdog(); + process.kill(process.pid, 'SIGINT'); + waitForPendingSignal(common.mustCall(() => { + const hadPendingSignals1 = binding.stopSigintWatchdog(); + const hadPendingSignals2 = binding.stopSigintWatchdog(); + assert.strictEqual(hadPendingSignals1, true); + assert.strictEqual(hadPendingSignals2, false); + next(); + })); + }, + () => { // Signal comes in after first call to stop. - binding.startSigintWatchdog(); - binding.startSigintWatchdog(); - const hadPendingSignals1 = binding.stopSigintWatchdog(); - process.kill(process.pid, 'SIGINT'); - waitForPendingSignal(common.mustCall(() => { - const hadPendingSignals2 = binding.stopSigintWatchdog(); - assert.strictEqual(hadPendingSignals1, false); - assert.strictEqual(hadPendingSignals2, true); - })); -}].reduceRight((a, b) => common.mustCall(b).bind(null, a))(); + binding.startSigintWatchdog(); + binding.startSigintWatchdog(); + const hadPendingSignals1 = binding.stopSigintWatchdog(); + process.kill(process.pid, 'SIGINT'); + waitForPendingSignal(common.mustCall(() => { + const hadPendingSignals2 = binding.stopSigintWatchdog(); + assert.strictEqual(hadPendingSignals1, false); + assert.strictEqual(hadPendingSignals2, true); + })); + }].reduceRight((a, b) => common.mustCall(b).bind(null, a))(); function waitForPendingSignal(cb) { if (binding.watchdogHasPendingSigint()) diff --git a/test/parallel/test-whatwg-url-properties.js b/test/parallel/test-whatwg-url-properties.js index 60cf581ad8da4d..340a51525e33bf 100644 --- a/test/parallel/test-whatwg-url-properties.js +++ b/test/parallel/test-whatwg-url-properties.js @@ -19,9 +19,9 @@ for (const prop in url) { // https://heycam.github.io/webidl/#es-attributes // https://heycam.github.io/webidl/#es-stringifier const expected = ['toString', - 'href', 'origin', 'protocol', - 'username', 'password', 'host', 'hostname', 'port', - 'pathname', 'search', 'searchParams', 'hash']; + 'href', 'origin', 'protocol', + 'username', 'password', 'host', 'hostname', 'port', + 'pathname', 'search', 'searchParams', 'hash']; assert.deepStrictEqual(props, expected); diff --git a/test/parallel/test-zerolengthbufferbug.js b/test/parallel/test-zerolengthbufferbug.js index 9e2cde6b2fadae..056fc725ff5593 100644 --- a/test/parallel/test-zerolengthbufferbug.js +++ b/test/parallel/test-zerolengthbufferbug.js @@ -8,7 +8,7 @@ var server = http.createServer(function(req, res) { var buffer = Buffer.alloc(0); // FIXME: WTF gjslint want this? res.writeHead(200, {'Content-Type': 'text/html', - 'Content-Length': buffer.length}); + 'Content-Length': buffer.length}); res.end(buffer); }); diff --git a/test/parallel/test-zlib-invalid-input.js b/test/parallel/test-zlib-invalid-input.js index ee2ee85d73ff09..eb9cd334c11b84 100644 --- a/test/parallel/test-zlib-invalid-input.js +++ b/test/parallel/test-zlib-invalid-input.js @@ -21,9 +21,9 @@ nonStringInputs.forEach(function(input) { console.error('Doing the unzips'); // zlib.Unzip classes need to get valid data, or else they'll throw. const unzips = [ zlib.Unzip(), - zlib.Gunzip(), - zlib.Inflate(), - zlib.InflateRaw() ]; + zlib.Gunzip(), + zlib.Inflate(), + zlib.InflateRaw() ]; var hadError = []; unzips.forEach(function(uz, i) { console.error('Error for ' + uz.constructor.name); diff --git a/test/parallel/test-zlib.js b/test/parallel/test-zlib.js index ea158ded48b5c1..54a4bc473631a0 100644 --- a/test/parallel/test-zlib.js +++ b/test/parallel/test-zlib.js @@ -150,9 +150,9 @@ Object.keys(tests).forEach(function(file) { var Def = pair[0]; var Inf = pair[1]; var opts = { level: level, - windowBits: windowBits, - memLevel: memLevel, - strategy: strategy }; + windowBits: windowBits, + memLevel: memLevel, + strategy: strategy }; total++; diff --git a/test/sequential/test-crypto-timing-safe-equal.js b/test/sequential/test-crypto-timing-safe-equal.js index 9c4265a672cc0f..7a1f8d2993669b 100644 --- a/test/sequential/test-crypto-timing-safe-equal.js +++ b/test/sequential/test-crypto-timing-safe-equal.js @@ -24,14 +24,14 @@ assert.strictEqual( assert.throws(function() { crypto.timingSafeEqual(Buffer.from([1, 2, 3]), Buffer.from([1, 2])); }, /^TypeError: Input buffers must have the same length$/, - 'should throw when given buffers with different lengths'); + 'should throw when given buffers with different lengths'); assert.throws(function() { crypto.timingSafeEqual('not a buffer', Buffer.from([1, 2])); }, /^TypeError: First argument must be a buffer$/, - 'should throw if the first argument is not a buffer'); + 'should throw if the first argument is not a buffer'); assert.throws(function() { crypto.timingSafeEqual(Buffer.from([1, 2]), 'not a buffer'); }, /^TypeError: Second argument must be a buffer$/, - 'should throw if the second argument is not a buffer'); + 'should throw if the second argument is not a buffer'); From dd5a4e1d7560dcd50b66842b2b5b55b787c2873d Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Sat, 31 Dec 2016 21:40:59 -0800 Subject: [PATCH 168/291] tools: update ESLint to current version We have been stalled on ESLint 3.8.0 for some time. Current ESLint is 3.13.0. We have been unable to upgrade because of more aggressive reporting on some rules, including indentation. ESLint configuration options and bugfixes are now such that we can reasonably upgrade. PR-URL: https://github.com/nodejs/node/pull/10561 Reviewed-By: Teddy Katz Reviewed-By: James M Snell Reviewed-By: Sam Roberts --- .eslintrc | 6 +- tools/eslint/LICENSE | 2 +- tools/eslint/README.md | 7 +- tools/eslint/bin/eslint.js | 10 +- tools/eslint/conf/eslint.json | 14 +- tools/eslint/lib/ast-utils.js | 411 +- tools/eslint/lib/cli-engine.js | 30 +- .../code-path-analysis/code-path-analyzer.js | 31 +- .../code-path-analysis/code-path-segment.js | 279 +- .../lib/code-path-analysis/code-path-state.js | 131 +- .../lib/code-path-analysis/code-path.js | 93 +- .../lib/code-path-analysis/debug-helpers.js | 8 +- .../lib/code-path-analysis/fork-context.js | 93 +- .../lib/code-path-analysis/id-generator.js | 43 +- tools/eslint/lib/config.js | 236 +- tools/eslint/lib/config/autoconfig.js | 62 +- tools/eslint/lib/config/config-file.js | 12 +- tools/eslint/lib/config/config-initializer.js | 84 +- tools/eslint/lib/config/config-ops.js | 20 +- tools/eslint/lib/config/config-rule.js | 32 +- tools/eslint/lib/config/config-validator.js | 94 +- tools/eslint/lib/config/environments.js | 6 +- tools/eslint/lib/eslint.js | 102 +- tools/eslint/lib/file-finder.js | 130 +- tools/eslint/lib/formatters/checkstyle.js | 4 +- tools/eslint/lib/formatters/codeframe.js | 121 + tools/eslint/lib/formatters/compact.js | 4 +- tools/eslint/lib/formatters/html.js | 20 +- tools/eslint/lib/formatters/jslint-xml.js | 4 +- tools/eslint/lib/formatters/junit.js | 4 +- tools/eslint/lib/formatters/stylish.js | 10 +- tools/eslint/lib/formatters/table.js | 10 +- tools/eslint/lib/formatters/tap.js | 4 +- tools/eslint/lib/formatters/unix.js | 4 +- tools/eslint/lib/formatters/visualstudio.js | 4 +- tools/eslint/lib/ignored-paths.js | 247 +- .../internal-consistent-docs-description.js | 1 - .../internal-no-invalid-meta.js | 3 +- tools/eslint/lib/load-rules.js | 2 +- tools/eslint/lib/rule-context.js | 57 +- tools/eslint/lib/rules.js | 20 +- tools/eslint/lib/rules/accessor-pairs.js | 4 +- .../eslint/lib/rules/array-bracket-spacing.js | 6 +- tools/eslint/lib/rules/arrow-body-style.js | 98 +- tools/eslint/lib/rules/arrow-parens.js | 11 +- tools/eslint/lib/rules/block-scoped-var.js | 5 +- tools/eslint/lib/rules/block-spacing.js | 2 +- tools/eslint/lib/rules/brace-style.js | 82 +- tools/eslint/lib/rules/callback-return.js | 2 +- tools/eslint/lib/rules/camelcase.js | 7 +- .../eslint/lib/rules/capitalized-comments.js | 301 + tools/eslint/lib/rules/comma-dangle.js | 15 +- tools/eslint/lib/rules/comma-spacing.js | 4 +- tools/eslint/lib/rules/comma-style.js | 57 +- tools/eslint/lib/rules/complexity.js | 2 +- tools/eslint/lib/rules/consistent-return.js | 19 +- tools/eslint/lib/rules/consistent-this.js | 21 +- tools/eslint/lib/rules/constructor-super.js | 4 +- tools/eslint/lib/rules/curly.js | 19 +- tools/eslint/lib/rules/default-case.js | 8 +- tools/eslint/lib/rules/eqeqeq.js | 28 +- tools/eslint/lib/rules/func-call-spacing.js | 9 +- tools/eslint/lib/rules/func-name-matching.js | 77 +- tools/eslint/lib/rules/func-names.js | 31 +- tools/eslint/lib/rules/func-style.js | 6 +- .../lib/rules/generator-star-spacing.js | 4 +- tools/eslint/lib/rules/global-require.js | 12 +- tools/eslint/lib/rules/guard-for-in.js | 2 +- tools/eslint/lib/rules/handle-callback-err.js | 6 +- tools/eslint/lib/rules/id-blacklist.js | 4 +- tools/eslint/lib/rules/id-length.js | 10 +- tools/eslint/lib/rules/id-match.js | 4 +- tools/eslint/lib/rules/indent.js | 268 +- tools/eslint/lib/rules/jsx-quotes.js | 2 +- tools/eslint/lib/rules/key-spacing.js | 8 +- tools/eslint/lib/rules/keyword-spacing.js | 18 +- .../eslint/lib/rules/lines-around-comment.js | 16 +- .../lib/rules/lines-around-directive.js | 27 +- tools/eslint/lib/rules/max-depth.js | 3 +- tools/eslint/lib/rules/max-len.js | 32 +- tools/eslint/lib/rules/max-lines.js | 16 +- .../eslint/lib/rules/max-nested-callbacks.js | 4 +- tools/eslint/lib/rules/max-params.js | 4 +- tools/eslint/lib/rules/max-statements.js | 20 +- tools/eslint/lib/rules/new-cap.js | 2 +- tools/eslint/lib/rules/new-parens.js | 27 +- tools/eslint/lib/rules/newline-after-var.js | 63 +- .../eslint/lib/rules/newline-before-return.js | 6 +- tools/eslint/lib/rules/no-alert.js | 6 +- .../eslint/lib/rules/no-array-constructor.js | 2 +- tools/eslint/lib/rules/no-await-in-loop.js | 75 + tools/eslint/lib/rules/no-bitwise.js | 2 +- tools/eslint/lib/rules/no-caller.js | 2 +- tools/eslint/lib/rules/no-catch-shadow.js | 3 +- tools/eslint/lib/rules/no-class-assign.js | 7 +- tools/eslint/lib/rules/no-cond-assign.js | 4 +- tools/eslint/lib/rules/no-confusing-arrow.js | 4 +- tools/eslint/lib/rules/no-const-assign.js | 7 +- .../eslint/lib/rules/no-constant-condition.js | 2 +- tools/eslint/lib/rules/no-continue.js | 2 +- tools/eslint/lib/rules/no-control-regex.js | 4 +- tools/eslint/lib/rules/no-debugger.js | 2 +- tools/eslint/lib/rules/no-delete-var.js | 2 +- tools/eslint/lib/rules/no-div-regex.js | 2 +- tools/eslint/lib/rules/no-dupe-args.js | 2 +- .../eslint/lib/rules/no-dupe-class-members.js | 6 +- tools/eslint/lib/rules/no-dupe-keys.js | 4 +- tools/eslint/lib/rules/no-duplicate-case.js | 4 +- tools/eslint/lib/rules/no-else-return.js | 2 +- .../lib/rules/no-empty-character-class.js | 4 +- tools/eslint/lib/rules/no-empty-function.js | 2 +- tools/eslint/lib/rules/no-empty-pattern.js | 4 +- tools/eslint/lib/rules/no-empty.js | 4 +- tools/eslint/lib/rules/no-eq-null.js | 2 +- tools/eslint/lib/rules/no-eval.js | 2 +- tools/eslint/lib/rules/no-ex-assign.js | 6 +- tools/eslint/lib/rules/no-extend-native.js | 10 +- .../eslint/lib/rules/no-extra-boolean-cast.js | 17 +- tools/eslint/lib/rules/no-extra-label.js | 27 +- tools/eslint/lib/rules/no-extra-parens.js | 35 +- tools/eslint/lib/rules/no-fallthrough.js | 2 +- tools/eslint/lib/rules/no-func-assign.js | 7 +- tools/eslint/lib/rules/no-global-assign.js | 2 +- tools/eslint/lib/rules/no-implicit-globals.js | 12 +- tools/eslint/lib/rules/no-implied-eval.js | 4 +- tools/eslint/lib/rules/no-inline-comments.js | 2 +- .../eslint/lib/rules/no-inner-declarations.js | 14 +- tools/eslint/lib/rules/no-invalid-this.js | 2 +- .../lib/rules/no-irregular-whitespace.js | 6 +- tools/eslint/lib/rules/no-iterator.js | 2 +- tools/eslint/lib/rules/no-label-var.js | 2 +- tools/eslint/lib/rules/no-lone-blocks.js | 4 +- tools/eslint/lib/rules/no-lonely-if.js | 2 +- tools/eslint/lib/rules/no-loop-func.js | 2 +- tools/eslint/lib/rules/no-mixed-operators.js | 6 +- tools/eslint/lib/rules/no-mixed-requires.js | 14 +- .../lib/rules/no-mixed-spaces-and-tabs.js | 8 +- tools/eslint/lib/rules/no-multi-spaces.js | 2 +- tools/eslint/lib/rules/no-multi-str.js | 2 +- .../lib/rules/no-multiple-empty-lines.js | 22 +- tools/eslint/lib/rules/no-native-reassign.js | 2 +- .../eslint/lib/rules/no-negated-condition.js | 4 +- tools/eslint/lib/rules/no-negated-in-lhs.js | 2 +- tools/eslint/lib/rules/no-nested-ternary.js | 2 +- tools/eslint/lib/rules/no-new-func.js | 2 +- tools/eslint/lib/rules/no-new-object.js | 2 +- tools/eslint/lib/rules/no-new-require.js | 2 +- tools/eslint/lib/rules/no-new-symbol.js | 4 +- tools/eslint/lib/rules/no-new-wrappers.js | 2 +- tools/eslint/lib/rules/no-new.js | 2 +- tools/eslint/lib/rules/no-obj-calls.js | 4 +- tools/eslint/lib/rules/no-octal-escape.js | 3 +- tools/eslint/lib/rules/no-octal.js | 2 +- tools/eslint/lib/rules/no-param-reassign.js | 12 +- tools/eslint/lib/rules/no-path-concat.js | 2 +- tools/eslint/lib/rules/no-process-env.js | 2 +- tools/eslint/lib/rules/no-process-exit.js | 2 +- tools/eslint/lib/rules/no-proto.js | 2 +- .../eslint/lib/rules/no-prototype-builtins.js | 2 +- tools/eslint/lib/rules/no-redeclare.js | 13 +- tools/eslint/lib/rules/no-regex-spaces.js | 2 +- .../eslint/lib/rules/no-restricted-globals.js | 8 +- .../eslint/lib/rules/no-restricted-imports.js | 56 +- .../eslint/lib/rules/no-restricted-modules.js | 89 +- .../lib/rules/no-restricted-properties.js | 12 +- .../eslint/lib/rules/no-restricted-syntax.js | 8 +- tools/eslint/lib/rules/no-return-await.js | 94 + tools/eslint/lib/rules/no-script-url.js | 2 +- tools/eslint/lib/rules/no-self-compare.js | 2 +- tools/eslint/lib/rules/no-sequences.js | 2 +- tools/eslint/lib/rules/no-shadow.js | 4 +- tools/eslint/lib/rules/no-sparse-arrays.js | 2 +- tools/eslint/lib/rules/no-tabs.js | 14 +- tools/eslint/lib/rules/no-ternary.js | 2 +- .../eslint/lib/rules/no-this-before-super.js | 6 +- tools/eslint/lib/rules/no-throw-literal.js | 4 +- tools/eslint/lib/rules/no-undef-init.js | 2 +- tools/eslint/lib/rules/no-undef.js | 2 +- tools/eslint/lib/rules/no-undefined.js | 2 +- .../eslint/lib/rules/no-underscore-dangle.js | 4 +- .../lib/rules/no-unexpected-multiline.js | 4 +- tools/eslint/lib/rules/no-unneeded-ternary.js | 75 +- .../eslint/lib/rules/no-unused-expressions.js | 2 +- tools/eslint/lib/rules/no-unused-vars.js | 32 +- .../eslint/lib/rules/no-use-before-define.js | 8 +- tools/eslint/lib/rules/no-useless-call.js | 5 +- tools/eslint/lib/rules/no-useless-concat.js | 7 +- tools/eslint/lib/rules/no-useless-escape.js | 195 +- tools/eslint/lib/rules/no-useless-return.js | 293 + tools/eslint/lib/rules/no-var.js | 99 +- tools/eslint/lib/rules/no-void.js | 2 +- tools/eslint/lib/rules/no-warning-comments.js | 6 +- tools/eslint/lib/rules/no-with.js | 2 +- .../eslint/lib/rules/object-curly-newline.js | 4 +- .../lib/rules/object-property-newline.js | 17 +- tools/eslint/lib/rules/object-shorthand.js | 219 +- .../lib/rules/one-var-declaration-per-line.js | 2 +- tools/eslint/lib/rules/one-var.js | 18 +- tools/eslint/lib/rules/operator-assignment.js | 74 +- tools/eslint/lib/rules/operator-linebreak.js | 76 +- tools/eslint/lib/rules/padded-blocks.js | 4 +- .../eslint/lib/rules/prefer-arrow-callback.js | 4 +- tools/eslint/lib/rules/prefer-const.js | 137 +- .../eslint/lib/rules/prefer-destructuring.js | 173 + tools/eslint/lib/rules/prefer-reflect.js | 10 +- tools/eslint/lib/rules/quote-props.js | 14 +- tools/eslint/lib/rules/quotes.js | 17 +- tools/eslint/lib/rules/radix.js | 4 +- tools/eslint/lib/rules/require-await.js | 95 + tools/eslint/lib/rules/require-jsdoc.js | 10 +- tools/eslint/lib/rules/require-yield.js | 4 +- tools/eslint/lib/rules/semi.js | 6 +- tools/eslint/lib/rules/sort-imports.js | 68 +- tools/eslint/lib/rules/sort-vars.js | 4 +- tools/eslint/lib/rules/space-in-parens.js | 2 +- tools/eslint/lib/rules/space-infix-ops.js | 2 +- tools/eslint/lib/rules/spaced-comment.js | 2 +- tools/eslint/lib/rules/strict.js | 16 +- tools/eslint/lib/rules/symbol-description.js | 2 +- .../lib/rules/template-curly-spacing.js | 2 +- tools/eslint/lib/rules/unicode-bom.js | 2 +- tools/eslint/lib/rules/use-isnan.js | 2 +- tools/eslint/lib/rules/valid-jsdoc.js | 32 +- tools/eslint/lib/rules/valid-typeof.js | 4 +- tools/eslint/lib/rules/vars-on-top.js | 4 +- tools/eslint/lib/rules/yield-star-spacing.js | 4 +- tools/eslint/lib/rules/yoda.js | 51 +- .../lib/testers/event-generator-tester.js | 10 +- tools/eslint/lib/testers/rule-tester.js | 42 +- tools/eslint/lib/timing.js | 24 +- .../lib/util/comment-event-generator.js | 2 +- tools/eslint/lib/util/glob-util.js | 16 +- tools/eslint/lib/util/module-resolver.js | 24 +- tools/eslint/lib/util/node-event-generator.js | 23 +- tools/eslint/lib/util/npm-util.js | 8 +- tools/eslint/lib/util/patterns/letters.js | 37 + tools/eslint/lib/util/source-code-fixer.js | 8 +- tools/eslint/lib/util/source-code-util.js | 12 +- tools/eslint/lib/util/source-code.js | 12 +- tools/eslint/lib/util/traverser.js | 4 +- tools/eslint/lib/util/xml-escape.js | 2 +- tools/eslint/node_modules/.bin/eslint | 1 + .../node_modules/.bin/strip-json-comments | 1 - tools/eslint/node_modules/acorn/.tern-project | 6 - tools/eslint/node_modules/acorn/AUTHORS | 2 + .../acorn/bin/generate-identifier-regex.js | 55 - .../node_modules/acorn/bin/update_authors.sh | 6 - .../node_modules/acorn/dist/acorn.es.js | 52 +- tools/eslint/node_modules/acorn/dist/acorn.js | 6404 +++++++++-------- .../node_modules/acorn/dist/acorn_loose.es.js | 33 +- .../node_modules/acorn/dist/acorn_loose.js | 2391 +++--- tools/eslint/node_modules/acorn/dist/walk.js | 648 +- tools/eslint/node_modules/acorn/package.json | 28 +- .../node_modules/acorn/rollup/config.bin.js | 15 - .../node_modules/acorn/rollup/config.loose.js | 22 - .../node_modules/acorn/rollup/config.main.js | 11 - .../node_modules/acorn/rollup/config.walk.js | 11 - tools/eslint/node_modules/acorn/src/index.js | 2 +- .../node_modules/acorn/src/statement.js | 7 +- .../node_modules/ajv-keywords/.eslintrc.yml | 32 - .../node_modules/ajv-keywords/README.md | 274 +- .../eslint/node_modules/ajv-keywords/index.js | 6 +- .../ajv-keywords/keywords/_formatLimit.js | 92 + .../ajv-keywords/keywords/deepProperties.js | 55 + .../ajv-keywords/keywords/deepRequired.js | 57 + .../keywords/dot/_formatLimit.jst | 116 + .../keywords/dot/patternRequired.jst | 28 + .../ajv-keywords/keywords/dot/switch.jst | 73 + .../ajv-keywords/keywords/dotjs/README.md | 3 + .../keywords/dotjs/_formatLimit.js | 176 + .../keywords/dotjs/patternRequired.js | 52 + .../ajv-keywords/keywords/dotjs/switch.js | 129 + .../ajv-keywords/keywords/dynamicDefaults.js | 68 + .../ajv-keywords/keywords/formatMaximum.js | 3 + .../ajv-keywords/keywords/formatMinimum.js | 3 + .../node_modules/ajv-keywords/keywords/if.js | 21 + .../ajv-keywords/keywords/index.js | 15 +- .../ajv-keywords/keywords/instanceof.js | 71 +- .../ajv-keywords/keywords/patternRequired.js | 24 + .../ajv-keywords/keywords/prohibited.js | 25 + .../ajv-keywords/keywords/propertyNames.js | 9 +- .../ajv-keywords/keywords/range.js | 63 +- .../ajv-keywords/keywords/regexp.js | 9 +- .../ajv-keywords/keywords/switch.js | 39 + .../ajv-keywords/keywords/typeof.js | 49 +- .../node_modules/ajv-keywords/package.json | 43 +- tools/eslint/node_modules/ajv/README.md | 49 +- .../node_modules/ajv/dist/ajv.bundle.js | 351 +- tools/eslint/node_modules/ajv/dist/ajv.min.js | 10 +- .../node_modules/ajv/dist/ajv.min.js.map | 2 +- .../node_modules/ajv/dist/nodent.min.js | 16 +- .../node_modules/ajv/dist/regenerator.min.js | 48 +- tools/eslint/node_modules/ajv/lib/ajv.d.ts | 14 + tools/eslint/node_modules/ajv/lib/ajv.js | 6 +- tools/eslint/node_modules/ajv/lib/async.js | 8 +- .../node_modules/ajv/lib/compile/equal.js | 15 +- .../node_modules/ajv/lib/compile/formats.js | 4 +- .../node_modules/ajv/lib/compile/index.js | 13 +- .../eslint/node_modules/ajv/lib/dot/allOf.jst | 12 +- .../eslint/node_modules/ajv/lib/dot/anyOf.jst | 2 +- .../node_modules/ajv/lib/dot/custom.jst | 2 +- .../node_modules/ajv/lib/dot/definitions.def | 5 +- .../node_modules/ajv/lib/dot/dependencies.jst | 2 +- .../eslint/node_modules/ajv/lib/dot/enum.jst | 12 +- .../node_modules/ajv/lib/dot/errors.def | 2 +- .../node_modules/ajv/lib/dot/format.jst | 34 +- .../eslint/node_modules/ajv/lib/dot/items.jst | 17 +- tools/eslint/node_modules/ajv/lib/dot/not.jst | 2 +- .../eslint/node_modules/ajv/lib/dot/oneOf.jst | 6 +- .../node_modules/ajv/lib/dot/properties.jst | 42 +- tools/eslint/node_modules/ajv/lib/dot/ref.jst | 2 +- .../node_modules/ajv/lib/dot/required.jst | 15 +- .../node_modules/ajv/lib/dot/v5/switch.jst | 6 +- .../ajv/lib/dotjs/_formatLimit.js | 2 +- .../node_modules/ajv/lib/dotjs/_limit.js | 2 +- .../node_modules/ajv/lib/dotjs/_limitItems.js | 2 +- .../ajv/lib/dotjs/_limitLength.js | 2 +- .../ajv/lib/dotjs/_limitProperties.js | 2 +- .../node_modules/ajv/lib/dotjs/allOf.js | 15 +- .../node_modules/ajv/lib/dotjs/anyOf.js | 5 +- .../node_modules/ajv/lib/dotjs/constant.js | 2 +- .../node_modules/ajv/lib/dotjs/custom.js | 7 +- .../ajv/lib/dotjs/dependencies.js | 7 +- .../eslint/node_modules/ajv/lib/dotjs/enum.js | 9 +- .../node_modules/ajv/lib/dotjs/format.js | 34 +- .../node_modules/ajv/lib/dotjs/items.js | 34 +- .../node_modules/ajv/lib/dotjs/multipleOf.js | 2 +- .../eslint/node_modules/ajv/lib/dotjs/not.js | 5 +- .../node_modules/ajv/lib/dotjs/oneOf.js | 9 +- .../node_modules/ajv/lib/dotjs/pattern.js | 2 +- .../ajv/lib/dotjs/patternRequired.js | 2 +- .../node_modules/ajv/lib/dotjs/properties.js | 59 +- .../eslint/node_modules/ajv/lib/dotjs/ref.js | 3 +- .../node_modules/ajv/lib/dotjs/required.js | 15 +- .../node_modules/ajv/lib/dotjs/switch.js | 11 +- .../node_modules/ajv/lib/dotjs/uniqueItems.js | 2 +- tools/eslint/node_modules/ajv/lib/keyword.js | 72 +- tools/eslint/node_modules/ajv/package.json | 40 +- tools/eslint/node_modules/ajv/scripts/bundle | 33 + .../node_modules/ajv/scripts/compile-dots.js | 56 + tools/eslint/node_modules/ajv/scripts/info | 10 + .../node_modules/ajv/scripts/prepare-tests | 9 + .../node_modules/ajv/scripts/travis-gh-pages | 21 + .../node_modules/babel-code-frame/README.md | 43 + .../babel-code-frame/lib/index.js | 141 + .../babel-code-frame/package.json | 102 + .../eslint/node_modules/buffer-shims/index.js | 108 + .../node_modules/buffer-shims/license.md | 19 + .../node_modules/buffer-shims/package.json | 85 + .../node_modules/buffer-shims/readme.md | 21 + tools/eslint/node_modules/chalk/package.json | 1 + .../node_modules/circular-json/package.json | 16 +- .../node_modules/code-point-at/index.js | 7 +- .../node_modules/code-point-at/package.json | 31 +- .../node_modules/code-point-at/readme.md | 2 +- .../node_modules/concat-stream/package.json | 30 +- .../node_modules/concat-stream/readme.md | 2 +- .../eslint/node_modules/debug/.coveralls.yml | 1 + tools/eslint/node_modules/debug/LICENSE | 19 + tools/eslint/node_modules/debug/Makefile | 54 +- tools/eslint/node_modules/debug/Readme.md | 92 +- tools/eslint/node_modules/debug/karma.conf.js | 70 + tools/eslint/node_modules/debug/node.js | 210 +- tools/eslint/node_modules/debug/package.json | 62 +- .../node_modules/debug/{ => src}/browser.js | 44 +- .../node_modules/debug/{ => src}/debug.js | 74 +- tools/eslint/node_modules/debug/src/index.js | 10 + tools/eslint/node_modules/debug/src/node.js | 240 + .../eslint/node_modules/esutils/package.json | 1 + .../fast-levenshtein/levenshtein.js | 86 +- .../fast-levenshtein/package.json | 22 +- tools/eslint/node_modules/flat-cache/cache.js | 6 +- .../node_modules/flat-cache/changelog.md | 21 + .../node_modules/flat-cache/package.json | 24 +- tools/eslint/node_modules/flat-cache/utils.js | 10 + tools/eslint/node_modules/glob/package.json | 3 +- .../eslint/node_modules/globals/globals.json | 2 + .../eslint/node_modules/globals/package.json | 38 +- .../node_modules/graceful-fs/package.json | 20 +- .../node_modules/graceful-fs/polyfills.js | 28 +- tools/eslint/node_modules/ignore/package.json | 16 +- .../eslint/node_modules/inherits/package.json | 16 +- tools/eslint/node_modules/interpret/LICENSE | 22 + tools/eslint/node_modules/interpret/README.md | 136 + tools/eslint/node_modules/interpret/index.js | 132 + .../node_modules/interpret/package.json | 119 + .../node_modules/is-path-in-cwd/package.json | 2 +- tools/eslint/node_modules/js-tokens/LICENSE | 21 + .../node_modules/js-tokens/changelog.md | 82 + tools/eslint/node_modules/js-tokens/index.js | 19 + .../node_modules/js-tokens/package.json | 100 + tools/eslint/node_modules/js-tokens/readme.md | 217 + .../node_modules/js-yaml/dist/js-yaml.js | 24 +- .../node_modules/js-yaml/dist/js-yaml.min.js | 6 +- .../js-yaml/lib/js-yaml/dumper.js | 3 +- .../js-yaml/lib/js-yaml/loader.js | 7 +- .../js-yaml/lib/js-yaml/schema.js | 12 +- .../eslint/node_modules/js-yaml/package.json | 22 +- .../eslint/node_modules/jsonpointer/README.md | 2 +- .../node_modules/jsonpointer/benchmark.js | 56 - .../node_modules/jsonpointer/package.json | 25 +- tools/eslint/node_modules/lodash/LICENSE | 2 +- tools/eslint/node_modules/lodash/README.md | 6 +- tools/eslint/node_modules/lodash/_Hash.js | 2 +- .../eslint/node_modules/lodash/_ListCache.js | 2 +- tools/eslint/node_modules/lodash/_MapCache.js | 2 +- tools/eslint/node_modules/lodash/_SetCache.js | 2 +- .../node_modules/lodash/_arrayAggregator.js | 2 +- .../eslint/node_modules/lodash/_arrayEach.js | 2 +- .../node_modules/lodash/_arrayEachRight.js | 2 +- .../eslint/node_modules/lodash/_arrayEvery.js | 2 +- .../node_modules/lodash/_arrayFilter.js | 2 +- .../node_modules/lodash/_arrayIncludes.js | 2 +- .../node_modules/lodash/_arrayIncludesWith.js | 2 +- tools/eslint/node_modules/lodash/_arrayMap.js | 2 +- .../node_modules/lodash/_arrayReduce.js | 2 +- .../node_modules/lodash/_arrayReduceRight.js | 2 +- .../eslint/node_modules/lodash/_arraySome.js | 2 +- .../node_modules/lodash/_baseAssignIn.js | 17 + tools/eslint/node_modules/lodash/_baseAt.js | 8 +- .../eslint/node_modules/lodash/_baseClone.js | 36 +- .../node_modules/lodash/_baseDifference.js | 2 +- tools/eslint/node_modules/lodash/_baseGet.js | 3 +- .../eslint/node_modules/lodash/_baseGetTag.js | 26 +- .../eslint/node_modules/lodash/_baseInvoke.js | 10 +- .../node_modules/lodash/_baseIsArguments.js | 15 +- .../node_modules/lodash/_baseIsArrayBuffer.js | 15 +- .../eslint/node_modules/lodash/_baseIsDate.js | 15 +- .../node_modules/lodash/_baseIsEqual.js | 14 +- .../node_modules/lodash/_baseIsEqualDeep.js | 36 +- .../node_modules/lodash/_baseIsMatch.js | 8 +- .../node_modules/lodash/_baseIsRegExp.js | 15 +- .../node_modules/lodash/_baseIsTypedArray.js | 15 +- .../lodash/_baseMatchesProperty.js | 8 +- tools/eslint/node_modules/lodash/_baseMean.js | 2 +- tools/eslint/node_modules/lodash/_basePick.js | 12 +- .../eslint/node_modules/lodash/_basePickBy.js | 18 +- .../eslint/node_modules/lodash/_basePullAt.js | 21 +- tools/eslint/node_modules/lodash/_baseSet.js | 3 +- .../node_modules/lodash/_baseSortedIndex.js | 2 +- .../node_modules/lodash/_baseSortedIndexBy.js | 2 +- .../eslint/node_modules/lodash/_baseUnset.js | 15 +- tools/eslint/node_modules/lodash/_baseXor.js | 26 +- tools/eslint/node_modules/lodash/_castPath.js | 12 +- tools/eslint/node_modules/lodash/_cloneMap.js | 5 +- tools/eslint/node_modules/lodash/_cloneSet.js | 5 +- .../node_modules/lodash/_copySymbols.js | 2 +- .../node_modules/lodash/_copySymbolsIn.js | 16 + .../eslint/node_modules/lodash/_createBind.js | 4 +- .../eslint/node_modules/lodash/_createFlow.js | 16 +- .../node_modules/lodash/_createHybrid.js | 22 +- .../node_modules/lodash/_createPartial.js | 4 +- .../node_modules/lodash/_createRecurry.js | 22 +- .../node_modules/lodash/_createRound.js | 2 +- .../eslint/node_modules/lodash/_createWrap.js | 51 +- ...Defaults.js => _customDefaultsAssignIn.js} | 8 +- ...rgeDefaults.js => _customDefaultsMerge.js} | 9 +- .../node_modules/lodash/_customOmitClone.js | 16 + .../node_modules/lodash/_equalArrays.js | 21 +- .../eslint/node_modules/lodash/_equalByTag.js | 19 +- .../node_modules/lodash/_equalObjects.js | 21 +- .../eslint/node_modules/lodash/_getRawTag.js | 46 + .../eslint/node_modules/lodash/_getSymbols.js | 20 +- .../node_modules/lodash/_getSymbolsIn.js | 3 +- tools/eslint/node_modules/lodash/_getTag.js | 14 +- tools/eslint/node_modules/lodash/_hasPath.js | 5 +- .../eslint/node_modules/lodash/_hasUnicode.js | 8 +- tools/eslint/node_modules/lodash/_hashHas.js | 2 +- .../eslint/node_modules/lodash/_lazyValue.js | 6 +- .../eslint/node_modules/lodash/_mergeData.js | 26 +- tools/eslint/node_modules/lodash/_nodeUtil.js | 2 +- .../node_modules/lodash/_objectToString.js | 22 + tools/eslint/node_modules/lodash/_parent.js | 2 +- tools/eslint/node_modules/lodash/_shortOut.js | 2 +- .../node_modules/lodash/_stringToPath.js | 5 +- tools/eslint/node_modules/lodash/_toSource.js | 2 +- .../node_modules/lodash/_unicodeSize.js | 8 +- .../node_modules/lodash/_unicodeToArray.js | 8 +- .../node_modules/lodash/_unicodeWords.js | 28 +- .../node_modules/lodash/_updateWrapDetails.js | 36 +- tools/eslint/node_modules/lodash/ary.js | 4 +- tools/eslint/node_modules/lodash/at.js | 2 +- tools/eslint/node_modules/lodash/bind.js | 8 +- tools/eslint/node_modules/lodash/bindKey.js | 10 +- tools/eslint/node_modules/lodash/chunk.js | 2 +- tools/eslint/node_modules/lodash/clone.js | 5 +- tools/eslint/node_modules/lodash/cloneDeep.js | 6 +- .../node_modules/lodash/cloneDeepWith.js | 7 +- tools/eslint/node_modules/lodash/cloneWith.js | 6 +- tools/eslint/node_modules/lodash/compact.js | 2 +- tools/eslint/node_modules/lodash/cond.js | 2 +- tools/eslint/node_modules/lodash/conforms.js | 5 +- tools/eslint/node_modules/lodash/core.js | 239 +- tools/eslint/node_modules/lodash/core.min.js | 46 +- tools/eslint/node_modules/lodash/countBy.js | 3 +- tools/eslint/node_modules/lodash/create.js | 2 +- tools/eslint/node_modules/lodash/curry.js | 4 +- .../eslint/node_modules/lodash/curryRight.js | 4 +- tools/eslint/node_modules/lodash/deburr.js | 8 +- tools/eslint/node_modules/lodash/defaults.js | 6 +- .../node_modules/lodash/defaultsDeep.js | 4 +- tools/eslint/node_modules/lodash/drop.js | 2 +- tools/eslint/node_modules/lodash/dropRight.js | 2 +- tools/eslint/node_modules/lodash/dropWhile.js | 3 +- tools/eslint/node_modules/lodash/every.js | 3 +- tools/eslint/node_modules/lodash/fill.js | 2 +- tools/eslint/node_modules/lodash/filter.js | 3 +- tools/eslint/node_modules/lodash/find.js | 3 +- tools/eslint/node_modules/lodash/findIndex.js | 5 +- tools/eslint/node_modules/lodash/findLast.js | 3 +- .../node_modules/lodash/findLastIndex.js | 5 +- tools/eslint/node_modules/lodash/flatMap.js | 3 +- .../eslint/node_modules/lodash/flatMapDeep.js | 3 +- .../node_modules/lodash/flatMapDepth.js | 3 +- tools/eslint/node_modules/lodash/flatten.js | 2 +- .../eslint/node_modules/lodash/flattenDeep.js | 2 +- .../node_modules/lodash/flattenDepth.js | 2 +- tools/eslint/node_modules/lodash/flip.js | 4 +- tools/eslint/node_modules/lodash/forEach.js | 4 +- .../node_modules/lodash/forEachRight.js | 4 +- tools/eslint/node_modules/lodash/forIn.js | 4 +- .../eslint/node_modules/lodash/forInRight.js | 4 +- tools/eslint/node_modules/lodash/forOwn.js | 4 +- .../eslint/node_modules/lodash/forOwnRight.js | 4 +- .../node_modules/lodash/fp/_baseConvert.js | 77 +- .../eslint/node_modules/lodash/fp/_mapping.js | 15 +- tools/eslint/node_modules/lodash/fp/_util.js | 1 - tools/eslint/node_modules/lodash/fromPairs.js | 2 +- tools/eslint/node_modules/lodash/groupBy.js | 3 +- tools/eslint/node_modules/lodash/indexOf.js | 2 +- tools/eslint/node_modules/lodash/initial.js | 2 +- .../node_modules/lodash/intersectionWith.js | 5 +- tools/eslint/node_modules/lodash/invokeMap.js | 7 +- tools/eslint/node_modules/lodash/isBoolean.js | 15 +- tools/eslint/node_modules/lodash/isElement.js | 2 +- tools/eslint/node_modules/lodash/isEmpty.js | 3 + tools/eslint/node_modules/lodash/isEqual.js | 2 +- .../eslint/node_modules/lodash/isEqualWith.js | 2 +- tools/eslint/node_modules/lodash/isError.js | 22 +- .../eslint/node_modules/lodash/isFunction.js | 25 +- tools/eslint/node_modules/lodash/isNative.js | 2 +- tools/eslint/node_modules/lodash/isNumber.js | 15 +- .../node_modules/lodash/isPlainObject.js | 16 +- tools/eslint/node_modules/lodash/isString.js | 15 +- tools/eslint/node_modules/lodash/isSymbol.js | 15 +- tools/eslint/node_modules/lodash/isWeakSet.js | 15 +- tools/eslint/node_modules/lodash/iteratee.js | 5 +- tools/eslint/node_modules/lodash/join.js | 2 +- tools/eslint/node_modules/lodash/keyBy.js | 3 +- tools/eslint/node_modules/lodash/last.js | 2 +- .../eslint/node_modules/lodash/lastIndexOf.js | 2 +- tools/eslint/node_modules/lodash/lodash.js | 1024 +-- .../eslint/node_modules/lodash/lodash.min.js | 264 +- tools/eslint/node_modules/lodash/matches.js | 5 +- .../node_modules/lodash/matchesProperty.js | 5 +- tools/eslint/node_modules/lodash/memoize.js | 4 +- tools/eslint/node_modules/lodash/omit.js | 44 +- tools/eslint/node_modules/lodash/package.json | 29 +- tools/eslint/node_modules/lodash/partial.js | 4 +- .../node_modules/lodash/partialRight.js | 4 +- tools/eslint/node_modules/lodash/pick.js | 12 +- tools/eslint/node_modules/lodash/pickBy.js | 14 +- tools/eslint/node_modules/lodash/pullAllBy.js | 3 +- tools/eslint/node_modules/lodash/pullAt.js | 2 +- tools/eslint/node_modules/lodash/rearg.js | 4 +- tools/eslint/node_modules/lodash/remove.js | 3 +- tools/eslint/node_modules/lodash/result.js | 5 +- tools/eslint/node_modules/lodash/reverse.js | 2 +- tools/eslint/node_modules/lodash/slice.js | 2 +- .../node_modules/lodash/sortedIndexBy.js | 3 +- .../node_modules/lodash/sortedIndexOf.js | 2 +- .../node_modules/lodash/sortedLastIndexBy.js | 3 +- .../node_modules/lodash/sortedLastIndexOf.js | 2 +- tools/eslint/node_modules/lodash/spread.js | 2 +- .../eslint/node_modules/lodash/startsWith.js | 5 +- tools/eslint/node_modules/lodash/tail.js | 2 +- tools/eslint/node_modules/lodash/takeRight.js | 2 +- .../node_modules/lodash/takeRightWhile.js | 3 +- tools/eslint/node_modules/lodash/takeWhile.js | 5 +- tools/eslint/node_modules/lodash/template.js | 8 +- .../node_modules/lodash/templateSettings.js | 4 +- tools/eslint/node_modules/lodash/times.js | 6 +- tools/eslint/node_modules/lodash/toArray.js | 6 +- tools/eslint/node_modules/lodash/toPath.js | 5 +- .../node_modules/lodash/toSafeInteger.js | 4 +- tools/eslint/node_modules/lodash/unionBy.js | 3 +- tools/eslint/node_modules/lodash/unionWith.js | 4 +- tools/eslint/node_modules/lodash/uniq.js | 4 +- tools/eslint/node_modules/lodash/uniqBy.js | 7 +- tools/eslint/node_modules/lodash/uniqWith.js | 5 +- tools/eslint/node_modules/lodash/values.js | 2 +- tools/eslint/node_modules/lodash/wrap.js | 5 +- tools/eslint/node_modules/lodash/wrapperAt.js | 2 +- .../node_modules/lodash/wrapperLodash.js | 6 +- tools/eslint/node_modules/lodash/xorBy.js | 3 +- tools/eslint/node_modules/lodash/xorWith.js | 4 +- tools/eslint/node_modules/lodash/zipWith.js | 3 +- tools/eslint/node_modules/ms/LICENSE.md | 21 + tools/eslint/node_modules/ms/README.md | 33 +- tools/eslint/node_modules/ms/index.js | 102 +- tools/eslint/node_modules/ms/package.json | 80 +- .../node_modules/number-is-nan/package.json | 5 +- .../node_modules/prelude-ls/package.json | 2 +- .../node_modules/readable-stream/.zuul.yml | 1 - .../node_modules/readable-stream/README.md | 8 +- .../readable-stream/lib/_stream_readable.js | 285 +- .../readable-stream/lib/_stream_transform.js | 16 +- .../readable-stream/lib/_stream_writable.js | 76 +- .../lib/internal/streams/BufferList.js | 64 + .../node_modules/readable-stream/package.json | 57 +- .../node_modules/readable-stream/readable.js | 4 + tools/eslint/node_modules/rechoir/LICENSE | 22 + tools/eslint/node_modules/rechoir/README.md | 42 + tools/eslint/node_modules/rechoir/index.js | 59 + .../node_modules/rechoir/lib/extension.js | 11 + .../node_modules/rechoir/lib/normalize.js | 15 + .../node_modules/rechoir/lib/register.js | 15 + .../eslint/node_modules/rechoir/package.json | 148 + .../node_modules/require-uncached/index.js | 19 +- .../node_modules/require-uncached/license | 21 + .../require-uncached/package.json | 38 +- .../node_modules/require-uncached/readme.md | 19 +- .../node_modules/{ms => resolve}/LICENSE | 4 +- tools/eslint/node_modules/resolve/index.js | 5 + .../eslint/node_modules/resolve/lib/async.js | 193 + .../eslint/node_modules/resolve/lib/caller.js | 8 + tools/eslint/node_modules/resolve/lib/core.js | 22 + .../eslint/node_modules/resolve/lib/core.json | 47 + .../resolve/lib/node-modules-paths.js | 38 + tools/eslint/node_modules/resolve/lib/sync.js | 84 + .../eslint/node_modules/resolve/package.json | 101 + .../node_modules/resolve/readme.markdown | 148 + .../node_modules/shelljs/.eslintrc.json | 32 + tools/eslint/node_modules/shelljs/README.md | 294 +- tools/eslint/node_modules/shelljs/bin/shjs | 26 +- tools/eslint/node_modules/shelljs/global.js | 11 +- .../eslint/node_modules/shelljs/package.json | 71 +- tools/eslint/node_modules/shelljs/plugin.js | 16 + .../shelljs/scripts/generate-docs.js | 15 +- .../node_modules/shelljs/scripts/run-tests.js | 36 +- tools/eslint/node_modules/shelljs/shell.js | 148 +- tools/eslint/node_modules/shelljs/src/cat.js | 24 +- tools/eslint/node_modules/shelljs/src/cd.js | 36 +- .../eslint/node_modules/shelljs/src/chmod.js | 98 +- .../eslint/node_modules/shelljs/src/common.js | 336 +- tools/eslint/node_modules/shelljs/src/cp.js | 276 +- tools/eslint/node_modules/shelljs/src/dirs.js | 21 +- tools/eslint/node_modules/shelljs/src/echo.js | 22 +- .../eslint/node_modules/shelljs/src/error.js | 8 +- tools/eslint/node_modules/shelljs/src/exec.js | 177 +- tools/eslint/node_modules/shelljs/src/find.js | 19 +- tools/eslint/node_modules/shelljs/src/grep.js | 59 +- tools/eslint/node_modules/shelljs/src/head.js | 104 + tools/eslint/node_modules/shelljs/src/ln.js | 23 +- tools/eslint/node_modules/shelljs/src/ls.js | 163 +- .../eslint/node_modules/shelljs/src/mkdir.js | 54 +- tools/eslint/node_modules/shelljs/src/mv.js | 53 +- tools/eslint/node_modules/shelljs/src/popd.js | 2 +- .../eslint/node_modules/shelljs/src/pushd.js | 2 +- tools/eslint/node_modules/shelljs/src/pwd.js | 6 +- tools/eslint/node_modules/shelljs/src/rm.js | 88 +- tools/eslint/node_modules/shelljs/src/sed.js | 55 +- tools/eslint/node_modules/shelljs/src/set.js | 20 +- tools/eslint/node_modules/shelljs/src/sort.js | 91 + tools/eslint/node_modules/shelljs/src/tail.js | 72 + .../node_modules/shelljs/src/tempdir.js | 24 +- tools/eslint/node_modules/shelljs/src/test.js | 66 +- tools/eslint/node_modules/shelljs/src/to.js | 26 +- .../eslint/node_modules/shelljs/src/toEnd.js | 25 +- .../eslint/node_modules/shelljs/src/touch.js | 35 +- tools/eslint/node_modules/shelljs/src/uniq.js | 80 + .../eslint/node_modules/shelljs/src/which.js | 35 +- .../node_modules/string-width/package.json | 3 +- .../node_modules/strip-ansi/package.json | 3 +- .../node_modules/strip-json-comments/cli.js | 41 - .../node_modules/strip-json-comments/index.js | 70 + .../strip-json-comments/package.json | 58 +- .../strip-json-comments/readme.md | 40 +- .../strip-json-comments.js | 73 - .../table/dist/alignString.js.map | 1 - .../table/dist/alignTableData.js.map | 1 - .../table/dist/calculateCellHeight.js | 2 +- .../table/dist/calculateCellHeight.js.map | 1 - .../table/dist/calculateCellWidthIndex.js.map | 1 - .../calculateMaximumColumnWidthIndex.js.map | 1 - .../table/dist/calculateRowHeightIndex.js.map | 1 - .../node_modules/table/dist/createStream.js | 2 +- .../table/dist/createStream.js.map | 1 - .../node_modules/table/dist/drawBorder.js.map | 1 - .../node_modules/table/dist/drawRow.js.map | 1 - .../node_modules/table/dist/drawTable.js.map | 1 - .../table/dist/getBorderCharacters.js.map | 1 - .../node_modules/table/dist/index.js.map | 1 - .../node_modules/table/dist/makeConfig.js | 8 +- .../node_modules/table/dist/makeConfig.js.map | 1 - .../table/dist/makeStreamConfig.js | 8 +- .../table/dist/makeStreamConfig.js.map | 1 - .../dist/mapDataUsingRowHeightIndex.js.map | 1 - .../table/dist/padTableData.js.map | 1 - .../table/dist/stringifyTableData.js.map | 1 - tools/eslint/node_modules/table/dist/table.js | 2 +- .../node_modules/table/dist/table.js.map | 1 - .../table/dist/truncateTableData.js.map | 1 - .../node_modules/table/dist/validateConfig.js | 810 ++- .../table/dist/validateConfig.js.map | 1 - .../table/dist/validateStreamConfig.js | 789 +- .../table/dist/validateStreamConfig.js.map | 1 - .../table/dist/validateTableData.js.map | 1 - .../node_modules/table/dist/wrapString.js.map | 1 - .../node_modules/table/dist/wrapWord.js.map | 1 - .../is-fullwidth-code-point/index.js | 46 + .../is-fullwidth-code-point/license | 21 + .../is-fullwidth-code-point/package.json | 113 + .../is-fullwidth-code-point/readme.md | 39 + .../table/node_modules/string-width/index.js | 35 + .../table/node_modules/string-width/license | 21 + .../node_modules/string-width/package.json | 125 + .../table/node_modules/string-width/readme.md | 42 + tools/eslint/node_modules/table/package.json | 53 +- tools/eslint/node_modules/tryit/package.json | 25 +- .../node_modules/typedarray/package.json | 16 +- tools/eslint/package.json | 49 +- 722 files changed, 20993 insertions(+), 11049 deletions(-) create mode 100644 tools/eslint/lib/formatters/codeframe.js create mode 100644 tools/eslint/lib/rules/capitalized-comments.js create mode 100644 tools/eslint/lib/rules/no-await-in-loop.js create mode 100644 tools/eslint/lib/rules/no-return-await.js create mode 100644 tools/eslint/lib/rules/no-useless-return.js create mode 100644 tools/eslint/lib/rules/prefer-destructuring.js create mode 100644 tools/eslint/lib/rules/require-await.js create mode 100644 tools/eslint/lib/util/patterns/letters.js create mode 120000 tools/eslint/node_modules/.bin/eslint delete mode 120000 tools/eslint/node_modules/.bin/strip-json-comments delete mode 100644 tools/eslint/node_modules/acorn/.tern-project delete mode 100644 tools/eslint/node_modules/acorn/bin/generate-identifier-regex.js delete mode 100755 tools/eslint/node_modules/acorn/bin/update_authors.sh delete mode 100644 tools/eslint/node_modules/acorn/rollup/config.bin.js delete mode 100644 tools/eslint/node_modules/acorn/rollup/config.loose.js delete mode 100644 tools/eslint/node_modules/acorn/rollup/config.main.js delete mode 100644 tools/eslint/node_modules/acorn/rollup/config.walk.js delete mode 100644 tools/eslint/node_modules/ajv-keywords/.eslintrc.yml create mode 100644 tools/eslint/node_modules/ajv-keywords/keywords/_formatLimit.js create mode 100644 tools/eslint/node_modules/ajv-keywords/keywords/deepProperties.js create mode 100644 tools/eslint/node_modules/ajv-keywords/keywords/deepRequired.js create mode 100644 tools/eslint/node_modules/ajv-keywords/keywords/dot/_formatLimit.jst create mode 100644 tools/eslint/node_modules/ajv-keywords/keywords/dot/patternRequired.jst create mode 100644 tools/eslint/node_modules/ajv-keywords/keywords/dot/switch.jst create mode 100644 tools/eslint/node_modules/ajv-keywords/keywords/dotjs/README.md create mode 100644 tools/eslint/node_modules/ajv-keywords/keywords/dotjs/_formatLimit.js create mode 100644 tools/eslint/node_modules/ajv-keywords/keywords/dotjs/patternRequired.js create mode 100644 tools/eslint/node_modules/ajv-keywords/keywords/dotjs/switch.js create mode 100644 tools/eslint/node_modules/ajv-keywords/keywords/dynamicDefaults.js create mode 100644 tools/eslint/node_modules/ajv-keywords/keywords/formatMaximum.js create mode 100644 tools/eslint/node_modules/ajv-keywords/keywords/formatMinimum.js create mode 100644 tools/eslint/node_modules/ajv-keywords/keywords/if.js create mode 100644 tools/eslint/node_modules/ajv-keywords/keywords/patternRequired.js create mode 100644 tools/eslint/node_modules/ajv-keywords/keywords/prohibited.js create mode 100644 tools/eslint/node_modules/ajv-keywords/keywords/switch.js create mode 100755 tools/eslint/node_modules/ajv/scripts/bundle create mode 100644 tools/eslint/node_modules/ajv/scripts/compile-dots.js create mode 100755 tools/eslint/node_modules/ajv/scripts/info create mode 100755 tools/eslint/node_modules/ajv/scripts/prepare-tests create mode 100755 tools/eslint/node_modules/ajv/scripts/travis-gh-pages create mode 100644 tools/eslint/node_modules/babel-code-frame/README.md create mode 100644 tools/eslint/node_modules/babel-code-frame/lib/index.js create mode 100644 tools/eslint/node_modules/babel-code-frame/package.json create mode 100644 tools/eslint/node_modules/buffer-shims/index.js create mode 100644 tools/eslint/node_modules/buffer-shims/license.md create mode 100644 tools/eslint/node_modules/buffer-shims/package.json create mode 100644 tools/eslint/node_modules/buffer-shims/readme.md create mode 100644 tools/eslint/node_modules/debug/.coveralls.yml create mode 100644 tools/eslint/node_modules/debug/LICENSE create mode 100644 tools/eslint/node_modules/debug/karma.conf.js rename tools/eslint/node_modules/debug/{ => src}/browser.js (67%) rename tools/eslint/node_modules/debug/{ => src}/debug.js (68%) create mode 100644 tools/eslint/node_modules/debug/src/index.js create mode 100644 tools/eslint/node_modules/debug/src/node.js create mode 100644 tools/eslint/node_modules/interpret/LICENSE create mode 100644 tools/eslint/node_modules/interpret/README.md create mode 100644 tools/eslint/node_modules/interpret/index.js create mode 100644 tools/eslint/node_modules/interpret/package.json create mode 100644 tools/eslint/node_modules/js-tokens/LICENSE create mode 100644 tools/eslint/node_modules/js-tokens/changelog.md create mode 100644 tools/eslint/node_modules/js-tokens/index.js create mode 100644 tools/eslint/node_modules/js-tokens/package.json create mode 100644 tools/eslint/node_modules/js-tokens/readme.md delete mode 100644 tools/eslint/node_modules/jsonpointer/benchmark.js create mode 100644 tools/eslint/node_modules/lodash/_baseAssignIn.js create mode 100644 tools/eslint/node_modules/lodash/_copySymbolsIn.js rename tools/eslint/node_modules/lodash/{_assignInDefaults.js => _customDefaultsAssignIn.js} (68%) rename tools/eslint/node_modules/lodash/{_mergeDefaults.js => _customDefaultsMerge.js} (69%) create mode 100644 tools/eslint/node_modules/lodash/_customOmitClone.js create mode 100644 tools/eslint/node_modules/lodash/_getRawTag.js create mode 100644 tools/eslint/node_modules/lodash/_objectToString.js create mode 100644 tools/eslint/node_modules/ms/LICENSE.md delete mode 100644 tools/eslint/node_modules/readable-stream/.zuul.yml create mode 100644 tools/eslint/node_modules/readable-stream/lib/internal/streams/BufferList.js create mode 100644 tools/eslint/node_modules/rechoir/LICENSE create mode 100644 tools/eslint/node_modules/rechoir/README.md create mode 100644 tools/eslint/node_modules/rechoir/index.js create mode 100644 tools/eslint/node_modules/rechoir/lib/extension.js create mode 100644 tools/eslint/node_modules/rechoir/lib/normalize.js create mode 100644 tools/eslint/node_modules/rechoir/lib/register.js create mode 100644 tools/eslint/node_modules/rechoir/package.json create mode 100644 tools/eslint/node_modules/require-uncached/license rename tools/eslint/node_modules/{ms => resolve}/LICENSE (93%) create mode 100644 tools/eslint/node_modules/resolve/index.js create mode 100644 tools/eslint/node_modules/resolve/lib/async.js create mode 100644 tools/eslint/node_modules/resolve/lib/caller.js create mode 100644 tools/eslint/node_modules/resolve/lib/core.js create mode 100644 tools/eslint/node_modules/resolve/lib/core.json create mode 100644 tools/eslint/node_modules/resolve/lib/node-modules-paths.js create mode 100644 tools/eslint/node_modules/resolve/lib/sync.js create mode 100644 tools/eslint/node_modules/resolve/package.json create mode 100644 tools/eslint/node_modules/resolve/readme.markdown create mode 100644 tools/eslint/node_modules/shelljs/.eslintrc.json create mode 100644 tools/eslint/node_modules/shelljs/plugin.js create mode 100644 tools/eslint/node_modules/shelljs/src/head.js create mode 100644 tools/eslint/node_modules/shelljs/src/sort.js create mode 100644 tools/eslint/node_modules/shelljs/src/tail.js create mode 100644 tools/eslint/node_modules/shelljs/src/uniq.js delete mode 100755 tools/eslint/node_modules/strip-json-comments/cli.js create mode 100644 tools/eslint/node_modules/strip-json-comments/index.js delete mode 100644 tools/eslint/node_modules/strip-json-comments/strip-json-comments.js delete mode 100644 tools/eslint/node_modules/table/dist/alignString.js.map delete mode 100644 tools/eslint/node_modules/table/dist/alignTableData.js.map delete mode 100644 tools/eslint/node_modules/table/dist/calculateCellHeight.js.map delete mode 100644 tools/eslint/node_modules/table/dist/calculateCellWidthIndex.js.map delete mode 100644 tools/eslint/node_modules/table/dist/calculateMaximumColumnWidthIndex.js.map delete mode 100644 tools/eslint/node_modules/table/dist/calculateRowHeightIndex.js.map delete mode 100644 tools/eslint/node_modules/table/dist/createStream.js.map delete mode 100644 tools/eslint/node_modules/table/dist/drawBorder.js.map delete mode 100644 tools/eslint/node_modules/table/dist/drawRow.js.map delete mode 100644 tools/eslint/node_modules/table/dist/drawTable.js.map delete mode 100644 tools/eslint/node_modules/table/dist/getBorderCharacters.js.map delete mode 100644 tools/eslint/node_modules/table/dist/index.js.map delete mode 100644 tools/eslint/node_modules/table/dist/makeConfig.js.map delete mode 100644 tools/eslint/node_modules/table/dist/makeStreamConfig.js.map delete mode 100644 tools/eslint/node_modules/table/dist/mapDataUsingRowHeightIndex.js.map delete mode 100644 tools/eslint/node_modules/table/dist/padTableData.js.map delete mode 100644 tools/eslint/node_modules/table/dist/stringifyTableData.js.map delete mode 100644 tools/eslint/node_modules/table/dist/table.js.map delete mode 100644 tools/eslint/node_modules/table/dist/truncateTableData.js.map delete mode 100644 tools/eslint/node_modules/table/dist/validateConfig.js.map delete mode 100644 tools/eslint/node_modules/table/dist/validateStreamConfig.js.map delete mode 100644 tools/eslint/node_modules/table/dist/validateTableData.js.map delete mode 100644 tools/eslint/node_modules/table/dist/wrapString.js.map delete mode 100644 tools/eslint/node_modules/table/dist/wrapWord.js.map create mode 100644 tools/eslint/node_modules/table/node_modules/is-fullwidth-code-point/index.js create mode 100644 tools/eslint/node_modules/table/node_modules/is-fullwidth-code-point/license create mode 100644 tools/eslint/node_modules/table/node_modules/is-fullwidth-code-point/package.json create mode 100644 tools/eslint/node_modules/table/node_modules/is-fullwidth-code-point/readme.md create mode 100644 tools/eslint/node_modules/table/node_modules/string-width/index.js create mode 100644 tools/eslint/node_modules/table/node_modules/string-width/license create mode 100644 tools/eslint/node_modules/table/node_modules/string-width/package.json create mode 100644 tools/eslint/node_modules/table/node_modules/string-width/readme.md diff --git a/.eslintrc b/.eslintrc index 34f32e59f0a626..cf1f36c86bcbdc 100644 --- a/.eslintrc +++ b/.eslintrc @@ -84,7 +84,11 @@ rules: eol-last: 2 func-call-spacing: 2 func-name-matching: 2 - indent: [2, 2, {SwitchCase: 1, MemberExpression: 1}] + indent: [2, 2, {ArrayExpression: first, + CallExpression: {arguments: first}, + MemberExpression: 1, + ObjectExpression: first, + SwitchCase: 1}] key-spacing: [2, {mode: minimum}] keyword-spacing: 2 linebreak-style: [2, unix] diff --git a/tools/eslint/LICENSE b/tools/eslint/LICENSE index d41bdf7951f077..777939e8fc1a7f 100644 --- a/tools/eslint/LICENSE +++ b/tools/eslint/LICENSE @@ -1,5 +1,5 @@ ESLint -Copyright jQuery Foundation and other contributors, https://jquery.org/ +Copyright JS Foundation and other contributors, https://js.foundation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/tools/eslint/README.md b/tools/eslint/README.md index 4d84a7e3dfd5cd..dcd42cff46685a 100644 --- a/tools/eslint/README.md +++ b/tools/eslint/README.md @@ -13,7 +13,7 @@ [Rules](http://eslint.org/docs/rules/) | [Contributing](http://eslint.org/docs/developer-guide/contributing) | [Reporting Bugs](http://eslint.org/docs/developer-guide/contributing/reporting-bugs) | -[Code of Conduct](https://jquery.org/conduct/) | +[Code of Conduct](https://js.foundation/conduct/) | [Twitter](https://twitter.com/geteslint) | [Mailing List](https://groups.google.com/group/eslint) | [Chat Room](https://gitter.im/eslint/eslint) @@ -210,10 +210,7 @@ ESLint has full support for ECMAScript 6. By default, this support is off. You c ESLint doesn't natively support experimental ECMAScript language features. You can use [babel-eslint](https://github.com/babel/babel-eslint) to use any option available in Babel. -Once a language feature has been adopted into the ECMAScript standard, we will accept -issues and pull requests related to the new feature, subject to our [contributing -guidelines](http://eslint.org/docs/developer-guide/contributing). Until then, please use -the appropriate parser and plugin(s) for your experimental feature. +Once a language feature has been adopted into the ECMAScript standard (stage 4 according to the [TC39 process](https://tc39.github.io/process-document/)), we will accept issues and pull requests related to the new feature, subject to our [contributing guidelines](http://eslint.org/docs/developer-guide/contributing). Until then, please use the appropriate parser and plugin(s) for your experimental feature. ### Where to ask for help? diff --git a/tools/eslint/bin/eslint.js b/tools/eslint/bin/eslint.js index d85d29d7a5bdae..bf534971f24d9b 100755 --- a/tools/eslint/bin/eslint.js +++ b/tools/eslint/bin/eslint.js @@ -5,7 +5,7 @@ * @author Nicholas C. Zakas */ -/* eslint no-console:off, no-process-exit:off */ +/* eslint no-console:off */ "use strict"; @@ -36,7 +36,7 @@ const concat = require("concat-stream"), // Execution //------------------------------------------------------------------------------ -process.on("uncaughtException", function(err) { +process.once("uncaughtException", err => { // lazy load const lodash = require("lodash"); @@ -51,17 +51,17 @@ process.on("uncaughtException", function(err) { console.log(err.stack); } - process.exit(1); + process.exitCode = 1; }); if (useStdIn) { - process.stdin.pipe(concat({ encoding: "string" }, function(text) { + process.stdin.pipe(concat({ encoding: "string" }, text => { process.exitCode = cli.execute(process.argv, text); })); } else if (init) { const configInit = require("../lib/config/config-initializer"); - configInit.initializeConfig(function(err) { + configInit.initializeConfig(err => { if (err) { process.exitCode = 1; console.error(err.message); diff --git a/tools/eslint/conf/eslint.json b/tools/eslint/conf/eslint.json index 4d54e3ab6dac6a..81f5bb8aa5ee82 100755 --- a/tools/eslint/conf/eslint.json +++ b/tools/eslint/conf/eslint.json @@ -4,6 +4,7 @@ "rules": { "no-alert": "off", "no-array-constructor": "off", + "no-await-in-loop": "off", "no-bitwise": "off", "no-caller": "off", "no-case-declarations": "error", @@ -41,7 +42,7 @@ "no-fallthrough": "error", "no-floating-decimal": "off", "no-func-assign": "error", - "no-global-assign": "off", + "no-global-assign": "error", "no-implicit-coercion": "off", "no-implicit-globals": "off", "no-implied-eval": "off", @@ -63,9 +64,9 @@ "no-multi-spaces": "off", "no-multi-str": "off", "no-multiple-empty-lines": "off", - "no-native-reassign": "error", + "no-native-reassign": "off", "no-negated-condition": "off", - "no-negated-in-lhs": "error", + "no-negated-in-lhs": "off", "no-nested-ternary": "off", "no-new": "off", "no-new-func": "off", @@ -91,6 +92,7 @@ "no-restricted-properties": "off", "no-restricted-syntax": "off", "no-return-assign": "off", + "no-return-await": "off", "no-script-url": "off", "no-self-assign": "error", "no-self-compare": "off", @@ -115,7 +117,7 @@ "no-unneeded-ternary": "off", "no-unreachable": "error", "no-unsafe-finally": "error", - "no-unsafe-negation": "off", + "no-unsafe-negation": "error", "no-unused-expressions": "off", "no-unused-labels": "error", "no-unused-vars": "error", @@ -126,6 +128,7 @@ "no-useless-constructor": "off", "no-useless-escape": "off", "no-useless-rename": "off", + "no-useless-return": "off", "no-void": "off", "no-var": "off", "no-warning-comments": "off", @@ -141,6 +144,7 @@ "brace-style": "off", "callback-return": "off", "camelcase": "off", + "capitalized-comments": "off", "class-methods-use-this": "off", "comma-dangle": "off", "comma-spacing": "off", @@ -200,6 +204,7 @@ "padded-blocks": "off", "prefer-arrow-callback": "off", "prefer-const": "off", + "prefer-destructuring": "off", "prefer-numeric-literals": "off", "prefer-reflect": "off", "prefer-rest-params": "off", @@ -208,6 +213,7 @@ "quote-props": "off", "quotes": "off", "radix": "off", + "require-await": "off", "require-jsdoc": "off", "require-yield": "error", "rest-spread-spacing": "off", diff --git a/tools/eslint/lib/ast-utils.js b/tools/eslint/lib/ast-utils.js index 9e171ea316fc31..46dfebe101caa2 100644 --- a/tools/eslint/lib/ast-utils.js +++ b/tools/eslint/lib/ast-utils.js @@ -10,6 +10,7 @@ //------------------------------------------------------------------------------ const esutils = require("esutils"); +const lodash = require("lodash"); //------------------------------------------------------------------------------ // Helpers @@ -21,7 +22,7 @@ const arrayOrTypedArrayPattern = /Array$/; const arrayMethodPattern = /^(?:every|filter|find|findIndex|forEach|map|some)$/; const bindOrCallOrApplyPattern = /^(?:bind|call|apply)$/; const breakableTypePattern = /^(?:(?:Do)?While|For(?:In|Of)?|Switch)Statement$/; -const thisTagPattern = /^[\s\*]*@this/m; +const thisTagPattern = /^[\s*]*@this/m; /** * Checks reference if is non initializer and writable. @@ -83,6 +84,56 @@ function getUpperFunction(node) { return null; } +/** + * Checks whether a given node is a function node or not. + * The following types are function nodes: + * + * - ArrowFunctionExpression + * - FunctionDeclaration + * - FunctionExpression + * + * @param {ASTNode|null} node - A node to check. + * @returns {boolean} `true` if the node is a function node. + */ +function isFunction(node) { + return Boolean(node && anyFunctionPattern.test(node.type)); +} + +/** + * Checks whether a given node is a loop node or not. + * The following types are loop nodes: + * + * - DoWhileStatement + * - ForInStatement + * - ForOfStatement + * - ForStatement + * - WhileStatement + * + * @param {ASTNode|null} node - A node to check. + * @returns {boolean} `true` if the node is a loop node. + */ +function isLoop(node) { + return Boolean(node && anyLoopPattern.test(node.type)); +} + +/** + * Checks whether the given node is in a loop or not. + * + * @param {ASTNode} node - The node to check. + * @returns {boolean} `true` if the node is in a loop. + */ +function isInLoop(node) { + while (node && !isFunction(node)) { + if (isLoop(node)) { + return true; + } + + node = node.parent; + } + + return false; +} + /** * Checks whether or not a node is `null` or `undefined`. * @param {ASTNode} node - A node to check. @@ -176,9 +227,7 @@ function hasJSDocThisTag(node, sourceCode) { // because callbacks don't have its JSDoc comment. // e.g. // sinon.test(/* @this sinon.Sandbox */function() { this.spy(); }); - return sourceCode.getComments(node).leading.some(function(comment) { - return thisTagPattern.test(comment.value); - }); + return sourceCode.getComments(node).leading.some(comment => thisTagPattern.test(comment.value)); } /** @@ -197,6 +246,59 @@ function isParenthesised(sourceCode, node) { nextToken.value === ")" && nextToken.range[0] >= node.range[1]; } +/** + * Gets the `=>` token of the given arrow function node. + * + * @param {ASTNode} node - The arrow function node to get. + * @param {SourceCode} sourceCode - The source code object to get tokens. + * @returns {Token} `=>` token. + */ +function getArrowToken(node, sourceCode) { + let token = sourceCode.getTokenBefore(node.body); + + while (token.value !== "=>") { + token = sourceCode.getTokenBefore(token); + } + + return token; +} + +/** + * Gets the `(` token of the given function node. + * + * @param {ASTNode} node - The function node to get. + * @param {SourceCode} sourceCode - The source code object to get tokens. + * @returns {Token} `(` token. + */ +function getOpeningParenOfParams(node, sourceCode) { + let token = node.id ? sourceCode.getTokenAfter(node.id) : sourceCode.getFirstToken(node); + + while (token.value !== "(") { + token = sourceCode.getTokenAfter(token); + } + + return token; +} + +const lineIndexCache = new WeakMap(); + +/** + * Gets the range index for the first character in each of the lines of `sourceCode`. + * @param {SourceCode} sourceCode A sourceCode object + * @returns {number[]} The indices of the first characters in the each of the lines of the code + */ +function getLineIndices(sourceCode) { + + if (!lineIndexCache.has(sourceCode)) { + const lineIndices = (sourceCode.text.match(/[^\r\n\u2028\u2029]*(\r\n|\r|\n|\u2028|\u2029)/g) || []) + .reduce((indices, line) => indices.concat(indices[indices.length - 1] + line.length), [0]); + + // Store the sourceCode object in a WeakMap to avoid iterating over all of the lines every time a sourceCode object is passed in. + lineIndexCache.set(sourceCode, lineIndices); + } + return lineIndexCache.get(sourceCode); +} + //------------------------------------------------------------------------------ // Public Interface //------------------------------------------------------------------------------ @@ -218,6 +320,9 @@ module.exports = { isCallee, isES5Constructor, getUpperFunction, + isFunction, + isLoop, + isInLoop, isArrayFromMethod, isParenthesised, @@ -583,35 +688,23 @@ module.exports = { }, /** - * Checks whether a given node is a loop node or not. - * The following types are loop nodes: + * Checks whether the given node is an empty block node or not. * - * - DoWhileStatement - * - ForInStatement - * - ForOfStatement - * - ForStatement - * - WhileStatement - * - * @param {ASTNode|null} node - A node to check. - * @returns {boolean} `true` if the node is a loop node. + * @param {ASTNode|null} node - The node to check. + * @returns {boolean} `true` if the node is an empty block. */ - isLoop(node) { - return Boolean(node && anyLoopPattern.test(node.type)); + isEmptyBlock(node) { + return Boolean(node && node.type === "BlockStatement" && node.body.length === 0); }, /** - * Checks whether a given node is a function node or not. - * The following types are function nodes: + * Checks whether the given node is an empty function node or not. * - * - ArrowFunctionExpression - * - FunctionDeclaration - * - FunctionExpression - * - * @param {ASTNode|null} node - A node to check. - * @returns {boolean} `true` if the node is a function node. + * @param {ASTNode|null} node - The node to check. + * @returns {boolean} `true` if the node is an empty function. */ - isFunction(node) { - return Boolean(node && anyFunctionPattern.test(node.type)); + isEmptyFunction(node) { + return isFunction(node) && module.exports.isEmptyBlock(node.body); }, /** @@ -738,5 +831,271 @@ module.exports = { */ isDecimalInteger(node) { return node.type === "Literal" && typeof node.value === "number" && /^(0|[1-9]\d*)$/.test(node.raw); + }, + + /** + * Gets the name and kind of the given function node. + * + * - `function foo() {}` .................... `function 'foo'` + * - `(function foo() {})` .................. `function 'foo'` + * - `(function() {})` ...................... `function` + * - `function* foo() {}` ................... `generator function 'foo'` + * - `(function* foo() {})` ................. `generator function 'foo'` + * - `(function*() {})` ..................... `generator function` + * - `() => {}` ............................. `arrow function` + * - `async () => {}` ....................... `async arrow function` + * - `({ foo: function foo() {} })` ......... `method 'foo'` + * - `({ foo: function() {} })` ............. `method 'foo'` + * - `({ ['foo']: function() {} })` ......... `method 'foo'` + * - `({ [foo]: function() {} })` ........... `method` + * - `({ foo() {} })` ....................... `method 'foo'` + * - `({ foo: function* foo() {} })` ........ `generator method 'foo'` + * - `({ foo: function*() {} })` ............ `generator method 'foo'` + * - `({ ['foo']: function*() {} })` ........ `generator method 'foo'` + * - `({ [foo]: function*() {} })` .......... `generator method` + * - `({ *foo() {} })` ...................... `generator method 'foo'` + * - `({ foo: async function foo() {} })` ... `async method 'foo'` + * - `({ foo: async function() {} })` ....... `async method 'foo'` + * - `({ ['foo']: async function() {} })` ... `async method 'foo'` + * - `({ [foo]: async function() {} })` ..... `async method` + * - `({ async foo() {} })` ................. `async method 'foo'` + * - `({ get foo() {} })` ................... `getter 'foo'` + * - `({ set foo(a) {} })` .................. `setter 'foo'` + * - `class A { constructor() {} }` ......... `constructor` + * - `class A { foo() {} }` ................. `method 'foo'` + * - `class A { *foo() {} }` ................ `generator method 'foo'` + * - `class A { async foo() {} }` ........... `async method 'foo'` + * - `class A { ['foo']() {} }` ............. `method 'foo'` + * - `class A { *['foo']() {} }` ............ `generator method 'foo'` + * - `class A { async ['foo']() {} }` ....... `async method 'foo'` + * - `class A { [foo]() {} }` ............... `method` + * - `class A { *[foo]() {} }` .............. `generator method` + * - `class A { async [foo]() {} }` ......... `async method` + * - `class A { get foo() {} }` ............. `getter 'foo'` + * - `class A { set foo(a) {} }` ............ `setter 'foo'` + * - `class A { static foo() {} }` .......... `static method 'foo'` + * - `class A { static *foo() {} }` ......... `static generator method 'foo'` + * - `class A { static async foo() {} }` .... `static async method 'foo'` + * - `class A { static get foo() {} }` ...... `static getter 'foo'` + * - `class A { static set foo(a) {} }` ..... `static setter 'foo'` + * + * @param {ASTNode} node - The function node to get. + * @returns {string} The name and kind of the function node. + */ + getFunctionNameWithKind(node) { + const parent = node.parent; + const tokens = []; + + if (parent.type === "MethodDefinition" && parent.static) { + tokens.push("static"); + } + if (node.async) { + tokens.push("async"); + } + if (node.generator) { + tokens.push("generator"); + } + + if (node.type === "ArrowFunctionExpression") { + tokens.push("arrow", "function"); + } else if (parent.type === "Property" || parent.type === "MethodDefinition") { + if (parent.kind === "constructor") { + return "constructor"; + } else if (parent.kind === "get") { + tokens.push("getter"); + } else if (parent.kind === "set") { + tokens.push("setter"); + } else { + tokens.push("method"); + } + } else { + tokens.push("function"); + } + + if (node.id) { + tokens.push(`'${node.id.name}'`); + } else { + const name = module.exports.getStaticPropertyName(parent); + + if (name) { + tokens.push(`'${name}'`); + } + } + + return tokens.join(" "); + }, + + /** + * Gets the location of the given function node for reporting. + * + * - `function foo() {}` + * ^^^^^^^^^^^^ + * - `(function foo() {})` + * ^^^^^^^^^^^^ + * - `(function() {})` + * ^^^^^^^^ + * - `function* foo() {}` + * ^^^^^^^^^^^^^ + * - `(function* foo() {})` + * ^^^^^^^^^^^^^ + * - `(function*() {})` + * ^^^^^^^^^ + * - `() => {}` + * ^^ + * - `async () => {}` + * ^^ + * - `({ foo: function foo() {} })` + * ^^^^^^^^^^^^^^^^^ + * - `({ foo: function() {} })` + * ^^^^^^^^^^^^^ + * - `({ ['foo']: function() {} })` + * ^^^^^^^^^^^^^^^^^ + * - `({ [foo]: function() {} })` + * ^^^^^^^^^^^^^^^ + * - `({ foo() {} })` + * ^^^ + * - `({ foo: function* foo() {} })` + * ^^^^^^^^^^^^^^^^^^ + * - `({ foo: function*() {} })` + * ^^^^^^^^^^^^^^ + * - `({ ['foo']: function*() {} })` + * ^^^^^^^^^^^^^^^^^^ + * - `({ [foo]: function*() {} })` + * ^^^^^^^^^^^^^^^^ + * - `({ *foo() {} })` + * ^^^^ + * - `({ foo: async function foo() {} })` + * ^^^^^^^^^^^^^^^^^^^^^^^ + * - `({ foo: async function() {} })` + * ^^^^^^^^^^^^^^^^^^^ + * - `({ ['foo']: async function() {} })` + * ^^^^^^^^^^^^^^^^^^^^^^^ + * - `({ [foo]: async function() {} })` + * ^^^^^^^^^^^^^^^^^^^^^ + * - `({ async foo() {} })` + * ^^^^^^^^^ + * - `({ get foo() {} })` + * ^^^^^^^ + * - `({ set foo(a) {} })` + * ^^^^^^^ + * - `class A { constructor() {} }` + * ^^^^^^^^^^^ + * - `class A { foo() {} }` + * ^^^ + * - `class A { *foo() {} }` + * ^^^^ + * - `class A { async foo() {} }` + * ^^^^^^^^^ + * - `class A { ['foo']() {} }` + * ^^^^^^^ + * - `class A { *['foo']() {} }` + * ^^^^^^^^ + * - `class A { async ['foo']() {} }` + * ^^^^^^^^^^^^^ + * - `class A { [foo]() {} }` + * ^^^^^ + * - `class A { *[foo]() {} }` + * ^^^^^^ + * - `class A { async [foo]() {} }` + * ^^^^^^^^^^^ + * - `class A { get foo() {} }` + * ^^^^^^^ + * - `class A { set foo(a) {} }` + * ^^^^^^^ + * - `class A { static foo() {} }` + * ^^^^^^^^^^ + * - `class A { static *foo() {} }` + * ^^^^^^^^^^^ + * - `class A { static async foo() {} }` + * ^^^^^^^^^^^^^^^^ + * - `class A { static get foo() {} }` + * ^^^^^^^^^^^^^^ + * - `class A { static set foo(a) {} }` + * ^^^^^^^^^^^^^^ + * + * @param {ASTNode} node - The function node to get. + * @param {SourceCode} sourceCode - The source code object to get tokens. + * @returns {string} The location of the function node for reporting. + */ + getFunctionHeadLoc(node, sourceCode) { + const parent = node.parent; + let start = null; + let end = null; + + if (node.type === "ArrowFunctionExpression") { + const arrowToken = getArrowToken(node, sourceCode); + + start = arrowToken.loc.start; + end = arrowToken.loc.end; + } else if (parent.type === "Property" || parent.type === "MethodDefinition") { + start = parent.loc.start; + end = getOpeningParenOfParams(node, sourceCode).loc.start; + } else { + start = node.loc.start; + end = getOpeningParenOfParams(node, sourceCode).loc.start; + } + + return { + start: Object.assign({}, start), + end: Object.assign({}, end), + }; + }, + + /* + * Converts a range index into a (line, column) pair. + * @param {SourceCode} sourceCode A SourceCode object + * @param {number} rangeIndex The range index of a character in a file + * @returns {Object} A {line, column} location object with a 0-indexed column + */ + getLocationFromRangeIndex(sourceCode, rangeIndex) { + const lineIndices = getLineIndices(sourceCode); + + /* + * lineIndices is a sorted list of indices of the first character of each line. + * To figure out which line rangeIndex is on, determine the last index at which rangeIndex could + * be inserted into lineIndices to keep the list sorted. + */ + const lineNumber = lodash.sortedLastIndex(lineIndices, rangeIndex); + + return { line: lineNumber, column: rangeIndex - lineIndices[lineNumber - 1] }; + + }, + + /** + * Converts a (line, column) pair into a range index. + * @param {SourceCode} sourceCode A SourceCode object + * @param {Object} loc A line/column location + * @param {number} loc.line The line number of the location (1-indexed) + * @param {number} loc.column The column number of the location (0-indexed) + * @returns {number} The range index of the location in the file. + */ + getRangeIndexFromLocation(sourceCode, loc) { + return getLineIndices(sourceCode)[loc.line - 1] + loc.column; + }, + + /** + * Gets the parenthesized text of a node. This is similar to sourceCode.getText(node), but it also includes any parentheses + * surrounding the node. + * @param {SourceCode} sourceCode The source code object + * @param {ASTNode} node An expression node + * @returns {string} The text representing the node, with all surrounding parentheses included + */ + getParenthesisedText(sourceCode, node) { + let leftToken = sourceCode.getFirstToken(node); + let rightToken = sourceCode.getLastToken(node); + + while ( + sourceCode.getTokenBefore(leftToken) && + sourceCode.getTokenBefore(leftToken).type === "Punctuator" && + sourceCode.getTokenBefore(leftToken).value === "(" && + sourceCode.getTokenAfter(rightToken) && + sourceCode.getTokenAfter(rightToken).type === "Punctuator" && + sourceCode.getTokenAfter(rightToken).value === ")" + ) { + leftToken = sourceCode.getTokenBefore(leftToken); + rightToken = sourceCode.getTokenAfter(rightToken); + } + + return sourceCode.getText().slice(leftToken.range[0], rightToken.range[1]); } }; diff --git a/tools/eslint/lib/cli-engine.js b/tools/eslint/lib/cli-engine.js index b9019932fe9b54..de875a4d352926 100644 --- a/tools/eslint/lib/cli-engine.js +++ b/tools/eslint/lib/cli-engine.js @@ -90,7 +90,7 @@ const debug = require("debug")("eslint:cli-engine"); * @private */ function calculateStatsPerFile(messages) { - return messages.reduce(function(stat, message) { + return messages.reduce((stat, message) => { if (message.fatal || message.severity === 2) { stat.errorCount++; } else { @@ -110,7 +110,7 @@ function calculateStatsPerFile(messages) { * @private */ function calculateStatsPerRun(results) { - return results.reduce(function(stat, result) { + return results.reduce((stat, result) => { stat.errorCount += result.errorCount; stat.warningCount += result.warningCount; return stat; @@ -241,7 +241,7 @@ function processText(text, configHelper, filename, fix, allowInlineConfig) { const parsedBlocks = processor.preprocess(text, filename); const unprocessedMessages = []; - parsedBlocks.forEach(function(block) { + parsedBlocks.forEach(block => { unprocessedMessages.push(eslint.verify(block, config, { filename, allowInlineConfig @@ -320,11 +320,11 @@ function createIgnoreResult(filePath, baseDir) { const isInBowerComponents = baseDir && /^bower_components/.test(path.relative(baseDir, filePath)); if (isHidden) { - message = "File ignored by default. Use a negated ignore pattern (like \"--ignore-pattern \'!\'\") to override."; + message = "File ignored by default. Use a negated ignore pattern (like \"--ignore-pattern '!'\") to override."; } else if (isInNodeModules) { - message = "File ignored by default. Use \"--ignore-pattern \'!node_modules/*\'\" to override."; + message = "File ignored by default. Use \"--ignore-pattern '!node_modules/*'\" to override."; } else if (isInBowerComponents) { - message = "File ignored by default. Use \"--ignore-pattern \'!bower_components/*\'\" to override."; + message = "File ignored by default. Use \"--ignore-pattern '!bower_components/*'\" to override."; } else { message = "File ignored because of a matching ignore pattern. Use \"--no-ignore\" to override."; } @@ -442,7 +442,7 @@ function CLIEngine(options) { options = Object.assign( Object.create(null), defaultOptions, - {cwd: process.cwd()}, + { cwd: process.cwd() }, options ); @@ -466,15 +466,15 @@ function CLIEngine(options) { if (this.options.rulePaths) { const cwd = this.options.cwd; - this.options.rulePaths.forEach(function(rulesdir) { + this.options.rulePaths.forEach(rulesdir => { debug(`Loading rules from ${rulesdir}`); rules.load(rulesdir, cwd); }); } - Object.keys(this.options.rules || {}).forEach(function(name) { + Object.keys(this.options.rules || {}).forEach(name => { validator.validateRuleOptions(name, this.options.rules[name], "CLI"); - }.bind(this)); + }); } /** @@ -526,7 +526,7 @@ CLIEngine.getFormatter = function(format) { CLIEngine.getErrorResults = function(results) { const filtered = []; - results.forEach(function(result) { + results.forEach(result => { const filteredMessages = result.messages.filter(isErrorMessage); if (filteredMessages.length > 0) { @@ -549,9 +549,7 @@ CLIEngine.getErrorResults = function(results) { * @returns {void} */ CLIEngine.outputFixes = function(report) { - report.results.filter(function(result) { - return result.hasOwnProperty("output"); - }).forEach(function(result) { + report.results.filter(result => result.hasOwnProperty("output")).forEach(result => { fs.writeFileSync(result.filePath, result.output); }); }; @@ -708,7 +706,7 @@ CLIEngine.prototype = { patterns = this.resolveFileGlobPatterns(patterns); const fileList = globUtil.listFilesToProcess(patterns, options); - fileList.forEach(function(fileInfo) { + fileList.forEach(fileInfo => { executeOnFile(fileInfo.filename, fileInfo.ignored); }); @@ -794,4 +792,6 @@ CLIEngine.prototype = { }; +CLIEngine.version = pkg.version; + module.exports = CLIEngine; diff --git a/tools/eslint/lib/code-path-analysis/code-path-analyzer.js b/tools/eslint/lib/code-path-analysis/code-path-analyzer.js index 655211430b4e2e..cb8b1e1bf8ce8c 100644 --- a/tools/eslint/lib/code-path-analysis/code-path-analyzer.js +++ b/tools/eslint/lib/code-path-analysis/code-path-analyzer.js @@ -569,21 +569,20 @@ function postprocess(analyzer, node) { /** * The class to analyze code paths. * This class implements the EventGenerator interface. - * - * @constructor - * @param {EventGenerator} eventGenerator - An event generator to wrap. */ -function CodePathAnalyzer(eventGenerator) { - this.original = eventGenerator; - this.emitter = eventGenerator.emitter; - this.codePath = null; - this.idGenerator = new IdGenerator("s"); - this.currentNode = null; - this.onLooped = this.onLooped.bind(this); -} +class CodePathAnalyzer { -CodePathAnalyzer.prototype = { - constructor: CodePathAnalyzer, + /** + * @param {EventGenerator} eventGenerator - An event generator to wrap. + */ + constructor(eventGenerator) { + this.original = eventGenerator; + this.emitter = eventGenerator.emitter; + this.codePath = null; + this.idGenerator = new IdGenerator("s"); + this.currentNode = null; + this.onLooped = this.onLooped.bind(this); + } /** * Does the process to enter a given AST node. @@ -608,7 +607,7 @@ CodePathAnalyzer.prototype = { this.original.enterNode(node); this.currentNode = null; - }, + } /** * Does the process to leave a given AST node. @@ -631,7 +630,7 @@ CodePathAnalyzer.prototype = { postprocess(this, node); this.currentNode = null; - }, + } /** * This is called on a code path looped. @@ -652,6 +651,6 @@ CodePathAnalyzer.prototype = { ); } } -}; +} module.exports = CodePathAnalyzer; diff --git a/tools/eslint/lib/code-path-analysis/code-path-segment.js b/tools/eslint/lib/code-path-analysis/code-path-segment.js index b3966c415b0aac..db1eba4560c251 100644 --- a/tools/eslint/lib/code-path-analysis/code-path-segment.js +++ b/tools/eslint/lib/code-path-analysis/code-path-segment.js @@ -68,174 +68,175 @@ function isReachable(segment) { /** * A code path segment. - * - * @constructor - * @param {string} id - An identifier. - * @param {CodePathSegment[]} allPrevSegments - An array of the previous segments. - * This array includes unreachable segments. - * @param {boolean} reachable - A flag which shows this is reachable. */ -function CodePathSegment(id, allPrevSegments, reachable) { +class CodePathSegment { /** - * The identifier of this code path. - * Rules use it to store additional information of each rule. - * @type {string} + * @param {string} id - An identifier. + * @param {CodePathSegment[]} allPrevSegments - An array of the previous segments. + * This array includes unreachable segments. + * @param {boolean} reachable - A flag which shows this is reachable. */ - this.id = id; + constructor(id, allPrevSegments, reachable) { + + /** + * The identifier of this code path. + * Rules use it to store additional information of each rule. + * @type {string} + */ + this.id = id; + + /** + * An array of the next segments. + * @type {CodePathSegment[]} + */ + this.nextSegments = []; + + /** + * An array of the previous segments. + * @type {CodePathSegment[]} + */ + this.prevSegments = allPrevSegments.filter(isReachable); + + /** + * An array of the next segments. + * This array includes unreachable segments. + * @type {CodePathSegment[]} + */ + this.allNextSegments = []; + + /** + * An array of the previous segments. + * This array includes unreachable segments. + * @type {CodePathSegment[]} + */ + this.allPrevSegments = allPrevSegments; + + /** + * A flag which shows this is reachable. + * @type {boolean} + */ + this.reachable = reachable; + + // Internal data. + Object.defineProperty(this, "internal", { + value: { + used: false, + loopedPrevSegments: [] + } + }); - /** - * An array of the next segments. - * @type {CodePathSegment[]} - */ - this.nextSegments = []; + /* istanbul ignore if */ + if (debug.enabled) { + this.internal.nodes = []; + this.internal.exitNodes = []; + } + } /** - * An array of the previous segments. - * @type {CodePathSegment[]} + * Checks a given previous segment is coming from the end of a loop. + * + * @param {CodePathSegment} segment - A previous segment to check. + * @returns {boolean} `true` if the segment is coming from the end of a loop. */ - this.prevSegments = allPrevSegments.filter(isReachable); + isLoopedPrevSegment(segment) { + return this.internal.loopedPrevSegments.indexOf(segment) !== -1; + } /** - * An array of the next segments. - * This array includes unreachable segments. - * @type {CodePathSegment[]} + * Creates the root segment. + * + * @param {string} id - An identifier. + * @returns {CodePathSegment} The created segment. */ - this.allNextSegments = []; + static newRoot(id) { + return new CodePathSegment(id, [], true); + } /** - * An array of the previous segments. - * This array includes unreachable segments. - * @type {CodePathSegment[]} + * Creates a segment that follows given segments. + * + * @param {string} id - An identifier. + * @param {CodePathSegment[]} allPrevSegments - An array of the previous segments. + * @returns {CodePathSegment} The created segment. */ - this.allPrevSegments = allPrevSegments; + static newNext(id, allPrevSegments) { + return new CodePathSegment( + id, + flattenUnusedSegments(allPrevSegments), + allPrevSegments.some(isReachable)); + } /** - * A flag which shows this is reachable. - * @type {boolean} + * Creates an unreachable segment that follows given segments. + * + * @param {string} id - An identifier. + * @param {CodePathSegment[]} allPrevSegments - An array of the previous segments. + * @returns {CodePathSegment} The created segment. */ - this.reachable = reachable; - - // Internal data. - Object.defineProperty(this, "internal", {value: { - used: false, - loopedPrevSegments: [] - }}); - - /* istanbul ignore if */ - if (debug.enabled) { - this.internal.nodes = []; - this.internal.exitNodes = []; - } -} + static newUnreachable(id, allPrevSegments) { + const segment = new CodePathSegment(id, flattenUnusedSegments(allPrevSegments), false); -CodePathSegment.prototype = { - constructor: CodePathSegment, + // In `if (a) return a; foo();` case, the unreachable segment preceded by + // the return statement is not used but must not be remove. + CodePathSegment.markUsed(segment); + + return segment; + } /** - * Checks a given previous segment is coming from the end of a loop. + * Creates a segment that follows given segments. + * This factory method does not connect with `allPrevSegments`. + * But this inherits `reachable` flag. * - * @param {CodePathSegment} segment - A previous segment to check. - * @returns {boolean} `true` if the segment is coming from the end of a loop. + * @param {string} id - An identifier. + * @param {CodePathSegment[]} allPrevSegments - An array of the previous segments. + * @returns {CodePathSegment} The created segment. */ - isLoopedPrevSegment(segment) { - return this.internal.loopedPrevSegments.indexOf(segment) !== -1; + static newDisconnected(id, allPrevSegments) { + return new CodePathSegment(id, [], allPrevSegments.some(isReachable)); } -}; - -/** - * Creates the root segment. - * - * @param {string} id - An identifier. - * @returns {CodePathSegment} The created segment. - */ -CodePathSegment.newRoot = function(id) { - return new CodePathSegment(id, [], true); -}; -/** - * Creates a segment that follows given segments. - * - * @param {string} id - An identifier. - * @param {CodePathSegment[]} allPrevSegments - An array of the previous segments. - * @returns {CodePathSegment} The created segment. - */ -CodePathSegment.newNext = function(id, allPrevSegments) { - return new CodePathSegment( - id, - flattenUnusedSegments(allPrevSegments), - allPrevSegments.some(isReachable)); -}; - -/** - * Creates an unreachable segment that follows given segments. - * - * @param {string} id - An identifier. - * @param {CodePathSegment[]} allPrevSegments - An array of the previous segments. - * @returns {CodePathSegment} The created segment. - */ -CodePathSegment.newUnreachable = function(id, allPrevSegments) { - const segment = new CodePathSegment(id, flattenUnusedSegments(allPrevSegments), false); - - // In `if (a) return a; foo();` case, the unreachable segment preceded by - // the return statement is not used but must not be remove. - CodePathSegment.markUsed(segment); - - return segment; -}; - -/** - * Creates a segment that follows given segments. - * This factory method does not connect with `allPrevSegments`. - * But this inherits `reachable` flag. - * - * @param {string} id - An identifier. - * @param {CodePathSegment[]} allPrevSegments - An array of the previous segments. - * @returns {CodePathSegment} The created segment. - */ -CodePathSegment.newDisconnected = function(id, allPrevSegments) { - return new CodePathSegment(id, [], allPrevSegments.some(isReachable)); -}; - -/** - * Makes a given segment being used. - * - * And this function registers the segment into the previous segments as a next. - * - * @param {CodePathSegment} segment - A segment to mark. - * @returns {void} - */ -CodePathSegment.markUsed = function(segment) { - if (segment.internal.used) { - return; - } - segment.internal.used = true; + /** + * Makes a given segment being used. + * + * And this function registers the segment into the previous segments as a next. + * + * @param {CodePathSegment} segment - A segment to mark. + * @returns {void} + */ + static markUsed(segment) { + if (segment.internal.used) { + return; + } + segment.internal.used = true; - let i; + let i; - if (segment.reachable) { - for (i = 0; i < segment.allPrevSegments.length; ++i) { - const prevSegment = segment.allPrevSegments[i]; + if (segment.reachable) { + for (i = 0; i < segment.allPrevSegments.length; ++i) { + const prevSegment = segment.allPrevSegments[i]; - prevSegment.allNextSegments.push(segment); - prevSegment.nextSegments.push(segment); - } - } else { - for (i = 0; i < segment.allPrevSegments.length; ++i) { - segment.allPrevSegments[i].allNextSegments.push(segment); + prevSegment.allNextSegments.push(segment); + prevSegment.nextSegments.push(segment); + } + } else { + for (i = 0; i < segment.allPrevSegments.length; ++i) { + segment.allPrevSegments[i].allNextSegments.push(segment); + } } } -}; -/** - * Marks a previous segment as looped. - * - * @param {CodePathSegment} segment - A segment. - * @param {CodePathSegment} prevSegment - A previous segment to mark. - * @returns {void} - */ -CodePathSegment.markPrevSegmentAsLooped = function(segment, prevSegment) { - segment.internal.loopedPrevSegments.push(prevSegment); -}; + /** + * Marks a previous segment as looped. + * + * @param {CodePathSegment} segment - A segment. + * @param {CodePathSegment} prevSegment - A previous segment to mark. + * @returns {void} + */ + static markPrevSegmentAsLooped(segment, prevSegment) { + segment.internal.loopedPrevSegments.push(prevSegment); + } +} module.exports = CodePathSegment; diff --git a/tools/eslint/lib/code-path-analysis/code-path-state.js b/tools/eslint/lib/code-path-analysis/code-path-state.js index 3b0b1606e2c993..64779c0d3c8b12 100644 --- a/tools/eslint/lib/code-path-analysis/code-path-state.js +++ b/tools/eslint/lib/code-path-analysis/code-path-state.js @@ -221,36 +221,35 @@ function finalizeTestSegmentsOfFor(context, choiceContext, head) { /** * A class which manages state to analyze code paths. - * - * @constructor - * @param {IdGenerator} idGenerator - An id generator to generate id for code - * path segments. - * @param {Function} onLooped - A callback function to notify looping. */ -function CodePathState(idGenerator, onLooped) { - this.idGenerator = idGenerator; - this.notifyLooped = onLooped; - this.forkContext = ForkContext.newRoot(idGenerator); - this.choiceContext = null; - this.switchContext = null; - this.tryContext = null; - this.loopContext = null; - this.breakContext = null; - - this.currentSegments = []; - this.initialSegment = this.forkContext.head[0]; - - // returnedSegments and thrownSegments push elements into finalSegments also. - const final = this.finalSegments = []; - const returned = this.returnedForkContext = []; - const thrown = this.thrownForkContext = []; - - returned.add = addToReturnedOrThrown.bind(null, returned, thrown, final); - thrown.add = addToReturnedOrThrown.bind(null, thrown, returned, final); -} +class CodePathState { -CodePathState.prototype = { - constructor: CodePathState, + /** + * @param {IdGenerator} idGenerator - An id generator to generate id for code + * path segments. + * @param {Function} onLooped - A callback function to notify looping. + */ + constructor(idGenerator, onLooped) { + this.idGenerator = idGenerator; + this.notifyLooped = onLooped; + this.forkContext = ForkContext.newRoot(idGenerator); + this.choiceContext = null; + this.switchContext = null; + this.tryContext = null; + this.loopContext = null; + this.breakContext = null; + + this.currentSegments = []; + this.initialSegment = this.forkContext.head[ 0 ]; + + // returnedSegments and thrownSegments push elements into finalSegments also. + const final = this.finalSegments = []; + const returned = this.returnedForkContext = []; + const thrown = this.thrownForkContext = []; + + returned.add = addToReturnedOrThrown.bind(null, returned, thrown, final); + thrown.add = addToReturnedOrThrown.bind(null, thrown, returned, final); + } /** * The head segments. @@ -258,7 +257,7 @@ CodePathState.prototype = { */ get headSegments() { return this.forkContext.head; - }, + } /** * The parent forking context. @@ -269,7 +268,7 @@ CodePathState.prototype = { const current = this.forkContext; return current && current.upper; - }, + } /** * Creates and stacks new forking context. @@ -285,7 +284,7 @@ CodePathState.prototype = { ); return this.forkContext; - }, + } /** * Pops and merges the last forking context. @@ -298,7 +297,7 @@ CodePathState.prototype = { this.forkContext.replaceHead(lastContext.makeNext(0, -1)); return lastContext; - }, + } /** * Creates a new path. @@ -306,7 +305,7 @@ CodePathState.prototype = { */ forkPath() { this.forkContext.add(this.parentForkContext.makeNext(-1, -1)); - }, + } /** * Creates a bypass path. @@ -316,7 +315,7 @@ CodePathState.prototype = { */ forkBypassPath() { this.forkContext.add(this.parentForkContext.head); - }, + } //-------------------------------------------------------------------------- // ConditionalExpression, LogicalExpression, IfStatement @@ -362,7 +361,7 @@ CodePathState.prototype = { falseForkContext: ForkContext.newEmpty(this.forkContext), processed: false }; - }, + } /** * Pops the last choice context and finalizes it. @@ -449,7 +448,7 @@ CodePathState.prototype = { forkContext.replaceHead(prevForkContext.makeNext(0, -1)); return context; - }, + } /** * Makes a code path segment of the right-hand operand of a logical @@ -494,7 +493,7 @@ CodePathState.prototype = { forkContext.replaceHead(forkContext.makeNext(-1, -1)); } - }, + } /** * Makes a code path segment of the `if` block. @@ -521,7 +520,7 @@ CodePathState.prototype = { forkContext.replaceHead( context.trueForkContext.makeNext(0, -1) ); - }, + } /** * Makes a code path segment of the `else` block. @@ -544,7 +543,7 @@ CodePathState.prototype = { forkContext.replaceHead( context.falseForkContext.makeNext(0, -1) ); - }, + } //-------------------------------------------------------------------------- // SwitchStatement @@ -570,7 +569,7 @@ CodePathState.prototype = { }; this.pushBreakContext(true, label); - }, + } /** * Pops the last context of SwitchStatement and finalizes it. @@ -649,7 +648,7 @@ CodePathState.prototype = { * This is a path after switch statement. */ this.forkContext.replaceHead(brokenForkContext.makeNext(0, -1)); - }, + } /** * Makes a code path segment for a `SwitchCase` node. @@ -696,7 +695,7 @@ CodePathState.prototype = { context.lastIsDefault = isDefault; context.countForks += 1; - }, + } //-------------------------------------------------------------------------- // TryStatement @@ -723,7 +722,7 @@ CodePathState.prototype = { lastOfTryIsReachable: false, lastOfCatchIsReachable: false }; - }, + } /** * Pops the last context of TryStatement and finalizes it. @@ -777,7 +776,7 @@ CodePathState.prototype = { if (!context.lastOfTryIsReachable && !context.lastOfCatchIsReachable) { this.forkContext.makeUnreachable(); } - }, + } /** * Makes a code path segment for a `catch` block. @@ -802,7 +801,7 @@ CodePathState.prototype = { this.pushForkContext(); this.forkBypassPath(); this.forkContext.add(thrownSegments); - }, + } /** * Makes a code path segment for a `finally` block. @@ -863,7 +862,7 @@ CodePathState.prototype = { this.pushForkContext(true); this.forkContext.add(segments); - }, + } /** * Makes a code path segment from the first throwable node to the `catch` @@ -889,7 +888,7 @@ CodePathState.prototype = { context.thrownForkContext.add(forkContext.head); forkContext.replaceHead(forkContext.makeNext(-1, -1)); - }, + } //-------------------------------------------------------------------------- // Loop Statements @@ -969,7 +968,7 @@ CodePathState.prototype = { default: throw new Error(`unknown type: "${type}"`); } - }, + } /** * Pops the last context of a loop statement and finalizes it. @@ -1039,7 +1038,7 @@ CodePathState.prototype = { } else { forkContext.replaceHead(brokenForkContext.makeNext(0, -1)); } - }, + } /** * Makes a code path segment for the test part of a WhileStatement. @@ -1056,7 +1055,7 @@ CodePathState.prototype = { context.test = test; context.continueDestSegments = testSegments; forkContext.replaceHead(testSegments); - }, + } /** * Makes a code path segment for the body part of a WhileStatement. @@ -1078,7 +1077,7 @@ CodePathState.prototype = { context.brokenForkContext.addAll(choiceContext.falseForkContext); } forkContext.replaceHead(choiceContext.trueForkContext.makeNext(0, -1)); - }, + } /** * Makes a code path segment for the body part of a DoWhileStatement. @@ -1093,7 +1092,7 @@ CodePathState.prototype = { // Update state. context.entrySegments = bodySegments; forkContext.replaceHead(bodySegments); - }, + } /** * Makes a code path segment for the test part of a DoWhileStatement. @@ -1114,7 +1113,7 @@ CodePathState.prototype = { forkContext.replaceHead(testSegments); } - }, + } /** * Makes a code path segment for the test part of a ForStatement. @@ -1133,7 +1132,7 @@ CodePathState.prototype = { context.endOfInitSegments = endOfInitSegments; context.continueDestSegments = context.testSegments = testSegments; forkContext.replaceHead(testSegments); - }, + } /** * Makes a code path segment for the update part of a ForStatement. @@ -1160,7 +1159,7 @@ CodePathState.prototype = { context.continueDestSegments = context.updateSegments = updateSegments; forkContext.replaceHead(updateSegments); - }, + } /** * Makes a code path segment for the body part of a ForStatement. @@ -1211,7 +1210,7 @@ CodePathState.prototype = { } context.continueDestSegments = context.continueDestSegments || bodySegments; forkContext.replaceHead(bodySegments); - }, + } /** * Makes a code path segment for the left part of a ForInStatement and a @@ -1228,7 +1227,7 @@ CodePathState.prototype = { context.prevSegments = forkContext.head; context.leftSegments = context.continueDestSegments = leftSegments; forkContext.replaceHead(leftSegments); - }, + } /** * Makes a code path segment for the right part of a ForInStatement and a @@ -1247,7 +1246,7 @@ CodePathState.prototype = { // Update state. context.endOfLeftSegments = forkContext.head; forkContext.replaceHead(rightSegments); - }, + } /** * Makes a code path segment for the body part of a ForInStatement and a @@ -1269,7 +1268,7 @@ CodePathState.prototype = { // Update state. context.brokenForkContext.add(forkContext.head); forkContext.replaceHead(bodySegments); - }, + } //-------------------------------------------------------------------------- // Control Statements @@ -1291,7 +1290,7 @@ CodePathState.prototype = { brokenForkContext: ForkContext.newEmpty(this.forkContext) }; return this.breakContext; - }, + } /** * Removes the top item of the break context stack. @@ -1315,7 +1314,7 @@ CodePathState.prototype = { } return context; - }, + } /** * Makes a path for a `break` statement. @@ -1341,7 +1340,7 @@ CodePathState.prototype = { } forkContext.replaceHead(forkContext.makeUnreachable(-1, -1)); - }, + } /** * Makes a path for a `continue` statement. @@ -1377,7 +1376,7 @@ CodePathState.prototype = { } } forkContext.replaceHead(forkContext.makeUnreachable(-1, -1)); - }, + } /** * Makes a path for a `return` statement. @@ -1394,7 +1393,7 @@ CodePathState.prototype = { getReturnContext(this).returnedForkContext.add(forkContext.head); forkContext.replaceHead(forkContext.makeUnreachable(-1, -1)); } - }, + } /** * Makes a path for a `throw` statement. @@ -1411,7 +1410,7 @@ CodePathState.prototype = { getThrowContext(this).thrownForkContext.add(forkContext.head); forkContext.replaceHead(forkContext.makeUnreachable(-1, -1)); } - }, + } /** * Makes the final path. @@ -1424,6 +1423,6 @@ CodePathState.prototype = { this.returnedForkContext.add(segments); } } -}; +} module.exports = CodePathState; diff --git a/tools/eslint/lib/code-path-analysis/code-path.js b/tools/eslint/lib/code-path-analysis/code-path.js index 96363423c23ed5..6ef07b4a2d93b2 100644 --- a/tools/eslint/lib/code-path-analysis/code-path.js +++ b/tools/eslint/lib/code-path-analysis/code-path.js @@ -18,47 +18,56 @@ const IdGenerator = require("./id-generator"); /** * A code path. - * - * @constructor - * @param {string} id - An identifier. - * @param {CodePath|null} upper - The code path of the upper function scope. - * @param {Function} onLooped - A callback function to notify looping. */ -function CodePath(id, upper, onLooped) { +class CodePath { /** - * The identifier of this code path. - * Rules use it to store additional information of each rule. - * @type {string} + * @param {string} id - An identifier. + * @param {CodePath|null} upper - The code path of the upper function scope. + * @param {Function} onLooped - A callback function to notify looping. */ - this.id = id; + constructor(id, upper, onLooped) { - /** - * The code path of the upper function scope. - * @type {CodePath|null} - */ - this.upper = upper; + /** + * The identifier of this code path. + * Rules use it to store additional information of each rule. + * @type {string} + */ + this.id = id; - /** - * The code paths of nested function scopes. - * @type {CodePath[]} - */ - this.childCodePaths = []; + /** + * The code path of the upper function scope. + * @type {CodePath|null} + */ + this.upper = upper; + + /** + * The code paths of nested function scopes. + * @type {CodePath[]} + */ + this.childCodePaths = []; - // Initializes internal state. - Object.defineProperty( - this, - "internal", - {value: new CodePathState(new IdGenerator(`${id}_`), onLooped)}); + // Initializes internal state. + Object.defineProperty( + this, + "internal", + { value: new CodePathState(new IdGenerator(`${id}_`), onLooped) }); - // Adds this into `childCodePaths` of `upper`. - if (upper) { - upper.childCodePaths.push(this); + // Adds this into `childCodePaths` of `upper`. + if (upper) { + upper.childCodePaths.push(this); + } } -} -CodePath.prototype = { - constructor: CodePath, + /** + * Gets the state of a given code path. + * + * @param {CodePath} codePath - A code path to get. + * @returns {CodePathState} The state of the code path. + */ + static getState(codePath) { + return codePath.internal; + } /** * The initial code path segment. @@ -66,7 +75,7 @@ CodePath.prototype = { */ get initialSegment() { return this.internal.initialSegment; - }, + } /** * Final code path segments. @@ -75,7 +84,7 @@ CodePath.prototype = { */ get finalSegments() { return this.internal.finalSegments; - }, + } /** * Final code path segments which is with `return` statements. @@ -85,7 +94,7 @@ CodePath.prototype = { */ get returnedSegments() { return this.internal.returnedForkContext; - }, + } /** * Final code path segments which is with `throw` statements. @@ -93,7 +102,7 @@ CodePath.prototype = { */ get thrownSegments() { return this.internal.thrownForkContext; - }, + } /** * Current code path segments. @@ -101,7 +110,7 @@ CodePath.prototype = { */ get currentSegments() { return this.internal.currentSegments; - }, + } /** * Traverses all segments in this code path. @@ -219,16 +228,6 @@ CodePath.prototype = { } } } -}; - -/** - * Gets the state of a given code path. - * - * @param {CodePath} codePath - A code path to get. - * @returns {CodePathState} The state of the code path. - */ -CodePath.getState = function getState(codePath) { - return codePath.internal; -}; +} module.exports = CodePath; diff --git a/tools/eslint/lib/code-path-analysis/debug-helpers.js b/tools/eslint/lib/code-path-analysis/debug-helpers.js index 5e311eb352b986..622bd6081fa546 100644 --- a/tools/eslint/lib/code-path-analysis/debug-helpers.js +++ b/tools/eslint/lib/code-path-analysis/debug-helpers.js @@ -108,7 +108,7 @@ module.exports = { } if (segment.internal.nodes.length > 0) { - text += segment.internal.nodes.map(function(node) { + text += segment.internal.nodes.map(node => { switch (node.type) { case "Identifier": return `${node.type} (${node.name})`; case "Literal": return `${node.type} (${node.value})`; @@ -116,7 +116,7 @@ module.exports = { } }).join("\\n"); } else if (segment.internal.exitNodes.length > 0) { - text += segment.internal.exitNodes.map(function(node) { + text += segment.internal.exitNodes.map(node => { switch (node.type) { case "Identifier": return `${node.type}:exit (${node.name})`; case "Literal": return `${node.type}:exit (${node.value})`; @@ -176,7 +176,7 @@ module.exports = { stack.push([nextSegment, 0]); } - codePath.returnedSegments.forEach(function(finalSegment) { + codePath.returnedSegments.forEach(finalSegment => { if (lastId === finalSegment.id) { text += "->final"; } else { @@ -185,7 +185,7 @@ module.exports = { lastId = null; }); - codePath.thrownSegments.forEach(function(finalSegment) { + codePath.thrownSegments.forEach(finalSegment => { if (lastId === finalSegment.id) { text += "->thrown"; } else { diff --git a/tools/eslint/lib/code-path-analysis/fork-context.js b/tools/eslint/lib/code-path-analysis/fork-context.js index 6996af1dcc1f71..7423c13199b3ff 100644 --- a/tools/eslint/lib/code-path-analysis/fork-context.js +++ b/tools/eslint/lib/code-path-analysis/fork-context.js @@ -99,21 +99,20 @@ function mergeExtraSegments(context, segments) { /** * A class to manage forking. - * - * @constructor - * @param {IdGenerator} idGenerator - An identifier generator for segments. - * @param {ForkContext|null} upper - An upper fork context. - * @param {number} count - A number of parallel segments. */ -function ForkContext(idGenerator, upper, count) { - this.idGenerator = idGenerator; - this.upper = upper; - this.count = count; - this.segmentsList = []; -} +class ForkContext { -ForkContext.prototype = { - constructor: ForkContext, + /** + * @param {IdGenerator} idGenerator - An identifier generator for segments. + * @param {ForkContext|null} upper - An upper fork context. + * @param {number} count - A number of parallel segments. + */ + constructor(idGenerator, upper, count) { + this.idGenerator = idGenerator; + this.upper = upper; + this.count = count; + this.segmentsList = []; + } /** * The head segments. @@ -123,7 +122,7 @@ ForkContext.prototype = { const list = this.segmentsList; return list.length === 0 ? [] : list[list.length - 1]; - }, + } /** * A flag which shows empty. @@ -131,7 +130,7 @@ ForkContext.prototype = { */ get empty() { return this.segmentsList.length === 0; - }, + } /** * A flag which shows reachable. @@ -141,7 +140,7 @@ ForkContext.prototype = { const segments = this.head; return segments.length > 0 && segments.some(isReachable); - }, + } /** * Creates new segments from this context. @@ -152,7 +151,7 @@ ForkContext.prototype = { */ makeNext(begin, end) { return makeSegments(this, begin, end, CodePathSegment.newNext); - }, + } /** * Creates new segments from this context. @@ -164,7 +163,7 @@ ForkContext.prototype = { */ makeUnreachable(begin, end) { return makeSegments(this, begin, end, CodePathSegment.newUnreachable); - }, + } /** * Creates new segments from this context. @@ -177,7 +176,7 @@ ForkContext.prototype = { */ makeDisconnected(begin, end) { return makeSegments(this, begin, end, CodePathSegment.newDisconnected); - }, + } /** * Adds segments into this context. @@ -190,7 +189,7 @@ ForkContext.prototype = { assert(segments.length >= this.count, `${segments.length} >= ${this.count}`); this.segmentsList.push(mergeExtraSegments(this, segments)); - }, + } /** * Replaces the head segments with given segments. @@ -203,7 +202,7 @@ ForkContext.prototype = { assert(segments.length >= this.count, `${segments.length} >= ${this.count}`); this.segmentsList.splice(-1, 1, mergeExtraSegments(this, segments)); - }, + } /** * Adds all segments of a given fork context into this context. @@ -219,7 +218,7 @@ ForkContext.prototype = { for (let i = 0; i < source.length; ++i) { this.segmentsList.push(source[i]); } - }, + } /** * Clears all secments in this context. @@ -229,34 +228,34 @@ ForkContext.prototype = { clear() { this.segmentsList = []; } -}; -/** - * Creates the root fork context. - * - * @param {IdGenerator} idGenerator - An identifier generator for segments. - * @returns {ForkContext} New fork context. - */ -ForkContext.newRoot = function(idGenerator) { - const context = new ForkContext(idGenerator, null, 1); + /** + * Creates the root fork context. + * + * @param {IdGenerator} idGenerator - An identifier generator for segments. + * @returns {ForkContext} New fork context. + */ + static newRoot(idGenerator) { + const context = new ForkContext(idGenerator, null, 1); - context.add([CodePathSegment.newRoot(idGenerator.next())]); + context.add([CodePathSegment.newRoot(idGenerator.next())]); - return context; -}; + return context; + } -/** - * Creates an empty fork context preceded by a given context. - * - * @param {ForkContext} parentContext - The parent fork context. - * @param {boolean} forkLeavingPath - A flag which shows inside of `finally` block. - * @returns {ForkContext} New fork context. - */ -ForkContext.newEmpty = function(parentContext, forkLeavingPath) { - return new ForkContext( - parentContext.idGenerator, - parentContext, - (forkLeavingPath ? 2 : 1) * parentContext.count); -}; + /** + * Creates an empty fork context preceded by a given context. + * + * @param {ForkContext} parentContext - The parent fork context. + * @param {boolean} forkLeavingPath - A flag which shows inside of `finally` block. + * @returns {ForkContext} New fork context. + */ + static newEmpty(parentContext, forkLeavingPath) { + return new ForkContext( + parentContext.idGenerator, + parentContext, + (forkLeavingPath ? 2 : 1) * parentContext.count); + } +} module.exports = ForkContext; diff --git a/tools/eslint/lib/code-path-analysis/id-generator.js b/tools/eslint/lib/code-path-analysis/id-generator.js index f33858cacd4071..062058ddc12639 100644 --- a/tools/eslint/lib/code-path-analysis/id-generator.js +++ b/tools/eslint/lib/code-path-analysis/id-generator.js @@ -15,29 +15,32 @@ /** * A generator for unique ids. - * - * @constructor - * @param {string} prefix - Optional. A prefix of generated ids. - */ -function IdGenerator(prefix) { - this.prefix = String(prefix); - this.n = 0; -} - -/** - * Generates id. - * - * @returns {string} A generated id. */ -IdGenerator.prototype.next = function() { - this.n = 1 + this.n | 0; +class IdGenerator { - /* istanbul ignore if */ - if (this.n < 0) { - this.n = 1; + /** + * @param {string} prefix - Optional. A prefix of generated ids. + */ + constructor(prefix) { + this.prefix = String(prefix); + this.n = 0; } - return this.prefix + this.n; -}; + /** + * Generates id. + * + * @returns {string} A generated id. + */ + next() { + this.n = 1 + this.n | 0; + + /* istanbul ignore if */ + if (this.n < 0) { + this.n = 1; + } + + return this.prefix + this.n; + } +} module.exports = IdGenerator; diff --git a/tools/eslint/lib/config.js b/tools/eslint/lib/config.js index 9ff203c16d9e45..9c56e7ad988e28 100644 --- a/tools/eslint/lib/config.js +++ b/tools/eslint/lib/config.js @@ -179,155 +179,159 @@ function getLocalConfig(thisConfig, directory) { //------------------------------------------------------------------------------ /** - * Config - * @constructor - * @class Config - * @param {Object} options Options to be passed in + * Configuration class */ -function Config(options) { - options = options || {}; +class Config { - this.ignore = options.ignore; - this.ignorePath = options.ignorePath; - this.cache = {}; - this.parser = options.parser; - this.parserOptions = options.parserOptions || {}; + /** + * Config options + * @param {Object} options Options to be passed in + */ + constructor(options) { + options = options || {}; - this.baseConfig = options.baseConfig ? loadConfig(options.baseConfig) : { rules: {} }; + this.ignore = options.ignore; + this.ignorePath = options.ignorePath; + this.cache = {}; + this.parser = options.parser; + this.parserOptions = options.parserOptions || {}; - this.useEslintrc = (options.useEslintrc !== false); + this.baseConfig = options.baseConfig ? loadConfig(options.baseConfig) : { rules: {} }; - this.env = (options.envs || []).reduce(function(envs, name) { - envs[name] = true; - return envs; - }, {}); + this.useEslintrc = (options.useEslintrc !== false); - /* - * Handle declared globals. - * For global variable foo, handle "foo:false" and "foo:true" to set - * whether global is writable. - * If user declares "foo", convert to "foo:false". - */ - this.globals = (options.globals || []).reduce(function(globals, def) { - const parts = def.split(":"); + this.env = (options.envs || []).reduce((envs, name) => { + envs[ name ] = true; + return envs; + }, {}); - globals[parts[0]] = (parts.length > 1 && parts[1] === "true"); + /* + * Handle declared globals. + * For global variable foo, handle "foo:false" and "foo:true" to set + * whether global is writable. + * If user declares "foo", convert to "foo:false". + */ + this.globals = (options.globals || []).reduce((globals, def) => { + const parts = def.split(":"); - return globals; - }, {}); + globals[parts[0]] = (parts.length > 1 && parts[1] === "true"); - const useConfig = options.configFile; + return globals; + }, {}); - this.options = options; + const useConfig = options.configFile; - if (useConfig) { - debug(`Using command line config ${useConfig}`); - if (isResolvable(useConfig) || isResolvable(`eslint-config-${useConfig}`) || useConfig.charAt(0) === "@") { - this.useSpecificConfig = loadConfig(useConfig); - } else { - this.useSpecificConfig = loadConfig(path.resolve(this.options.cwd, useConfig)); + this.options = options; + + if (useConfig) { + debug(`Using command line config ${useConfig}`); + if (isResolvable(useConfig) || isResolvable(`eslint-config-${useConfig}`) || useConfig.charAt(0) === "@") { + this.useSpecificConfig = loadConfig(useConfig); + } else { + this.useSpecificConfig = loadConfig(path.resolve(this.options.cwd, useConfig)); + } } } -} -/** - * Build a config object merging the base config (conf/eslint.json), the - * environments config (conf/environments.js) and eventually the user config. - * @param {string} filePath a file in whose directory we start looking for a local config - * @returns {Object} config object - */ -Config.prototype.getConfig = function(filePath) { - const directory = filePath ? path.dirname(filePath) : this.options.cwd; - let config, - userConfig; + /** + * Build a config object merging the base config (conf/eslint.json), the + * environments config (conf/environments.js) and eventually the user config. + * @param {string} filePath a file in whose directory we start looking for a local config + * @returns {Object} config object + */ + getConfig(filePath) { + const directory = filePath ? path.dirname(filePath) : this.options.cwd; + let config, + userConfig; - debug(`Constructing config for ${filePath ? filePath : "text"}`); + debug(`Constructing config for ${filePath ? filePath : "text"}`); - config = this.cache[directory]; + config = this.cache[directory]; - if (config) { - debug("Using config from cache"); - return config; - } + if (config) { + debug("Using config from cache"); + return config; + } - // Step 1: Determine user-specified config from .eslintrc.* and package.json files - if (this.useEslintrc) { - debug("Using .eslintrc and package.json files"); - userConfig = getLocalConfig(this, directory); - } else { - debug("Not using .eslintrc or package.json files"); - userConfig = {}; - } + // Step 1: Determine user-specified config from .eslintrc.* and package.json files + if (this.useEslintrc) { + debug("Using .eslintrc and package.json files"); + userConfig = getLocalConfig(this, directory); + } else { + debug("Not using .eslintrc or package.json files"); + userConfig = {}; + } - // Step 2: Create a copy of the baseConfig - config = ConfigOps.merge({}, this.baseConfig); + // Step 2: Create a copy of the baseConfig + config = ConfigOps.merge({}, this.baseConfig); - // Step 3: Merge in the user-specified configuration from .eslintrc and package.json - config = ConfigOps.merge(config, userConfig); + // Step 3: Merge in the user-specified configuration from .eslintrc and package.json + config = ConfigOps.merge(config, userConfig); - // Step 4: Merge in command line config file - if (this.useSpecificConfig) { - debug("Merging command line config file"); + // Step 4: Merge in command line config file + if (this.useSpecificConfig) { + debug("Merging command line config file"); - config = ConfigOps.merge(config, this.useSpecificConfig); - } + config = ConfigOps.merge(config, this.useSpecificConfig); + } - // Step 5: Merge in command line environments - debug("Merging command line environment settings"); - config = ConfigOps.merge(config, { env: this.env }); + // Step 5: Merge in command line environments + debug("Merging command line environment settings"); + config = ConfigOps.merge(config, { env: this.env }); - // Step 6: Merge in command line rules - if (this.options.rules) { - debug("Merging command line rules"); - config = ConfigOps.merge(config, { rules: this.options.rules }); - } + // Step 6: Merge in command line rules + if (this.options.rules) { + debug("Merging command line rules"); + config = ConfigOps.merge(config, { rules: this.options.rules }); + } - // Step 7: Merge in command line globals - config = ConfigOps.merge(config, { globals: this.globals }); + // Step 7: Merge in command line globals + config = ConfigOps.merge(config, { globals: this.globals }); - // Only override parser if it is passed explicitly through the command line or if it's not - // defined yet (because the final object will at least have the parser key) - if (this.parser || !config.parser) { - config = ConfigOps.merge(config, { - parser: this.parser - }); - } + // Only override parser if it is passed explicitly through the command line or if it's not + // defined yet (because the final object will at least have the parser key) + if (this.parser || !config.parser) { + config = ConfigOps.merge(config, { + parser: this.parser + }); + } - if (this.parserOptions) { - config = ConfigOps.merge(config, { - parserOptions: this.parserOptions - }); - } + if (this.parserOptions) { + config = ConfigOps.merge(config, { + parserOptions: this.parserOptions + }); + } - // Step 8: Merge in command line plugins - if (this.options.plugins) { - debug("Merging command line plugins"); - Plugins.loadAll(this.options.plugins); - config = ConfigOps.merge(config, { plugins: this.options.plugins }); - } + // Step 8: Merge in command line plugins + if (this.options.plugins) { + debug("Merging command line plugins"); + Plugins.loadAll(this.options.plugins); + config = ConfigOps.merge(config, { plugins: this.options.plugins }); + } - // Step 9: Apply environments to the config if present - if (config.env) { - config = ConfigOps.applyEnvironments(config); - } + // Step 9: Apply environments to the config if present + if (config.env) { + config = ConfigOps.applyEnvironments(config); + } - this.cache[directory] = config; + this.cache[directory] = config; - return config; -}; + return config; + } -/** - * Find local config files from directory and parent directories. - * @param {string} directory The directory to start searching from. - * @returns {string[]} The paths of local config files found. - */ -Config.prototype.findLocalConfigFiles = function(directory) { + /** + * Find local config files from directory and parent directories. + * @param {string} directory The directory to start searching from. + * @returns {string[]} The paths of local config files found. + */ + findLocalConfigFiles(directory) { - if (!this.localConfigFinder) { - this.localConfigFinder = new FileFinder(ConfigFile.CONFIG_FILES, this.options.cwd); - } + if (!this.localConfigFinder) { + this.localConfigFinder = new FileFinder(ConfigFile.CONFIG_FILES, this.options.cwd); + } - return this.localConfigFinder.findAllInDirectoryAndParents(directory); -}; + return this.localConfigFinder.findAllInDirectoryAndParents(directory); + } +} module.exports = Config; diff --git a/tools/eslint/lib/config/autoconfig.js b/tools/eslint/lib/config/autoconfig.js index dd25bcd49191bc..23fdbe69803afc 100644 --- a/tools/eslint/lib/config/autoconfig.js +++ b/tools/eslint/lib/config/autoconfig.js @@ -49,14 +49,12 @@ const MAX_CONFIG_COMBINATIONS = 17, // 16 combinations + 1 for severity only * @returns {Object} registryItems for each rule in provided rulesConfig */ function makeRegistryItems(rulesConfig) { - return Object.keys(rulesConfig).reduce(function(accumulator, ruleId) { - accumulator[ruleId] = rulesConfig[ruleId].map(function(config) { - return { - config, - specificity: config.length || 1, - errorCount: void 0 - }; - }); + return Object.keys(rulesConfig).reduce((accumulator, ruleId) => { + accumulator[ruleId] = rulesConfig[ruleId].map(config => ({ + config, + specificity: config.length || 1, + errorCount: void 0 + })); return accumulator; }, {}); } @@ -173,10 +171,8 @@ Registry.prototype = { newRegistry = new Registry(); newRegistry.rules = Object.assign({}, this.rules); - ruleIds.forEach(function(ruleId) { - const errorFreeItems = newRegistry.rules[ruleId].filter(function(registryItem) { - return (registryItem.errorCount === 0); - }); + ruleIds.forEach(ruleId => { + const errorFreeItems = newRegistry.rules[ruleId].filter(registryItem => (registryItem.errorCount === 0)); if (errorFreeItems.length > 0) { newRegistry.rules[ruleId] = errorFreeItems; @@ -198,10 +194,8 @@ Registry.prototype = { newRegistry = new Registry(); newRegistry.rules = Object.assign({}, this.rules); - ruleIds.forEach(function(ruleId) { - newRegistry.rules[ruleId] = newRegistry.rules[ruleId].filter(function(registryItem) { - return (typeof registryItem.errorCount !== "undefined"); - }); + ruleIds.forEach(ruleId => { + newRegistry.rules[ruleId] = newRegistry.rules[ruleId].filter(registryItem => (typeof registryItem.errorCount !== "undefined")); }); return newRegistry; @@ -218,15 +212,13 @@ Registry.prototype = { const ruleIds = Object.keys(this.rules), failingRegistry = new Registry(); - ruleIds.forEach(function(ruleId) { - const failingConfigs = this.rules[ruleId].filter(function(registryItem) { - return (registryItem.errorCount > 0); - }); + ruleIds.forEach(ruleId => { + const failingConfigs = this.rules[ruleId].filter(registryItem => (registryItem.errorCount > 0)); if (failingConfigs && failingConfigs.length === this.rules[ruleId].length) { failingRegistry.rules[ruleId] = failingConfigs; } - }.bind(this)); + }); return failingRegistry; }, @@ -239,13 +231,13 @@ Registry.prototype = { */ createConfig() { const ruleIds = Object.keys(this.rules), - config = {rules: {}}; + config = { rules: {} }; - ruleIds.forEach(function(ruleId) { + ruleIds.forEach(ruleId => { if (this.rules[ruleId].length === 1) { config.rules[ruleId] = this.rules[ruleId][0].config; } - }.bind(this)); + }); return config; }, @@ -261,11 +253,9 @@ Registry.prototype = { newRegistry = new Registry(); newRegistry.rules = Object.assign({}, this.rules); - ruleIds.forEach(function(ruleId) { - newRegistry.rules[ruleId] = this.rules[ruleId].filter(function(registryItem) { - return (registryItem.specificity === specificity); - }); - }.bind(this)); + ruleIds.forEach(ruleId => { + newRegistry.rules[ruleId] = this.rules[ruleId].filter(registryItem => (registryItem.specificity === specificity)); + }); return newRegistry; }, @@ -294,16 +284,16 @@ Registry.prototype = { const filenames = Object.keys(sourceCodes); const totalFilesLinting = filenames.length * ruleSets.length; - filenames.forEach(function(filename) { + filenames.forEach(filename => { debug(`Linting file: ${filename}`); ruleSetIdx = 0; - ruleSets.forEach(function(ruleSet) { - const lintConfig = Object.assign({}, config, {rules: ruleSet}); + ruleSets.forEach(ruleSet => { + const lintConfig = Object.assign({}, config, { rules: ruleSet }); const lintResults = eslint.verify(sourceCodes[filename], lintConfig); - lintResults.forEach(function(result) { + lintResults.forEach(result => { // It is possible that the error is from a configuration comment // in a linted file, in which case there may not be a config @@ -342,11 +332,9 @@ function extendFromRecommended(config) { ConfigOps.normalizeToStrings(newConfig); - const recRules = Object.keys(recConfig.rules).filter(function(ruleId) { - return ConfigOps.isErrorSeverity(recConfig.rules[ruleId]); - }); + const recRules = Object.keys(recConfig.rules).filter(ruleId => ConfigOps.isErrorSeverity(recConfig.rules[ruleId])); - recRules.forEach(function(ruleId) { + recRules.forEach(ruleId => { if (lodash.isEqual(recConfig.rules[ruleId], newConfig.rules[ruleId])) { delete newConfig.rules[ruleId]; } diff --git a/tools/eslint/lib/config/config-file.js b/tools/eslint/lib/config/config-file.js index c11a55fad8413d..90015097a3db97 100644 --- a/tools/eslint/lib/config/config-file.js +++ b/tools/eslint/lib/config/config-file.js @@ -235,7 +235,7 @@ function loadConfigFile(file) { function writeJSONConfigFile(config, filePath) { debug(`Writing JSON config file: ${filePath}`); - const content = stringify(config, {cmp: sortByKey, space: 4}); + const content = stringify(config, { cmp: sortByKey, space: 4 }); fs.writeFileSync(filePath, content, "utf8"); } @@ -253,7 +253,7 @@ function writeYAMLConfigFile(config, filePath) { // lazy load YAML to improve performance when not used const yaml = require("js-yaml"); - const content = yaml.safeDump(config, {sortKeys: true}); + const content = yaml.safeDump(config, { sortKeys: true }); fs.writeFileSync(filePath, content, "utf8"); } @@ -268,7 +268,7 @@ function writeYAMLConfigFile(config, filePath) { function writeJSConfigFile(config, filePath) { debug(`Writing JS config file: ${filePath}`); - const content = `module.exports = ${stringify(config, {cmp: sortByKey, space: 4})};`; + const content = `module.exports = ${stringify(config, { cmp: sortByKey, space: 4 })};`; fs.writeFileSync(filePath, content, "utf8"); } @@ -359,7 +359,7 @@ function applyExtends(config, filePath, relativeTo) { } // Make the last element in an array take the highest precedence - config = configExtends.reduceRight(function(previousValue, parentPath) { + config = configExtends.reduceRight((previousValue, parentPath) => { if (parentPath === "eslint:recommended") { @@ -430,7 +430,7 @@ function normalizePackageName(name, prefix) { * it's a scoped package * package name is "eslint-config", or just a username */ - const scopedPackageShortcutRegex = new RegExp(`^(@[^\/]+)(?:\/(?:${prefix})?)?$`), + const scopedPackageShortcutRegex = new RegExp(`^(@[^/]+)(?:/(?:${prefix})?)?$`), scopedPackageNameRegex = new RegExp(`^${prefix}(-|$)`); if (scopedPackageShortcutRegex.test(name)) { @@ -441,7 +441,7 @@ function normalizePackageName(name, prefix) { * for scoped packages, insert the eslint-config after the first / unless * the path is already @scope/eslint or @scope/eslint-config-xxx */ - name = name.replace(/^@([^\/]+)\/(.*)$/, `@$1/${prefix}-$2`); + name = name.replace(/^@([^/]+)\/(.*)$/, `@$1/${prefix}-$2`); } } else if (name.indexOf(`${prefix}-`) !== 0) { name = `${prefix}-${name}`; diff --git a/tools/eslint/lib/config/config-initializer.js b/tools/eslint/lib/config/config-initializer.js index e3aef07baef388..502a73bd6c3ed1 100644 --- a/tools/eslint/lib/config/config-initializer.js +++ b/tools/eslint/lib/config/config-initializer.js @@ -44,10 +44,14 @@ function writeFile(config, format) { extname = ".json"; } + const installedESLint = config.installedESLint; + + delete config.installedESLint; + ConfigFile.write(config, `./.eslintrc${extname}`); log.info(`Successfully created .eslintrc${extname} file in ${process.cwd()}`); - if (config.installedESLint) { + if (installedESLint) { log.info("ESLint was installed locally. We recommend using this local copy instead of your globally-installed copy."); } } @@ -62,9 +66,7 @@ function installModules(config) { // Create a list of modules which should be installed based on config if (config.plugins) { - modules = modules.concat(config.plugins.map(function(name) { - return `eslint-plugin-${name}`; - })); + modules = modules.concat(config.plugins.map(name => `eslint-plugin-${name}`)); } if (config.extends && config.extends.indexOf("eslint:") === -1) { modules.push(`eslint-config-${config.extends}`); @@ -81,7 +83,7 @@ function installModules(config) { const installStatus = npmUtil.checkDevDeps(modules); // Install packages which aren't already installed - const modulesToInstall = Object.keys(installStatus).filter(function(module) { + const modulesToInstall = Object.keys(installStatus).filter(module => { const notInstalled = installStatus[module] === false; if (module === "eslint" && notInstalled) { @@ -128,7 +130,7 @@ function configureRules(answers, config) { const patterns = answers.patterns.split(/[\s]+/); try { - sourceCodes = getSourceCodeOfFiles(patterns, { baseConfig: newConfig, useEslintrc: false }, function(total) { + sourceCodes = getSourceCodeOfFiles(patterns, { baseConfig: newConfig, useEslintrc: false }, total => { bar.tick((BAR_SOURCE_CODE_TOTAL / total)); }); } catch (e) { @@ -147,20 +149,18 @@ function configureRules(answers, config) { registry.populateFromCoreRules(); // Lint all files with each rule config in the registry - registry = registry.lintSourceCode(sourceCodes, newConfig, function(total) { + registry = registry.lintSourceCode(sourceCodes, newConfig, total => { bar.tick((BAR_TOTAL - BAR_SOURCE_CODE_TOTAL) / total); // Subtract out ticks used at beginning }); - debug(`\nRegistry: ${util.inspect(registry.rules, {depth: null})}`); + debug(`\nRegistry: ${util.inspect(registry.rules, { depth: null })}`); // Create a list of recommended rules, because we don't want to disable them - const recRules = Object.keys(recConfig.rules).filter(function(ruleId) { - return ConfigOps.isErrorSeverity(recConfig.rules[ruleId]); - }); + const recRules = Object.keys(recConfig.rules).filter(ruleId => ConfigOps.isErrorSeverity(recConfig.rules[ruleId])); // Find and disable rules which had no error-free configuration const failingRegistry = registry.getFailingRulesRegistry(); - Object.keys(failingRegistry.rules).forEach(function(ruleId) { + Object.keys(failingRegistry.rules).forEach(ruleId => { // If the rule is recommended, set it to error, otherwise disable it disabledConfigs[ruleId] = (recRules.indexOf(ruleId) !== -1) ? 2 : 0; @@ -194,9 +194,7 @@ function configureRules(answers, config) { // Log out some stats to let the user know what happened const finalRuleIds = Object.keys(newConfig.rules); const totalRules = finalRuleIds.length; - const enabledRules = finalRuleIds.filter(function(ruleId) { - return (newConfig.rules[ruleId] !== 0); - }).length; + const enabledRules = finalRuleIds.filter(ruleId => (newConfig.rules[ruleId] !== 0)).length; const resultMessage = [ `\nEnabled ${enabledRules} out of ${totalRules}`, `rules based on ${fileQty}`, @@ -215,7 +213,7 @@ function configureRules(answers, config) { * @returns {Object} config object */ function processAnswers(answers) { - let config = {rules: {}, env: {}}; + let config = { rules: {}, env: {} }; if (answers.es6) { config.env.es6 = true; @@ -227,7 +225,7 @@ function processAnswers(answers) { if (answers.commonjs) { config.env.commonjs = true; } - answers.env.forEach(function(env) { + answers.env.forEach(env => { config.env[env] = true; }); if (answers.jsx) { @@ -266,9 +264,10 @@ function processAnswers(answers) { */ function getConfigForStyleGuide(guide) { const guides = { - google: {extends: "google"}, - airbnb: {extends: "airbnb", plugins: ["react", "jsx-a11y", "import"]}, - standard: {extends: "standard", plugins: ["standard", "promise"]} + google: { extends: "google" }, + airbnb: { extends: "airbnb", plugins: ["react", "jsx-a11y", "import"] }, + "airbnb-base": { extends: "airbnb-base", plugins: ["import"] }, + standard: { extends: "standard", plugins: ["standard", "promise"] } }; if (!guides[guide]) { @@ -296,21 +295,30 @@ function promptUser(callback) { message: "How would you like to configure ESLint?", default: "prompt", choices: [ - {name: "Answer questions about your style", value: "prompt"}, - {name: "Use a popular style guide", value: "guide"}, - {name: "Inspect your JavaScript file(s)", value: "auto"} + { name: "Answer questions about your style", value: "prompt" }, + { name: "Use a popular style guide", value: "guide" }, + { name: "Inspect your JavaScript file(s)", value: "auto" } ] }, { type: "list", name: "styleguide", message: "Which style guide do you want to follow?", - choices: [{name: "Google", value: "google"}, {name: "Airbnb", value: "airbnb"}, {name: "Standard", value: "standard"}], + choices: [{ name: "Google", value: "google" }, { name: "Airbnb", value: "airbnb" }, { name: "Standard", value: "standard" }], when(answers) { answers.packageJsonExists = npmUtil.checkPackageJson(); return answers.source === "guide" && answers.packageJsonExists; } }, + { + type: "confirm", + name: "airbnbReact", + message: "Do you use React?", + default: false, + when(answers) { + return answers.styleguide === "airbnb"; + }, + }, { type: "input", name: "patterns", @@ -335,7 +343,7 @@ function promptUser(callback) { return ((answers.source === "guide" && answers.packageJsonExists) || answers.source === "auto"); } } - ], function(earlyAnswers) { + ], earlyAnswers => { // early exit if you are using a style guide if (earlyAnswers.source === "guide") { @@ -343,7 +351,9 @@ function promptUser(callback) { log.info("A package.json is necessary to install plugins such as style guides. Run `npm init` to create a package.json file and try again."); return; } - + if (earlyAnswers.styleguide === "airbnb" && !earlyAnswers.airbnbReact) { + earlyAnswers.styleguide = "airbnb-base"; + } try { config = getConfigForStyleGuide(earlyAnswers.styleguide); writeFile(config, earlyAnswers.format); @@ -376,7 +386,7 @@ function promptUser(callback) { name: "env", message: "Where will your code run?", default: ["browser"], - choices: [{name: "Browser", value: "browser"}, {name: "Node", value: "node"}] + choices: [{ name: "Browser", value: "browser" }, { name: "Node", value: "node" }] }, { type: "confirm", @@ -384,9 +394,7 @@ function promptUser(callback) { message: "Do you use CommonJS?", default: false, when(answers) { - return answers.env.some(function(env) { - return env === "browser"; - }); + return answers.env.some(env => env === "browser"); } }, { @@ -398,13 +406,13 @@ function promptUser(callback) { { type: "confirm", name: "react", - message: "Do you use React", + message: "Do you use React?", default: false, when(answers) { return answers.jsx; } } - ], function(secondAnswers) { + ], secondAnswers => { // early exit if you are using automatic style generation if (earlyAnswers.source === "auto") { @@ -428,21 +436,21 @@ function promptUser(callback) { name: "indent", message: "What style of indentation do you use?", default: "tab", - choices: [{name: "Tabs", value: "tab"}, {name: "Spaces", value: 4}] + choices: [{ name: "Tabs", value: "tab" }, { name: "Spaces", value: 4 }] }, { type: "list", name: "quotes", message: "What quotes do you use for strings?", default: "double", - choices: [{name: "Double", value: "double"}, {name: "Single", value: "single"}] + choices: [{ name: "Double", value: "double" }, { name: "Single", value: "single" }] }, { type: "list", name: "linebreak", message: "What line endings do you use?", default: "unix", - choices: [{name: "Unix", value: "unix"}, {name: "Windows", value: "windows"}] + choices: [{ name: "Unix", value: "unix" }, { name: "Windows", value: "windows" }] }, { type: "confirm", @@ -457,7 +465,7 @@ function promptUser(callback) { default: "JavaScript", choices: ["JavaScript", "YAML", "JSON"] } - ], function(answers) { + ], answers => { try { const totalAnswers = Object.assign({}, earlyAnswers, secondAnswers, answers); @@ -465,10 +473,8 @@ function promptUser(callback) { installModules(config); writeFile(config, answers.format); } catch (err) { - callback(err); - return; + callback(err); // eslint-disable-line callback-return } - return; }); }); }); diff --git a/tools/eslint/lib/config/config-ops.js b/tools/eslint/lib/config/config-ops.js index 42b0fe81b90615..52dea1a106df79 100644 --- a/tools/eslint/lib/config/config-ops.js +++ b/tools/eslint/lib/config/config-ops.js @@ -18,7 +18,7 @@ const debug = require("debug")("eslint:config-ops"); //------------------------------------------------------------------------------ const RULE_SEVERITY_STRINGS = ["off", "warn", "error"], - RULE_SEVERITY = RULE_SEVERITY_STRINGS.reduce(function(map, value, index) { + RULE_SEVERITY = RULE_SEVERITY_STRINGS.reduce((map, value, index) => { map[value] = index; return map; }, {}), @@ -57,9 +57,7 @@ module.exports = { envConfig.env = env; - Object.keys(env).filter(function(name) { - return env[name]; - }).forEach(function(name) { + Object.keys(env).filter(name => env[name]).forEach(name => { const environment = Environments.get(name); if (environment) { @@ -149,7 +147,7 @@ module.exports = { if (typeof src !== "object" && !Array.isArray(src)) { src = [src]; } - Object.keys(src).forEach(function(e, i) { + Object.keys(src).forEach((e, i) => { e = src[i]; if (typeof dst[i] === "undefined") { dst[i] = e; @@ -171,11 +169,11 @@ module.exports = { }); } else { if (target && typeof target === "object") { - Object.keys(target).forEach(function(key) { + Object.keys(target).forEach(key => { dst[key] = target[key]; }); } - Object.keys(src).forEach(function(key) { + Object.keys(src).forEach(key => { if (Array.isArray(src[key]) || Array.isArray(target[key])) { dst[key] = deepmerge(target[key], src[key], key === "plugins", isRule); } else if (typeof src[key] !== "object" || !src[key] || key === "exported" || key === "astGlobals") { @@ -199,7 +197,7 @@ module.exports = { normalize(config) { if (config.rules) { - Object.keys(config.rules).forEach(function(ruleId) { + Object.keys(config.rules).forEach(ruleId => { const ruleConfig = config.rules[ruleId]; if (typeof ruleConfig === "string") { @@ -221,7 +219,7 @@ module.exports = { normalizeToStrings(config) { if (config.rules) { - Object.keys(config.rules).forEach(function(ruleId) { + Object.keys(config.rules).forEach(ruleId => { const ruleConfig = config.rules[ruleId]; if (typeof ruleConfig === "number") { @@ -269,8 +267,6 @@ module.exports = { * @returns {boolean} `true` if the configuration has valid severity. */ isEverySeverityValid(config) { - return Object.keys(config).every(function(ruleId) { - return this.isValidSeverity(config[ruleId]); - }, this); + return Object.keys(config).every(ruleId => this.isValidSeverity(config[ruleId])); } }; diff --git a/tools/eslint/lib/config/config-rule.js b/tools/eslint/lib/config/config-rule.js index eb5c23fe8c840a..d495198aed454b 100644 --- a/tools/eslint/lib/config/config-rule.js +++ b/tools/eslint/lib/config/config-rule.js @@ -23,7 +23,7 @@ const rules = require("../rules"), * @returns {Array[]} An array of arrays. */ function explodeArray(xs) { - return xs.reduce(function(accumulator, x) { + return xs.reduce((accumulator, x) => { accumulator.push([x]); return accumulator; }, []); @@ -49,8 +49,8 @@ function combineArrays(arr1, arr2) { if (arr2.length === 0) { return explodeArray(arr1); } - arr1.forEach(function(x1) { - arr2.forEach(function(x2) { + arr1.forEach(x1 => { + arr2.forEach(x2 => { res.push([].concat(x1, x2)); }); }); @@ -78,16 +78,14 @@ function combineArrays(arr1, arr2) { * @returns {Array[]} Array of arrays of objects grouped by property */ function groupByProperty(objects) { - const groupedObj = objects.reduce(function(accumulator, obj) { + const groupedObj = objects.reduce((accumulator, obj) => { const prop = Object.keys(obj)[0]; accumulator[prop] = accumulator[prop] ? accumulator[prop].concat(obj) : [obj]; return accumulator; }, {}); - return Object.keys(groupedObj).map(function(prop) { - return groupedObj[prop]; - }); + return Object.keys(groupedObj).map(prop => groupedObj[prop]); } @@ -152,16 +150,16 @@ function combinePropertyObjects(objArr1, objArr2) { if (objArr2.length === 0) { return objArr1; } - objArr1.forEach(function(obj1) { - objArr2.forEach(function(obj2) { + objArr1.forEach(obj1 => { + objArr2.forEach(obj2 => { const combinedObj = {}; const obj1Props = Object.keys(obj1); const obj2Props = Object.keys(obj2); - obj1Props.forEach(function(prop1) { + obj1Props.forEach(prop1 => { combinedObj[prop1] = obj1[prop1]; }); - obj2Props.forEach(function(prop2) { + obj2Props.forEach(prop2 => { combinedObj[prop2] = obj2[prop2]; }); res.push(combinedObj); @@ -205,7 +203,7 @@ RuleConfigSet.prototype = { addErrorSeverity(severity) { severity = severity || 2; - this.ruleConfigs = this.ruleConfigs.map(function(config) { + this.ruleConfigs = this.ruleConfigs.map(config => { config.unshift(severity); return config; }); @@ -241,9 +239,7 @@ RuleConfigSet.prototype = { }, combine() { - this.objectConfigs = groupByProperty(this.objectConfigs).reduce(function(accumulator, objArr) { - return combinePropertyObjects(accumulator, objArr); - }, []); + this.objectConfigs = groupByProperty(this.objectConfigs).reduce((accumulator, objArr) => combinePropertyObjects(accumulator, objArr), []); } }; @@ -251,7 +247,7 @@ RuleConfigSet.prototype = { * The object schema could have multiple independent properties. * If any contain enums or booleans, they can be added and then combined */ - Object.keys(obj.properties).forEach(function(prop) { + Object.keys(obj.properties).forEach(prop => { if (obj.properties[prop].enum) { objectConfigSet.add(prop, obj.properties[prop].enum); } @@ -276,7 +272,7 @@ function generateConfigsFromSchema(schema) { const configSet = new RuleConfigSet(); if (Array.isArray(schema)) { - schema.forEach(function(opt) { + schema.forEach(opt => { if (opt.enum) { configSet.addEnums(opt.enum); } @@ -302,7 +298,7 @@ function generateConfigsFromSchema(schema) { function createCoreRuleConfigs() { const ruleList = loadRules(); - return Object.keys(ruleList).reduce(function(accumulator, id) { + return Object.keys(ruleList).reduce((accumulator, id) => { const rule = rules.get(id); const schema = (typeof rule === "function") ? rule.schema : rule.meta.schema; diff --git a/tools/eslint/lib/config/config-validator.js b/tools/eslint/lib/config/config-validator.js index ef285eae4e6032..c5268169b92356 100644 --- a/tools/eslint/lib/config/config-validator.js +++ b/tools/eslint/lib/config/config-validator.js @@ -54,65 +54,59 @@ function getRuleOptionsSchema(id) { } /** - * Validates a rule's options against its schema. - * @param {string} id The rule's unique name. - * @param {array|number} options The given options for the rule. - * @param {string} source The name of the configuration source. - * @returns {void} - */ -function validateRuleOptions(id, options, source) { - const schema = getRuleOptionsSchema(id); - let validateRule = validators.rules[id], - severity, - localOptions, - validSeverity = true; - - if (!validateRule && schema) { - validateRule = schemaValidator(schema, { verbose: true }); - validators.rules[id] = validateRule; +* Validates a rule's severity and returns the severity value. Throws an error if the severity is invalid. +* @param {options} options The given options for the rule. +* @returns {number|string} The rule's severity value +*/ +function validateRuleSeverity(options) { + const severity = Array.isArray(options) ? options[0] : options; + + if (severity !== 0 && severity !== 1 && severity !== 2 && !(typeof severity === "string" && /^(?:off|warn|error)$/i.test(severity))) { + throw new Error(`\tSeverity should be one of the following: 0 = off, 1 = warn, 2 = error (you passed '${util.inspect(severity).replace(/'/g, "\"").replace(/\n/g, "")}').\n`); } - // if it's not an array, it should be just a severity - if (Array.isArray(options)) { - localOptions = options.concat(); // clone - severity = localOptions.shift(); - } else { - severity = options; - localOptions = []; + return severity; +} + +/** +* Validates the non-severity options passed to a rule, based on its schema. +* @param {string} id The rule's unique name +* @param {array} localOptions The options for the rule, excluding severity +* @returns {void} +*/ +function validateRuleSchema(id, localOptions) { + const schema = getRuleOptionsSchema(id); + + if (!validators.rules[id] && schema) { + validators.rules[id] = schemaValidator(schema, { verbose: true }); } - validSeverity = ( - severity === 0 || severity === 1 || severity === 2 || - (typeof severity === "string" && /^(?:off|warn|error)$/i.test(severity)) - ); + const validateRule = validators.rules[id]; if (validateRule) { validateRule(localOptions); + if (validateRule.errors) { + throw new Error(validateRule.errors.map(error => `\tValue "${error.value}" ${error.message}.\n`).join("")); + } } +} - if ((validateRule && validateRule.errors) || !validSeverity) { - const message = [ - source, ":\n", - "\tConfiguration for rule \"", id, "\" is invalid:\n" - ]; - - if (!validSeverity) { - message.push( - "\tSeverity should be one of the following: 0 = off, 1 = warn, 2 = error (you passed '", - util.inspect(severity).replace(/'/g, "\"").replace(/\n/g, ""), - "').\n" - ); - } +/** + * Validates a rule's options against its schema. + * @param {string} id The rule's unique name. + * @param {array|number} options The given options for the rule. + * @param {string} source The name of the configuration source. + * @returns {void} + */ +function validateRuleOptions(id, options, source) { + try { + const severity = validateRuleSeverity(options); - if (validateRule && validateRule.errors) { - validateRule.errors.forEach(function(error) { - message.push( - "\tValue \"", error.value, "\" ", error.message, ".\n" - ); - }); + if (severity !== 0 && !(typeof severity === "string" && severity.toLowerCase() === "off")) { + validateRuleSchema(id, Array.isArray(options) ? options.slice(1) : []); } - - throw new Error(message.join("")); + } catch (err) { + throw new Error(`${source}:\n\tConfiguration for rule "${id}" is invalid:\n${err.message}`); } } @@ -134,7 +128,7 @@ function validateEnvironment(environment, source) { } if (typeof environment === "object") { - Object.keys(environment).forEach(function(env) { + Object.keys(environment).forEach(env => { if (!Environments.get(env)) { const message = [ source, ":\n", @@ -158,7 +152,7 @@ function validateEnvironment(environment, source) { function validate(config, source) { if (typeof config.rules === "object") { - Object.keys(config.rules).forEach(function(id) { + Object.keys(config.rules).forEach(id => { validateRuleOptions(id, config.rules[id], source); }); } diff --git a/tools/eslint/lib/config/environments.js b/tools/eslint/lib/config/environments.js index 36b989068ff6da..5c34da9328a4da 100644 --- a/tools/eslint/lib/config/environments.js +++ b/tools/eslint/lib/config/environments.js @@ -22,7 +22,7 @@ let environments = new Map(); * @private */ function load() { - Object.keys(envs).forEach(function(envName) { + Object.keys(envs).forEach(envName => { environments.set(envName, envs[envName]); }); } @@ -65,9 +65,9 @@ module.exports = { */ importPlugin(plugin, pluginName) { if (plugin.environments) { - Object.keys(plugin.environments).forEach(function(envName) { + Object.keys(plugin.environments).forEach(envName => { this.define(`${pluginName}/${envName}`, plugin.environments[envName]); - }, this); + }); } }, diff --git a/tools/eslint/lib/eslint.js b/tools/eslint/lib/eslint.js index fd7685f49257c6..3ae7cfe9c68103 100755 --- a/tools/eslint/lib/eslint.js +++ b/tools/eslint/lib/eslint.js @@ -26,7 +26,22 @@ const assert = require("assert"), Traverser = require("./util/traverser"), RuleContext = require("./rule-context"), rules = require("./rules"), - timing = require("./timing"); + timing = require("./timing"), + + pkg = require("../package.json"); + + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +/** + * The result of a parsing operation from parseForESLint() + * @typedef {Object} CustomParseResult + * @property {ASTNode} ast The ESTree AST Program node. + * @property {Object} services An object containing additional services related + * to the parser. + */ //------------------------------------------------------------------------------ // Helpers @@ -45,7 +60,7 @@ function parseBooleanConfig(string, comment) { // Collapse whitespace around `:` and `,` to make parsing easier string = string.replace(/\s*([:,])\s*/g, "$1"); - string.split(/\s|,+/).forEach(function(name) { + string.split(/\s|,+/).forEach(name => { if (!name) { return; } @@ -95,7 +110,7 @@ function parseJsonConfig(string, location, messages) { // Optionator cannot parse commaless notations. // But we are supporting that. So this is a fallback for that. items = {}; - string = string.replace(/([a-zA-Z0-9\-\/]+):/g, "\"$1\":").replace(/(\]|[0-9])\s+(?=")/, "$1,"); + string = string.replace(/([a-zA-Z0-9\-/]+):/g, "\"$1\":").replace(/(]|[0-9])\s+(?=")/, "$1,"); try { items = JSON.parse(`{${string}}`); } catch (ex) { @@ -126,7 +141,7 @@ function parseListConfig(string) { // Collapse whitespace around , string = string.replace(/\s*,\s*/g, ","); - string.split(/,+/).forEach(function(name) { + string.split(/,+/).forEach(name => { name = name.trim(); if (!name) { return; @@ -153,7 +168,7 @@ function addDeclaredGlobals(program, globalScope, config) { Object.assign(declaredGlobals, builtin); - Object.keys(config.env).forEach(function(name) { + Object.keys(config.env).forEach(name => { if (config.env[name]) { const env = Environments.get(name), environmentGlobals = env && env.globals; @@ -168,7 +183,7 @@ function addDeclaredGlobals(program, globalScope, config) { Object.assign(declaredGlobals, config.globals); Object.assign(explicitGlobals, config.astGlobals); - Object.keys(declaredGlobals).forEach(function(name) { + Object.keys(declaredGlobals).forEach(name => { let variable = globalScope.set.get(name); if (!variable) { @@ -180,7 +195,7 @@ function addDeclaredGlobals(program, globalScope, config) { variable.writeable = declaredGlobals[name]; }); - Object.keys(explicitGlobals).forEach(function(name) { + Object.keys(explicitGlobals).forEach(name => { let variable = globalScope.set.get(name); if (!variable) { @@ -194,7 +209,7 @@ function addDeclaredGlobals(program, globalScope, config) { }); // mark all exported variables as such - Object.keys(exportedGlobals).forEach(function(name) { + Object.keys(exportedGlobals).forEach(name => { const variable = globalScope.set.get(name); if (variable) { @@ -207,7 +222,7 @@ function addDeclaredGlobals(program, globalScope, config) { * Since we augment the global scope using configuration, we need to update * references and remove the ones that were added by configuration. */ - globalScope.through = globalScope.through.filter(function(reference) { + globalScope.through = globalScope.through.filter(reference => { const name = reference.identifier.name; const variable = globalScope.set.get(name); @@ -238,7 +253,7 @@ function addDeclaredGlobals(program, globalScope, config) { function disableReporting(reportingConfig, start, rulesToDisable) { if (rulesToDisable.length) { - rulesToDisable.forEach(function(rule) { + rulesToDisable.forEach(rule => { reportingConfig.push({ start, end: null, @@ -266,7 +281,7 @@ function enableReporting(reportingConfig, start, rulesToEnable) { let i; if (rulesToEnable.length) { - rulesToEnable.forEach(function(rule) { + rulesToEnable.forEach(rule => { for (i = reportingConfig.length - 1; i >= 0; i--) { if (!reportingConfig[i].end && reportingConfig[i].rule === rule) { reportingConfig[i].end = start; @@ -313,7 +328,7 @@ function modifyConfigsFromComments(filename, ast, config, reportingConfig, messa }; const commentRules = {}; - ast.comments.forEach(function(comment) { + ast.comments.forEach(comment => { let value = comment.value.trim(); const match = /^(eslint(-\w+){0,3}|exported|globals?)(\s|$)/.exec(value); @@ -347,7 +362,7 @@ function modifyConfigsFromComments(filename, ast, config, reportingConfig, messa case "eslint": { const items = parseJsonConfig(value, comment.loc, messages); - Object.keys(items).forEach(function(name) { + Object.keys(items).forEach(name => { const ruleValue = items[name]; validator.validateRuleOptions(name, ruleValue, `${filename} line ${comment.loc.start.line}`); @@ -371,7 +386,7 @@ function modifyConfigsFromComments(filename, ast, config, reportingConfig, messa }); // apply environment configs - Object.keys(commentConfig.env).forEach(function(name) { + Object.keys(commentConfig.env).forEach(name => { const env = Environments.get(name); if (env) { @@ -442,11 +457,11 @@ function prepareConfig(config) { let parserOptions = {}; if (typeof config.rules === "object") { - Object.keys(config.rules).forEach(function(k) { + Object.keys(config.rules).forEach(k => { const rule = config.rules[k]; if (rule === null) { - throw new Error(`Invalid config for rule '${k}'\.`); + throw new Error(`Invalid config for rule '${k}'.`); } if (Array.isArray(rule)) { copiedRules[k] = rule.slice(); @@ -458,7 +473,7 @@ function prepareConfig(config) { // merge in environment parserOptions if (typeof config.env === "object") { - Object.keys(config.env).forEach(function(envName) { + Object.keys(config.env).forEach(envName => { const env = Environments.get(envName); if (config.env[envName] && env && env.parserOptions) { @@ -598,7 +613,8 @@ module.exports = (function() { * @param {string} text The text to parse. * @param {Object} config The ESLint configuration object. * @param {string} filePath The path to the file being parsed. - * @returns {ASTNode} The AST if successful or null if not. + * @returns {ASTNode|CustomParseResult} The AST or parse result if successful, + * or null if not. * @private */ function parse(text, config, filePath) { @@ -642,7 +658,11 @@ module.exports = (function() { * problem that ESLint identified just like any other. */ try { - return parser.parse(text, parserOptions); + if (typeof parser.parseForESLint === "function") { + return parser.parseForESLint(text, parserOptions); + } else { + return parser.parse(text, parserOptions); + } } catch (ex) { // If the message includes a leading line number, strip it: @@ -738,6 +758,7 @@ module.exports = (function() { api.verify = function(textOrSourceCode, config, filenameOrOptions, saveState) { const text = (typeof textOrSourceCode === "string") ? textOrSourceCode : null; let ast, + parseResult, shebang, allowInlineConfig; @@ -759,7 +780,7 @@ module.exports = (function() { if (envInFile) { if (!config || !config.env) { - config = Object.assign({}, config || {}, {env: envInFile}); + config = Object.assign({}, config || {}, { env: envInFile }); } else { config = Object.assign({}, config); config.env = Object.assign({}, config.env, envInFile); @@ -778,8 +799,8 @@ module.exports = (function() { return messages; } - ast = parse( - stripUnicodeBOM(text).replace(/^#!([^\r\n]+)/, function(match, captured) { + parseResult = parse( + stripUnicodeBOM(text).replace(/^#!([^\r\n]+)/, (match, captured) => { shebang = captured; return `//${captured}`; }), @@ -787,6 +808,14 @@ module.exports = (function() { currentFilename ); + // if this result is from a parseForESLint() method, normalize + if (parseResult && parseResult.ast) { + ast = parseResult.ast; + } else { + ast = parseResult; + parseResult = null; + } + if (ast) { sourceCode = new SourceCode(text, ast); } @@ -808,9 +837,7 @@ module.exports = (function() { ConfigOps.normalize(config); // enable appropriate rules - Object.keys(config.rules).filter(function(key) { - return getRuleSeverity(config.rules[key]) > 0; - }).forEach(function(key) { + Object.keys(config.rules).filter(key => getRuleSeverity(config.rules[key]) > 0).forEach(key => { let ruleCreator; ruleCreator = rules.get(key); @@ -832,13 +859,16 @@ module.exports = (function() { try { const ruleContext = new RuleContext( key, api, severity, options, - config.settings, config.parserOptions, config.parser, ruleCreator.meta); + config.settings, config.parserOptions, config.parser, + ruleCreator.meta, + (parseResult && parseResult.services ? parseResult.services : {}) + ); const rule = ruleCreator.create ? ruleCreator.create(ruleContext) : ruleCreator(ruleContext); // add all the node types as listeners - Object.keys(rule).forEach(function(nodeType) { + Object.keys(rule).forEach(nodeType => { api.on(nodeType, timing.enabled ? timing.time(key, rule[nodeType]) : rule[nodeType] @@ -904,7 +934,7 @@ module.exports = (function() { } // sort by line and column - messages.sort(function(a, b) { + messages.sort((a, b) => { const lineDiff = a.line - b.line; if (lineDiff === 0) { @@ -957,7 +987,7 @@ module.exports = (function() { } if (opts) { - message = message.replace(/\{\{\s*([^{}]+?)\s*\}\}/g, function(fullMatch, term) { + message = message.replace(/\{\{\s*([^{}]+?)\s*\}\}/g, (fullMatch, term) => { if (term in opts) { return opts[term]; } @@ -1027,7 +1057,7 @@ module.exports = (function() { }; // copy over methods - Object.keys(externalMethods).forEach(function(methodName) { + Object.keys(externalMethods).forEach(methodName => { const exMethodName = externalMethods[methodName]; // All functions expected to have less arguments than 5. @@ -1152,7 +1182,7 @@ module.exports = (function() { * @returns {void} */ api.defineRules = function(rulesToDefine) { - Object.getOwnPropertyNames(rulesToDefine).forEach(function(ruleId) { + Object.getOwnPropertyNames(rulesToDefine).forEach(ruleId => { defineRule(ruleId, rulesToDefine[ruleId]); }); }; @@ -1165,6 +1195,16 @@ module.exports = (function() { return require("../conf/eslint.json"); }; + /** + * Gets an object with all loaded rules. + * @returns {Map} All loaded rules + */ + api.getRules = function() { + return rules.getAllLoadedRules(); + }; + + api.version = pkg.version; + /** * Gets variables that are declared by a specified node. * diff --git a/tools/eslint/lib/file-finder.js b/tools/eslint/lib/file-finder.js index 18f3b65133d7a3..acb886c9d1e2c2 100644 --- a/tools/eslint/lib/file-finder.js +++ b/tools/eslint/lib/file-finder.js @@ -31,22 +31,6 @@ function getDirectoryEntries(directory) { } } -//------------------------------------------------------------------------------ -// API -//------------------------------------------------------------------------------ - -/** - * FileFinder - * @constructor - * @param {string[]} files The basename(s) of the file(s) to find. - * @param {stirng} cwd Current working directory - */ -function FileFinder(files, cwd) { - this.fileNames = Array.isArray(files) ? files : [files]; - this.cwd = cwd || process.cwd(); - this.cache = {}; -} - /** * Create a hash of filenames from a directory listing * @param {string[]} entries Array of directory entries. @@ -57,7 +41,7 @@ function FileFinder(files, cwd) { function normalizeDirectoryEntries(entries, directory, supportedConfigs) { const fileHash = {}; - entries.forEach(function(entry) { + entries.forEach(entry => { if (supportedConfigs.indexOf(entry) >= 0) { const resolvedEntry = path.resolve(directory, entry); @@ -69,69 +53,89 @@ function normalizeDirectoryEntries(entries, directory, supportedConfigs) { return fileHash; } +//------------------------------------------------------------------------------ +// API +//------------------------------------------------------------------------------ + /** - * Find all instances of files with the specified file names, in directory and - * parent directories. Cache the results. - * Does not check if a matching directory entry is a file. - * Searches for all the file names in this.fileNames. - * Is currently used by lib/config.js to find .eslintrc and package.json files. - * @param {string} directory The directory to start the search from. - * @returns {string[]} The file paths found. + * FileFinder class */ -FileFinder.prototype.findAllInDirectoryAndParents = function(directory) { - const cache = this.cache; - - if (directory) { - directory = path.resolve(this.cwd, directory); - } else { - directory = this.cwd; +class FileFinder { + + /** + * @param {string[]} files The basename(s) of the file(s) to find. + * @param {stirng} cwd Current working directory + */ + constructor(files, cwd) { + this.fileNames = Array.isArray(files) ? files : [files]; + this.cwd = cwd || process.cwd(); + this.cache = {}; } - if (cache.hasOwnProperty(directory)) { - return cache[directory]; - } + /** + * Find all instances of files with the specified file names, in directory and + * parent directories. Cache the results. + * Does not check if a matching directory entry is a file. + * Searches for all the file names in this.fileNames. + * Is currently used by lib/config.js to find .eslintrc and package.json files. + * @param {string} directory The directory to start the search from. + * @returns {string[]} The file paths found. + */ + findAllInDirectoryAndParents(directory) { + const cache = this.cache; + + if (directory) { + directory = path.resolve(this.cwd, directory); + } else { + directory = this.cwd; + } - const dirs = []; - const fileNames = this.fileNames; - let searched = 0; + if (cache.hasOwnProperty(directory)) { + return cache[directory]; + } - do { - dirs[searched++] = directory; - cache[directory] = []; + const dirs = []; + const fileNames = this.fileNames; + let searched = 0; - const filesMap = normalizeDirectoryEntries(getDirectoryEntries(directory), directory, fileNames); + do { + dirs[searched++] = directory; + cache[directory] = []; - if (Object.keys(filesMap).length) { - for (let k = 0; k < fileNames.length; k++) { + const filesMap = normalizeDirectoryEntries(getDirectoryEntries(directory), directory, fileNames); - if (filesMap[fileNames[k]]) { - const filePath = filesMap[fileNames[k]]; + if (Object.keys(filesMap).length) { + for (let k = 0; k < fileNames.length; k++) { - // Add the file path to the cache of each directory searched. - for (let j = 0; j < searched; j++) { - cache[dirs[j]].push(filePath); - } + if (filesMap[fileNames[k]]) { + const filePath = filesMap[fileNames[k]]; + + // Add the file path to the cache of each directory searched. + for (let j = 0; j < searched; j++) { + cache[dirs[j]].push(filePath); + } - break; + break; + } } } - } - const child = directory; + const child = directory; + + // Assign parent directory to directory. + directory = path.dirname(directory); - // Assign parent directory to directory. - directory = path.dirname(directory); + if (directory === child) { + return cache[dirs[0]]; + } + } while (!cache.hasOwnProperty(directory)); - if (directory === child) { - return cache[dirs[0]]; + // Add what has been cached previously to the cache of each directory searched. + for (let i = 0; i < searched; i++) { + dirs.push.apply(cache[dirs[i]], cache[directory]); } - } while (!cache.hasOwnProperty(directory)); - // Add what has been cached previously to the cache of each directory searched. - for (let i = 0; i < searched; i++) { - dirs.push.apply(cache[dirs[i]], cache[directory]); + return cache[dirs[0]]; } - - return cache[dirs[0]]; -}; +} module.exports = FileFinder; diff --git a/tools/eslint/lib/formatters/checkstyle.js b/tools/eslint/lib/formatters/checkstyle.js index 0beedcf6895217..5985ad0eff5752 100644 --- a/tools/eslint/lib/formatters/checkstyle.js +++ b/tools/eslint/lib/formatters/checkstyle.js @@ -35,12 +35,12 @@ module.exports = function(results) { output += ""; output += ""; - results.forEach(function(result) { + results.forEach(result => { const messages = result.messages; output += ``; - messages.forEach(function(message) { + messages.forEach(message => { output += [ ` 0 ? "red" : "yellow"; + const summary = []; + + if (errors > 0) { + summary.push(`${errors} ${pluralize("error", errors)}`); + } + + if (warnings > 0) { + summary.push(`${warnings} ${pluralize("warning", warnings)}`); + } + + return chalk[summaryColor].bold(`${summary.join(" and ")} found.`); +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +module.exports = function(results) { + let errors = 0; + let warnings = 0; + const resultsWithMessages = results.filter(result => result.messages.length > 0); + + let output = resultsWithMessages.reduce((resultsOutput, result) => { + const messages = result.messages.map(message => { + if (message.fatal || message.severity === 2) { + errors++; + } else { + warnings++; + } + + return `${formatMessage(message, result)}\n\n`; + }); + + return resultsOutput.concat(messages); + }, []).join("\n"); + + output += "\n"; + output += formatSummary(errors, warnings); + + return (errors + warnings) > 0 ? output : ""; +}; diff --git a/tools/eslint/lib/formatters/compact.js b/tools/eslint/lib/formatters/compact.js index 9c7aeb87d7c064..c641039ff284c6 100644 --- a/tools/eslint/lib/formatters/compact.js +++ b/tools/eslint/lib/formatters/compact.js @@ -32,13 +32,13 @@ module.exports = function(results) { let output = "", total = 0; - results.forEach(function(result) { + results.forEach(result => { const messages = result.messages; total += messages.length; - messages.forEach(function(message) { + messages.forEach(message => { output += `${result.filePath}: `; output += `line ${message.line || 0}`; diff --git a/tools/eslint/lib/formatters/html.js b/tools/eslint/lib/formatters/html.js index 66e89d372cb8db..e61fdea6a93eec 100644 --- a/tools/eslint/lib/formatters/html.js +++ b/tools/eslint/lib/formatters/html.js @@ -70,7 +70,7 @@ function renderMessages(messages, parentIndex) { * @param {Object} message Message. * @returns {string} HTML (table row) describing a message. */ - return lodash.map(messages, function(message) { + return lodash.map(messages, message => { const lineNumber = message.line || 0; const columnNumber = message.column || 0; @@ -91,15 +91,13 @@ function renderMessages(messages, parentIndex) { * @returns {string} HTML string describing the results. */ function renderResults(results) { - return lodash.map(results, function(result, index) { - return resultTemplate({ - index, - color: renderColor(result.errorCount, result.warningCount), - filePath: result.filePath, - summary: renderSummary(result.errorCount, result.warningCount) - - }) + renderMessages(result.messages, index); - }).join("\n"); + return lodash.map(results, (result, index) => resultTemplate({ + index, + color: renderColor(result.errorCount, result.warningCount), + filePath: result.filePath, + summary: renderSummary(result.errorCount, result.warningCount) + + }) + renderMessages(result.messages, index)).join("\n"); } //------------------------------------------------------------------------------ @@ -114,7 +112,7 @@ module.exports = function(results) { totalWarnings = 0; // Iterate over results to get totals - results.forEach(function(result) { + results.forEach(result => { totalErrors += result.errorCount; totalWarnings += result.warningCount; }); diff --git a/tools/eslint/lib/formatters/jslint-xml.js b/tools/eslint/lib/formatters/jslint-xml.js index 7cfa893d32fad2..14743430d8ff94 100644 --- a/tools/eslint/lib/formatters/jslint-xml.js +++ b/tools/eslint/lib/formatters/jslint-xml.js @@ -17,12 +17,12 @@ module.exports = function(results) { output += ""; output += ""; - results.forEach(function(result) { + results.forEach(result => { const messages = result.messages; output += ``; - messages.forEach(function(message) { + messages.forEach(message => { output += [ `\n"; output += "\n"; - results.forEach(function(result) { + results.forEach(result => { const messages = result.messages; @@ -43,7 +43,7 @@ module.exports = function(results) { output += `\n`; } - messages.forEach(function(message) { + messages.forEach(message => { const type = message.fatal ? "error" : "failure"; output += ``; diff --git a/tools/eslint/lib/formatters/stylish.js b/tools/eslint/lib/formatters/stylish.js index 578a146c010f57..a176d03ab83e0b 100644 --- a/tools/eslint/lib/formatters/stylish.js +++ b/tools/eslint/lib/formatters/stylish.js @@ -33,7 +33,7 @@ module.exports = function(results) { warnings = 0, summaryColor = "yellow"; - results.forEach(function(result) { + results.forEach(result => { const messages = result.messages; if (messages.length === 0) { @@ -44,7 +44,7 @@ module.exports = function(results) { output += `${chalk.underline(result.filePath)}\n`; output += `${table( - messages.map(function(message) { + messages.map(message => { let messageType; if (message.fatal || message.severity === 2) { @@ -71,11 +71,7 @@ module.exports = function(results) { return chalk.stripColor(str).length; } } - ).split("\n").map(function(el) { - return el.replace(/(\d+)\s+(\d+)/, function(m, p1, p2) { - return chalk.dim(`${p1}:${p2}`); - }); - }).join("\n")}\n\n`; + ).split("\n").map(el => el.replace(/(\d+)\s+(\d+)/, (m, p1, p2) => chalk.dim(`${p1}:${p2}`))).join("\n")}\n\n`; }); if (total > 0) { diff --git a/tools/eslint/lib/formatters/table.js b/tools/eslint/lib/formatters/table.js index cd09626cc79381..b4859154ba610d 100644 --- a/tools/eslint/lib/formatters/table.js +++ b/tools/eslint/lib/formatters/table.js @@ -36,7 +36,7 @@ function drawTable(messages) { chalk.bold("Rule ID") ]); - messages.forEach(function(message) { + messages.forEach(message => { let messageType; if (message.fatal || message.severity === 2) { @@ -92,7 +92,7 @@ function drawTable(messages) { function drawReport(results) { let files; - files = results.map(function(result) { + files = results.map(result => { if (!result.messages.length) { return ""; } @@ -100,9 +100,7 @@ function drawReport(results) { return `\n${result.filePath}\n\n${drawTable(result.messages)}`; }); - files = files.filter(function(content) { - return content.trim(); - }); + files = files.filter(content => content.trim()); return files.join(""); } @@ -120,7 +118,7 @@ module.exports = function(report) { errorCount = 0; warningCount = 0; - report.forEach(function(fileReport) { + report.forEach(fileReport => { errorCount += fileReport.errorCount; warningCount += fileReport.warningCount; }); diff --git a/tools/eslint/lib/formatters/tap.js b/tools/eslint/lib/formatters/tap.js index 568ac1e8b64548..27825d0ba996e7 100644 --- a/tools/eslint/lib/formatters/tap.js +++ b/tools/eslint/lib/formatters/tap.js @@ -44,7 +44,7 @@ function outputDiagnostics(diagnostic) { module.exports = function(results) { let output = `TAP version 13\n1..${results.length}\n`; - results.forEach(function(result, id) { + results.forEach((result, id) => { const messages = result.messages; let testResult = "ok"; let diagnostics = {}; @@ -52,7 +52,7 @@ module.exports = function(results) { if (messages.length > 0) { testResult = "not ok"; - messages.forEach(function(message) { + messages.forEach(message => { const diagnostic = { message: message.message, severity: getMessageType(message), diff --git a/tools/eslint/lib/formatters/unix.js b/tools/eslint/lib/formatters/unix.js index 867bbd5b49fcd3..a5635278bc3fa9 100644 --- a/tools/eslint/lib/formatters/unix.js +++ b/tools/eslint/lib/formatters/unix.js @@ -31,13 +31,13 @@ module.exports = function(results) { let output = "", total = 0; - results.forEach(function(result) { + results.forEach(result => { const messages = result.messages; total += messages.length; - messages.forEach(function(message) { + messages.forEach(message => { output += `${result.filePath}:`; output += `${message.line || 0}:`; diff --git a/tools/eslint/lib/formatters/visualstudio.js b/tools/eslint/lib/formatters/visualstudio.js index 134a04a5134ca0..feb7fb4bef382b 100644 --- a/tools/eslint/lib/formatters/visualstudio.js +++ b/tools/eslint/lib/formatters/visualstudio.js @@ -33,13 +33,13 @@ module.exports = function(results) { let output = "", total = 0; - results.forEach(function(result) { + results.forEach(result => { const messages = result.messages; total += messages.length; - messages.forEach(function(message) { + messages.forEach(message => { output += result.filePath; output += `(${message.line || 0}`; diff --git a/tools/eslint/lib/ignored-paths.js b/tools/eslint/lib/ignored-paths.js index bc2db8aaac8dc0..bace73db6a394b 100644 --- a/tools/eslint/lib/ignored-paths.js +++ b/tools/eslint/lib/ignored-paths.js @@ -72,160 +72,161 @@ function mergeDefaultOptions(options) { //------------------------------------------------------------------------------ /** - * IgnoredPaths - * @constructor - * @class IgnoredPaths - * @param {Object} options object containing 'ignore', 'ignorePath' and 'patterns' properties + * IgnoredPaths class */ -function IgnoredPaths(options) { - - options = mergeDefaultOptions(options); - - /** - * add pattern to node-ignore instance - * @param {Object} ig, instance of node-ignore - * @param {string} pattern, pattern do add to ig - * @returns {array} raw ignore rules - */ - function addPattern(ig, pattern) { - return ig.addPattern(pattern); - } +class IgnoredPaths { /** - * add ignore file to node-ignore instance - * @param {Object} ig, instance of node-ignore - * @param {string} filepath, file to add to ig - * @returns {array} raw ignore rules + * @param {Object} options object containing 'ignore', 'ignorePath' and 'patterns' properties */ - function addIgnoreFile(ig, filepath) { - ig.ignoreFiles.push(filepath); - return ig.add(fs.readFileSync(filepath, "utf8")); - } - - this.defaultPatterns = [].concat(DEFAULT_IGNORE_DIRS, options.patterns || []); - this.baseDir = options.cwd; - - this.ig = { - custom: ignore(), - default: ignore() - }; + constructor(options) { + options = mergeDefaultOptions(options); + + /** + * add pattern to node-ignore instance + * @param {Object} ig, instance of node-ignore + * @param {string} pattern, pattern do add to ig + * @returns {array} raw ignore rules + */ + function addPattern(ig, pattern) { + return ig.addPattern(pattern); + } - // Add a way to keep track of ignored files. This was present in node-ignore - // 2.x, but dropped for now as of 3.0.10. - this.ig.custom.ignoreFiles = []; - this.ig.default.ignoreFiles = []; + /** + * add ignore file to node-ignore instance + * @param {Object} ig, instance of node-ignore + * @param {string} filepath, file to add to ig + * @returns {array} raw ignore rules + */ + function addIgnoreFile(ig, filepath) { + ig.ignoreFiles.push(filepath); + return ig.add(fs.readFileSync(filepath, "utf8")); + } - if (options.dotfiles !== true) { + this.defaultPatterns = [].concat(DEFAULT_IGNORE_DIRS, options.patterns || []); + this.baseDir = options.cwd; - /* - * ignore files beginning with a dot, but not files in a parent or - * ancestor directory (which in relative format will begin with `../`). - */ - addPattern(this.ig.default, [".*", "!../"]); - } + this.ig = { + custom: ignore(), + default: ignore() + }; - addPattern(this.ig.default, this.defaultPatterns); + // Add a way to keep track of ignored files. This was present in node-ignore + // 2.x, but dropped for now as of 3.0.10. + this.ig.custom.ignoreFiles = []; + this.ig.default.ignoreFiles = []; - if (options.ignore !== false) { - let ignorePath; + if (options.dotfiles !== true) { - if (options.ignorePath) { - debug("Using specific ignore file"); + /* + * ignore files beginning with a dot, but not files in a parent or + * ancestor directory (which in relative format will begin with `../`). + */ + addPattern(this.ig.default, [".*", "!../"]); + } - try { - fs.statSync(options.ignorePath); - ignorePath = options.ignorePath; - } catch (e) { - e.message = `Cannot read ignore file: ${options.ignorePath}\nError: ${e.message}`; - throw e; + addPattern(this.ig.default, this.defaultPatterns); + + if (options.ignore !== false) { + let ignorePath; + + if (options.ignorePath) { + debug("Using specific ignore file"); + + try { + fs.statSync(options.ignorePath); + ignorePath = options.ignorePath; + } catch (e) { + e.message = `Cannot read ignore file: ${options.ignorePath}\nError: ${e.message}`; + throw e; + } + } else { + debug(`Looking for ignore file in ${options.cwd}`); + ignorePath = findIgnoreFile(options.cwd); + + try { + fs.statSync(ignorePath); + debug(`Loaded ignore file ${ignorePath}`); + } catch (e) { + debug("Could not find ignore file in cwd"); + this.options = options; + } } - } else { - debug(`Looking for ignore file in ${options.cwd}`); - ignorePath = findIgnoreFile(options.cwd); - - try { - fs.statSync(ignorePath); - debug(`Loaded ignore file ${ignorePath}`); - } catch (e) { - debug("Could not find ignore file in cwd"); - this.options = options; + + if (ignorePath) { + debug(`Adding ${ignorePath}`); + this.baseDir = path.dirname(path.resolve(options.cwd, ignorePath)); + addIgnoreFile(this.ig.custom, ignorePath); + addIgnoreFile(this.ig.default, ignorePath); } - } - if (ignorePath) { - debug(`Adding ${ignorePath}`); - this.baseDir = path.dirname(path.resolve(options.cwd, ignorePath)); - addIgnoreFile(this.ig.custom, ignorePath); - addIgnoreFile(this.ig.default, ignorePath); + if (options.ignorePattern) { + addPattern(this.ig.custom, options.ignorePattern); + addPattern(this.ig.default, options.ignorePattern); + } } - if (options.ignorePattern) { - addPattern(this.ig.custom, options.ignorePattern); - addPattern(this.ig.default, options.ignorePattern); - } + this.options = options; } - this.options = options; + /** + * Determine whether a file path is included in the default or custom ignore patterns + * @param {string} filepath Path to check + * @param {string} [category=null] check 'default', 'custom' or both (null) + * @returns {boolean} true if the file path matches one or more patterns, false otherwise + */ + contains(filepath, category) { -} + let result = false; + const absolutePath = path.resolve(this.options.cwd, filepath); + const relativePath = pathUtil.getRelativePath(absolutePath, this.options.cwd); -/** - * Determine whether a file path is included in the default or custom ignore patterns - * @param {string} filepath Path to check - * @param {string} [category=null] check 'default', 'custom' or both (null) - * @returns {boolean} true if the file path matches one or more patterns, false otherwise - */ -IgnoredPaths.prototype.contains = function(filepath, category) { + if ((typeof category === "undefined") || (category === "default")) { + result = result || (this.ig.default.filter([relativePath]).length === 0); + } - let result = false; - const absolutePath = path.resolve(this.options.cwd, filepath); - const relativePath = pathUtil.getRelativePath(absolutePath, this.options.cwd); + if ((typeof category === "undefined") || (category === "custom")) { + result = result || (this.ig.custom.filter([relativePath]).length === 0); + } - if ((typeof category === "undefined") || (category === "default")) { - result = result || (this.ig.default.filter([relativePath]).length === 0); - } + return result; - if ((typeof category === "undefined") || (category === "custom")) { - result = result || (this.ig.custom.filter([relativePath]).length === 0); } - return result; - -}; - -/** - * Returns a list of dir patterns for glob to ignore - * @returns {function()} method to check whether a folder should be ignored by glob. - */ -IgnoredPaths.prototype.getIgnoredFoldersGlobChecker = function() { + /** + * Returns a list of dir patterns for glob to ignore + * @returns {function()} method to check whether a folder should be ignored by glob. + */ + getIgnoredFoldersGlobChecker() { - const ig = ignore().add(DEFAULT_IGNORE_DIRS); + const ig = ignore().add(DEFAULT_IGNORE_DIRS); - if (this.options.ignore) { - ig.add(this.ig.custom); - } + if (this.options.ignore) { + ig.add(this.ig.custom); + } - const filter = ig.createFilter(); + const filter = ig.createFilter(); - /** - * TODO - * 1. - * Actually, it should be `this.options.baseDir`, which is the base dir of `ignore-path`, - * as well as Line 177. - * But doing this leads to a breaking change and fails tests. - * Related to #6759 - */ - const base = this.options.cwd; + /** + * TODO + * 1. + * Actually, it should be `this.options.baseDir`, which is the base dir of `ignore-path`, + * as well as Line 177. + * But doing this leads to a breaking change and fails tests. + * Related to #6759 + */ + const base = this.options.cwd; - return function(absolutePath) { - const relative = pathUtil.getRelativePath(absolutePath, base); + return function(absolutePath) { + const relative = pathUtil.getRelativePath(absolutePath, base); - if (!relative) { - return false; - } + if (!relative) { + return false; + } - return !filter(relative); - }; -}; + return !filter(relative); + }; + } +} module.exports = IgnoredPaths; diff --git a/tools/eslint/lib/internal-rules/internal-consistent-docs-description.js b/tools/eslint/lib/internal-rules/internal-consistent-docs-description.js index 3e4671aa7b151d..a4a5dca03fbbf2 100644 --- a/tools/eslint/lib/internal-rules/internal-consistent-docs-description.js +++ b/tools/eslint/lib/internal-rules/internal-consistent-docs-description.js @@ -95,7 +95,6 @@ function checkMetaDocsDescription(context, exportsNode) { firstWord } }); - return; } } diff --git a/tools/eslint/lib/internal-rules/internal-no-invalid-meta.js b/tools/eslint/lib/internal-rules/internal-no-invalid-meta.js index 783a1109e76571..d1c78efa61e557 100644 --- a/tools/eslint/lib/internal-rules/internal-no-invalid-meta.js +++ b/tools/eslint/lib/internal-rules/internal-no-invalid-meta.js @@ -147,7 +147,6 @@ function checkMetaValidity(context, exportsNode, ruleIsFixable) { if (ruleIsFixable && !hasMetaFixable(metaProperty)) { context.report(metaProperty, "Rule is fixable, but is missing a meta.fixable property."); - return; } } @@ -216,7 +215,7 @@ module.exports = { "Program:exit"() { if (!isCorrectExportsFormat(exportsNode)) { - context.report(exportsNode, "Rule does not export an Object. Make sure the rule follows the new rule format."); + context.report({ node: exportsNode, message: "Rule does not export an Object. Make sure the rule follows the new rule format." }); return; } diff --git a/tools/eslint/lib/load-rules.js b/tools/eslint/lib/load-rules.js index c698faa5e132d0..92fb7bf20ada0c 100644 --- a/tools/eslint/lib/load-rules.js +++ b/tools/eslint/lib/load-rules.js @@ -31,7 +31,7 @@ module.exports = function(rulesDir, cwd) { const rules = Object.create(null); - fs.readdirSync(rulesDir).forEach(function(file) { + fs.readdirSync(rulesDir).forEach(file => { if (path.extname(file) !== ".js") { return; } diff --git a/tools/eslint/lib/rule-context.js b/tools/eslint/lib/rule-context.js index ded5dab962d70c..9c80d2e1a31cc6 100644 --- a/tools/eslint/lib/rule-context.js +++ b/tools/eslint/lib/rule-context.js @@ -61,36 +61,41 @@ const PASSTHROUGHS = [ //------------------------------------------------------------------------------ /** + * Rule context class * Acts as an abstraction layer between rules and the main eslint object. - * @constructor - * @param {string} ruleId The ID of the rule using this object. - * @param {eslint} eslint The eslint object. - * @param {number} severity The configured severity level of the rule. - * @param {Array} options The configuration information to be added to the rule. - * @param {Object} settings The configuration settings passed from the config file. - * @param {Object} parserOptions The parserOptions settings passed from the config file. - * @param {Object} parserPath The parser setting passed from the config file. - * @param {Object} meta The metadata of the rule */ -function RuleContext(ruleId, eslint, severity, options, settings, parserOptions, parserPath, meta) { +class RuleContext { - // public. - this.id = ruleId; - this.options = options; - this.settings = settings; - this.parserOptions = parserOptions; - this.parserPath = parserPath; - this.meta = meta; + /** + * @param {string} ruleId The ID of the rule using this object. + * @param {eslint} eslint The eslint object. + * @param {number} severity The configured severity level of the rule. + * @param {Array} options The configuration information to be added to the rule. + * @param {Object} settings The configuration settings passed from the config file. + * @param {Object} parserOptions The parserOptions settings passed from the config file. + * @param {Object} parserPath The parser setting passed from the config file. + * @param {Object} meta The metadata of the rule + * @param {Object} parserServices The parser services for the rule. + */ + constructor(ruleId, eslint, severity, options, settings, parserOptions, parserPath, meta, parserServices) { - // private. - this.eslint = eslint; - this.severity = severity; + // public. + this.id = ruleId; + this.options = options; + this.settings = settings; + this.parserOptions = parserOptions; + this.parserPath = parserPath; + this.meta = meta; - Object.freeze(this); -} + // create a separate copy and freeze it (it's not nice to freeze other people's objects) + this.parserServices = Object.freeze(Object.assign({}, parserServices)); -RuleContext.prototype = { - constructor: RuleContext, + // private. + this.eslint = eslint; + this.severity = severity; + + Object.freeze(this); + } /** * Passthrough to eslint.getSourceCode(). @@ -98,7 +103,7 @@ RuleContext.prototype = { */ getSourceCode() { return this.eslint.getSourceCode(); - }, + } /** * Passthrough to eslint.report() that automatically assigns the rule ID and severity. @@ -147,7 +152,7 @@ RuleContext.prototype = { this.meta ); } -}; +} // Copy over passthrough methods. All functions will have 5 or fewer parameters. PASSTHROUGHS.forEach(function(name) { diff --git a/tools/eslint/lib/rules.js b/tools/eslint/lib/rules.js index 128a6bcd15b652..80f83882d331cb 100644 --- a/tools/eslint/lib/rules.js +++ b/tools/eslint/lib/rules.js @@ -40,7 +40,7 @@ function define(ruleId, ruleModule) { function load(rulesDir, cwd) { const newRules = loadRules(rulesDir, cwd); - Object.keys(newRules).forEach(function(ruleId) { + Object.keys(newRules).forEach(ruleId => { define(ruleId, newRules[ruleId]); }); } @@ -53,7 +53,7 @@ function load(rulesDir, cwd) { */ function importPlugin(plugin, pluginName) { if (plugin.rules) { - Object.keys(plugin.rules).forEach(function(ruleId) { + Object.keys(plugin.rules).forEach(ruleId => { const qualifiedRuleId = `${pluginName}/${ruleId}`, rule = plugin.rules[ruleId]; @@ -75,6 +75,21 @@ function getHandler(ruleId) { } } +/** + * Get an object with all currently loaded rules + * @returns {Map} All loaded rules + */ +function getAllLoadedRules() { + const allRules = new Map(); + + Object.keys(rules).forEach(name => { + const rule = getHandler(name); + + allRules.set(name, rule); + }); + return allRules; +} + /** * Reset rules storage. * Should be used only in tests. @@ -89,6 +104,7 @@ module.exports = { load, importPlugin, get: getHandler, + getAllLoadedRules, testClear, /** diff --git a/tools/eslint/lib/rules/accessor-pairs.js b/tools/eslint/lib/rules/accessor-pairs.js index 7e8870edc8c8e1..4afdc7136ca2a6 100644 --- a/tools/eslint/lib/rules/accessor-pairs.js +++ b/tools/eslint/lib/rules/accessor-pairs.js @@ -139,9 +139,9 @@ module.exports = { } if (checkSetWithoutGet && isSetPresent && !isGetPresent) { - context.report(node, "Getter is not present."); + context.report({ node, message: "Getter is not present." }); } else if (checkGetWithoutSet && isGetPresent && !isSetPresent) { - context.report(node, "Setter is not present."); + context.report({ node, message: "Setter is not present." }); } } diff --git a/tools/eslint/lib/rules/array-bracket-spacing.js b/tools/eslint/lib/rules/array-bracket-spacing.js index 9bd7e944951a77..73cfbdc3c1fa8e 100644 --- a/tools/eslint/lib/rules/array-bracket-spacing.js +++ b/tools/eslint/lib/rules/array-bracket-spacing.js @@ -179,8 +179,10 @@ module.exports = { const first = sourceCode.getFirstToken(node), second = sourceCode.getFirstToken(node, 1), - penultimate = sourceCode.getLastToken(node, 1), - last = sourceCode.getLastToken(node), + last = node.typeAnnotation + ? sourceCode.getTokenBefore(node.typeAnnotation) + : sourceCode.getLastToken(node), + penultimate = sourceCode.getTokenBefore(last), firstElement = node.elements[0], lastElement = node.elements[node.elements.length - 1]; diff --git a/tools/eslint/lib/rules/arrow-body-style.js b/tools/eslint/lib/rules/arrow-body-style.js index 038aeeb5af2550..9778a6776f5e1f 100644 --- a/tools/eslint/lib/rules/arrow-body-style.js +++ b/tools/eslint/lib/rules/arrow-body-style.js @@ -37,7 +37,7 @@ module.exports = { { type: "object", properties: { - requireReturnForObjectLiteral: {type: "boolean"} + requireReturnForObjectLiteral: { type: "boolean" } }, additionalProperties: false } @@ -46,7 +46,9 @@ module.exports = { maxItems: 2 } ] - } + }, + + fixable: "code" }, create(context) { @@ -55,6 +57,7 @@ module.exports = { const asNeeded = !options[0] || options[0] === "as-needed"; const never = options[0] === "never"; const requireReturnForObjectLiteral = options[1] && options[1].requireReturnForObjectLiteral; + const sourceCode = context.getSourceCode(); /** * Determines whether a arrow function body needs braces @@ -65,38 +68,85 @@ module.exports = { const arrowBody = node.body; if (arrowBody.type === "BlockStatement") { - if (never) { + const blockBody = arrowBody.body; + + if (blockBody.length !== 1 && !never) { + return; + } + + if (asNeeded && requireReturnForObjectLiteral && blockBody[0].type === "ReturnStatement" && + blockBody[0].argument && blockBody[0].argument.type === "ObjectExpression") { + return; + } + + if (never || asNeeded && blockBody[0].type === "ReturnStatement") { context.report({ node, loc: arrowBody.loc.start, - message: "Unexpected block statement surrounding arrow body." + message: "Unexpected block statement surrounding arrow body.", + fix(fixer) { + if (blockBody.length !== 1 || blockBody[0].type !== "ReturnStatement" || !blockBody[0].argument) { + return null; + } + + const sourceText = sourceCode.getText(); + const returnKeyword = sourceCode.getFirstToken(blockBody[0]); + const firstValueToken = sourceCode.getTokenAfter(returnKeyword); + let lastValueToken = sourceCode.getLastToken(blockBody[0]); + + if (lastValueToken.type === "Punctuator" && lastValueToken.value === ";") { + + /* The last token of the returned value is the last token of the ReturnExpression (if + * the ReturnExpression has no semicolon), or the second-to-last token (if the ReturnExpression + * has a semicolon). + */ + lastValueToken = sourceCode.getTokenBefore(lastValueToken); + } + + const tokenAfterArrowBody = sourceCode.getTokenAfter(arrowBody); + + if (tokenAfterArrowBody && tokenAfterArrowBody.type === "Punctuator" && /^[([/`+-]/.test(tokenAfterArrowBody.value)) { + + // Don't do a fix if the next token would cause ASI issues when preceded by the returned value. + return null; + } + + const textBeforeReturn = sourceText.slice(arrowBody.range[0] + 1, returnKeyword.range[0]); + const textBetweenReturnAndValue = sourceText.slice(returnKeyword.range[1], firstValueToken.range[0]); + const rawReturnValueText = sourceText.slice(firstValueToken.range[0], lastValueToken.range[1]); + const returnValueText = firstValueToken.value === "{" ? `(${rawReturnValueText})` : rawReturnValueText; + const textAfterValue = sourceText.slice(lastValueToken.range[1], blockBody[0].range[1] - 1); + const textAfterReturnStatement = sourceText.slice(blockBody[0].range[1], arrowBody.range[1] - 1); + + /* + * For fixes that only contain spaces around the return value, remove the extra spaces. + * This avoids ugly fixes that end up with extra spaces after the arrow, e.g. `() => 0 ;` + */ + return fixer.replaceText( + arrowBody, + (textBeforeReturn + textBetweenReturnAndValue).replace(/^\s*$/, "") + returnValueText + (textAfterValue + textAfterReturnStatement).replace(/^\s*$/, "") + ); + } }); - } else { - const blockBody = arrowBody.body; - - if (blockBody.length !== 1) { - return; - } - - if (asNeeded && requireReturnForObjectLiteral && blockBody[0].type === "ReturnStatement" && - blockBody[0].argument.type === "ObjectExpression") { - return; - } - - if (asNeeded && blockBody[0].type === "ReturnStatement") { - context.report({ - node, - loc: arrowBody.loc.start, - message: "Unexpected block statement surrounding arrow body." - }); - } } } else { if (always || (asNeeded && requireReturnForObjectLiteral && arrowBody.type === "ObjectExpression")) { context.report({ node, loc: arrowBody.loc.start, - message: "Expected block statement surrounding arrow body." + message: "Expected block statement surrounding arrow body.", + fix(fixer) { + const lastTokenBeforeBody = sourceCode.getTokensBetween(sourceCode.getFirstToken(node), arrowBody) + .reverse() + .find(token => token.value !== "("); + + const firstBodyToken = sourceCode.getTokenAfter(lastTokenBeforeBody); + + return fixer.replaceTextRange( + [firstBodyToken.range[0], node.range[1]], + `{return ${sourceCode.getText().slice(firstBodyToken.range[0], node.range[1])}}` + ); + } }); } } diff --git a/tools/eslint/lib/rules/arrow-parens.js b/tools/eslint/lib/rules/arrow-parens.js index 67bfdf541c2955..e069e307eb2040 100644 --- a/tools/eslint/lib/rules/arrow-parens.js +++ b/tools/eslint/lib/rules/arrow-parens.js @@ -58,7 +58,9 @@ module.exports = { requireForBlockBody && node.params.length === 1 && node.params[0].type === "Identifier" && - node.body.type !== "BlockStatement" + !node.params[0].typeAnnotation && + node.body.type !== "BlockStatement" && + !node.returnType ) { if (token.type === "Punctuator" && token.value === "(") { context.report({ @@ -95,7 +97,12 @@ module.exports = { } // "as-needed": x => x - if (asNeeded && node.params.length === 1 && node.params[0].type === "Identifier") { + if (asNeeded && + node.params.length === 1 && + node.params[0].type === "Identifier" && + !node.params[0].typeAnnotation && + !node.returnType + ) { if (token.type === "Punctuator" && token.value === "(") { context.report({ node, diff --git a/tools/eslint/lib/rules/block-scoped-var.js b/tools/eslint/lib/rules/block-scoped-var.js index 0f4705a1f140d9..bb0931a3ceb63f 100644 --- a/tools/eslint/lib/rules/block-scoped-var.js +++ b/tools/eslint/lib/rules/block-scoped-var.js @@ -47,10 +47,7 @@ module.exports = { function report(reference) { const identifier = reference.identifier; - context.report( - identifier, - "'{{name}}' used outside of binding context.", - {name: identifier.name}); + context.report({ node: identifier, message: "'{{name}}' used outside of binding context.", data: { name: identifier.name } }); } /** diff --git a/tools/eslint/lib/rules/block-spacing.js b/tools/eslint/lib/rules/block-spacing.js index f18b3cceba3132..9c0a7f388ba3bb 100644 --- a/tools/eslint/lib/rules/block-spacing.js +++ b/tools/eslint/lib/rules/block-spacing.js @@ -22,7 +22,7 @@ module.exports = { fixable: "whitespace", schema: [ - {enum: ["always", "never"]} + { enum: ["always", "never"] } ] }, diff --git a/tools/eslint/lib/rules/brace-style.js b/tools/eslint/lib/rules/brace-style.js index 6bd8a8f4c87edb..197767b07c19a5 100644 --- a/tools/eslint/lib/rules/brace-style.js +++ b/tools/eslint/lib/rules/brace-style.js @@ -30,7 +30,9 @@ module.exports = { }, additionalProperties: false } - ] + ], + + fixable: "whitespace" }, create(context) { @@ -69,6 +71,28 @@ module.exports = { return token.value === "{" || token.value === "}"; } + /** + * Reports a place where a newline unexpectedly appears + * @param {ASTNode} node The node to report + * @param {string} message The message to report + * @param {Token} firstToken The token before the unexpected newline + * @returns {void} + */ + function reportExtraNewline(node, message, firstToken) { + context.report({ + node, + message, + fix(fixer) { + const secondToken = sourceCode.getTokenAfter(firstToken); + const textBetween = sourceCode.getText().slice(firstToken.range[1], secondToken.range[0]); + const NEWLINE_REGEX = /\r\n|\r|\n|\u2028|\u2029/g; + + // Don't do a fix if there is a comment between the tokens. + return textBetween.trim() ? null : fixer.replaceTextRange([firstToken.range[1], secondToken.range[0]], textBetween.replace(NEWLINE_REGEX, "")); + } + }); + } + /** * Binds a list of properties to a function that verifies that the opening * curly brace is on the same line as its controlling statement of a given @@ -81,7 +105,7 @@ module.exports = { const blockProperties = arguments; return function(node) { - Array.prototype.forEach.call(blockProperties, function(blockProp) { + Array.prototype.forEach.call(blockProperties, blockProp => { const block = node[blockProp]; if (!isBlock(block)) { @@ -98,9 +122,13 @@ module.exports = { } if (style !== "allman" && previousToken.loc.start.line !== curlyToken.loc.start.line) { - context.report(node, OPEN_MESSAGE); + reportExtraNewline(node, OPEN_MESSAGE, previousToken); } else if (style === "allman" && previousToken.loc.start.line === curlyToken.loc.start.line) { - context.report(node, OPEN_MESSAGE_ALLMAN); + context.report({ + node, + message: OPEN_MESSAGE_ALLMAN, + fix: fixer => fixer.insertTextBefore(curlyToken, "\n") + }); } if (!block.body.length) { @@ -108,11 +136,19 @@ module.exports = { } if (curlyToken.loc.start.line === block.body[0].loc.start.line) { - context.report(block.body[0], BODY_MESSAGE); + context.report({ + node: block.body[0], + message: BODY_MESSAGE, + fix: fixer => fixer.insertTextAfter(curlyToken, "\n") + }); } - if (curlyTokenEnd.loc.start.line === block.body[block.body.length - 1].loc.start.line) { - context.report(block.body[block.body.length - 1], CLOSE_MESSAGE_SINGLE); + if (curlyTokenEnd.loc.start.line === block.body[block.body.length - 1].loc.end.line) { + context.report({ + node: block.body[block.body.length - 1], + message: CLOSE_MESSAGE_SINGLE, + fix: fixer => fixer.insertTextBefore(curlyTokenEnd, "\n") + }); } }); }; @@ -135,10 +171,14 @@ module.exports = { if (tokens[0].loc.start.line !== tokens[1].loc.start.line && node.consequent.type === "BlockStatement" && isCurlyPunctuator(tokens[0])) { - context.report(node.alternate, CLOSE_MESSAGE); + reportExtraNewline(node.alternate, CLOSE_MESSAGE, tokens[0]); } } else if (tokens[0].loc.start.line === tokens[1].loc.start.line) { - context.report(node.alternate, CLOSE_MESSAGE_STROUSTRUP_ALLMAN); + context.report({ + node: node.alternate, + message: CLOSE_MESSAGE_STROUSTRUP_ALLMAN, + fix: fixer => fixer.insertTextAfter(tokens[0], "\n") + }); } } @@ -158,10 +198,14 @@ module.exports = { if (style === "1tbs") { if (tokens[0].loc.start.line !== tokens[1].loc.start.line) { - context.report(node.finalizer, CLOSE_MESSAGE); + reportExtraNewline(node.finalizer, CLOSE_MESSAGE, tokens[0]); } } else if (tokens[0].loc.start.line === tokens[1].loc.start.line) { - context.report(node.finalizer, CLOSE_MESSAGE_STROUSTRUP_ALLMAN); + context.report({ + node: node.finalizer, + message: CLOSE_MESSAGE_STROUSTRUP_ALLMAN, + fix: fixer => fixer.insertTextAfter(tokens[0], "\n") + }); } } } @@ -181,11 +225,15 @@ module.exports = { if (isBlock(node.body)) { if (style === "1tbs") { if (previousToken.loc.start.line !== firstToken.loc.start.line) { - context.report(node, CLOSE_MESSAGE); + reportExtraNewline(node, CLOSE_MESSAGE, previousToken); } } else { if (previousToken.loc.start.line === firstToken.loc.start.line) { - context.report(node, CLOSE_MESSAGE_STROUSTRUP_ALLMAN); + context.report({ + node, + message: CLOSE_MESSAGE_STROUSTRUP_ALLMAN, + fix: fixer => fixer.insertTextAfter(previousToken, "\n") + }); } } } @@ -207,9 +255,13 @@ module.exports = { } if (style !== "allman" && tokens[0].loc.start.line !== tokens[1].loc.start.line) { - context.report(node, OPEN_MESSAGE); + reportExtraNewline(node, OPEN_MESSAGE, tokens[0]); } else if (style === "allman" && tokens[0].loc.start.line === tokens[1].loc.start.line) { - context.report(node, OPEN_MESSAGE_ALLMAN); + context.report({ + node, + message: OPEN_MESSAGE_ALLMAN, + fix: fixer => fixer.insertTextBefore(tokens[1], "\n") + }); } } diff --git a/tools/eslint/lib/rules/callback-return.js b/tools/eslint/lib/rules/callback-return.js index 242ef666d2ac6e..08600c01e58cd1 100644 --- a/tools/eslint/lib/rules/callback-return.js +++ b/tools/eslint/lib/rules/callback-return.js @@ -164,7 +164,7 @@ module.exports = { // as long as you're the child of a function at this point you should be asked to return if (findClosestParentOfType(node, ["FunctionDeclaration", "FunctionExpression", "ArrowFunctionExpression"])) { - context.report(node, "Expected return with your callback function."); + context.report({ node, message: "Expected return with your callback function." }); } } diff --git a/tools/eslint/lib/rules/camelcase.js b/tools/eslint/lib/rules/camelcase.js index 1b22c25e675ca3..6fb1475b21dbcd 100644 --- a/tools/eslint/lib/rules/camelcase.js +++ b/tools/eslint/lib/rules/camelcase.js @@ -38,6 +38,7 @@ module.exports = { // contains reported nodes to avoid reporting twice on destructuring with shorthand notation const reported = []; + const ALLOWED_PARENT_TYPES = new Set(["CallExpression", "NewExpression"]); /** * Checks if a string contains an underscore and isn't all upper-case @@ -60,7 +61,7 @@ module.exports = { function report(node) { if (reported.indexOf(node) < 0) { reported.push(node); - context.report(node, "Identifier '{{name}}' is not in camel case.", { name: node.name }); + context.report({ node, message: "Identifier '{{name}}' is not in camel case.", data: { name: node.name } }); } } @@ -118,7 +119,7 @@ module.exports = { return; } - if (isUnderscored(name) && effectiveParent.type !== "CallExpression") { + if (isUnderscored(name) && !ALLOWED_PARENT_TYPES.has(effectiveParent.type)) { report(node); } @@ -131,7 +132,7 @@ module.exports = { } // Report anything that is underscored that isn't a CallExpression - } else if (isUnderscored(name) && effectiveParent.type !== "CallExpression") { + } else if (isUnderscored(name) && !ALLOWED_PARENT_TYPES.has(effectiveParent.type)) { report(node); } } diff --git a/tools/eslint/lib/rules/capitalized-comments.js b/tools/eslint/lib/rules/capitalized-comments.js new file mode 100644 index 00000000000000..29cff4450b535a --- /dev/null +++ b/tools/eslint/lib/rules/capitalized-comments.js @@ -0,0 +1,301 @@ +/** + * @fileoverview enforce or disallow capitalization of the first letter of a comment + * @author Kevin Partington + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const LETTER_PATTERN = require("../util/patterns/letters"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const ALWAYS_MESSAGE = "Comments should not begin with a lowercase character", + NEVER_MESSAGE = "Comments should not begin with an uppercase character", + DEFAULT_IGNORE_PATTERN = /^\s*(?:eslint|istanbul|jscs|jshint|globals?|exported)\b/, + WHITESPACE = /\s/g, + MAYBE_URL = /^\s*[^:/?#\s]+:\/\/[^?#]/, // TODO: Combine w/ max-len pattern? + DEFAULTS = { + ignorePattern: null, + ignoreInlineComments: false, + ignoreConsecutiveComments: false + }; + +/* + * Base schema body for defining the basic capitalization rule, ignorePattern, + * and ignoreInlineComments values. + * This can be used in a few different ways in the actual schema. + */ +const SCHEMA_BODY = { + type: "object", + properties: { + ignorePattern: { + type: "string" + }, + ignoreInlineComments: { + type: "boolean" + }, + ignoreConsecutiveComments: { + type: "boolean" + } + }, + additionalProperties: false +}; + +/** + * Get normalized options for either block or line comments from the given + * user-provided options. + * - If the user-provided options is just a string, returns a normalized + * set of options using default values for all other options. + * - If the user-provided options is an object, then a normalized option + * set is returned. Options specified in overrides will take priority + * over options specified in the main options object, which will in + * turn take priority over the rule's defaults. + * + * @param {Object|string} rawOptions The user-provided options. + * @param {string} which Either "line" or "block". + * @returns {Object} The normalized options. + */ +function getNormalizedOptions(rawOptions, which) { + if (!rawOptions) { + return Object.assign({}, DEFAULTS); + } + + return Object.assign({}, DEFAULTS, rawOptions[which] || rawOptions); +} + +/** + * Get normalized options for block and line comments. + * + * @param {Object|string} rawOptions The user-provided options. + * @returns {Object} An object with "Line" and "Block" keys and corresponding + * normalized options objects. + */ +function getAllNormalizedOptions(rawOptions) { + return { + Line: getNormalizedOptions(rawOptions, "line"), + Block: getNormalizedOptions(rawOptions, "block") + }; +} + +/** + * Creates a regular expression for each ignorePattern defined in the rule + * options. + * + * This is done in order to avoid invoking the RegExp constructor repeatedly. + * + * @param {Object} normalizedOptions The normalized rule options. + * @returns {void} + */ +function createRegExpForIgnorePatterns(normalizedOptions) { + Object.keys(normalizedOptions).forEach(key => { + const ignorePatternStr = normalizedOptions[key].ignorePattern; + + if (ignorePatternStr) { + const regExp = RegExp(`^\\s*(?:${ignorePatternStr})`); + + normalizedOptions[key].ignorePatternRegExp = regExp; + } + }); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = { + meta: { + docs: { + description: "enforce or disallow capitalization of the first letter of a comment", + category: "Stylistic Issues", + recommended: false + }, + fixable: "code", + schema: [ + { enum: ["always", "never"] }, + { + oneOf: [ + SCHEMA_BODY, + { + type: "object", + properties: { + line: SCHEMA_BODY, + block: SCHEMA_BODY + }, + additionalProperties: false + } + ] + } + ] + }, + + create(context) { + + const capitalize = context.options[0] || "always", + normalizedOptions = getAllNormalizedOptions(context.options[1]), + sourceCode = context.getSourceCode(); + + createRegExpForIgnorePatterns(normalizedOptions); + + //---------------------------------------------------------------------- + // Helpers + //---------------------------------------------------------------------- + + /** + * Checks whether a comment is an inline comment. + * + * For the purpose of this rule, a comment is inline if: + * 1. The comment is preceded by a token on the same line; and + * 2. The command is followed by a token on the same line. + * + * Note that the comment itself need not be single-line! + * + * Also, it follows from this definition that only block comments can + * be considered as possibly inline. This is because line comments + * would consume any following tokens on the same line as the comment. + * + * @param {ASTNode} comment The comment node to check. + * @returns {boolean} True if the comment is an inline comment, false + * otherwise. + */ + function isInlineComment(comment) { + const previousToken = sourceCode.getTokenOrCommentBefore(comment), + nextToken = sourceCode.getTokenOrCommentAfter(comment); + + return Boolean( + previousToken && + nextToken && + comment.loc.start.line === previousToken.loc.end.line && + comment.loc.end.line === nextToken.loc.start.line + ); + } + + /** + * Determine if a comment follows another comment. + * + * @param {ASTNode} comment The comment to check. + * @returns {boolean} True if the comment follows a valid comment. + */ + function isConsecutiveComment(comment) { + const previousTokenOrComment = sourceCode.getTokenOrCommentBefore(comment); + + return Boolean( + previousTokenOrComment && + ["Block", "Line"].indexOf(previousTokenOrComment.type) !== -1 + ); + } + + /** + * Check a comment to determine if it is valid for this rule. + * + * @param {ASTNode} comment The comment node to process. + * @param {Object} options The options for checking this comment. + * @returns {boolean} True if the comment is valid, false otherwise. + */ + function isCommentValid(comment, options) { + + // 1. Check for default ignore pattern. + if (DEFAULT_IGNORE_PATTERN.test(comment.value)) { + return true; + } + + // 2. Check for custom ignore pattern. + const commentWithoutAsterisks = comment.value + .replace(/\*/g, ""); + + if (options.ignorePatternRegExp && options.ignorePatternRegExp.test(commentWithoutAsterisks)) { + return true; + } + + // 3. Check for inline comments. + if (options.ignoreInlineComments && isInlineComment(comment)) { + return true; + } + + // 4. Is this a consecutive comment (and are we tolerating those)? + if (options.ignoreConsecutiveComments && isConsecutiveComment(comment)) { + return true; + } + + // 5. Does the comment start with a possible URL? + if (MAYBE_URL.test(commentWithoutAsterisks)) { + return true; + } + + // 6. Is the initial word character a letter? + const commentWordCharsOnly = commentWithoutAsterisks + .replace(WHITESPACE, ""); + + if (commentWordCharsOnly.length === 0) { + return true; + } + + const firstWordChar = commentWordCharsOnly[0]; + + if (!LETTER_PATTERN.test(firstWordChar)) { + return true; + } + + // 7. Check the case of the initial word character. + const isUppercase = firstWordChar !== firstWordChar.toLocaleLowerCase(), + isLowercase = firstWordChar !== firstWordChar.toLocaleUpperCase(); + + if (capitalize === "always" && isLowercase) { + return false; + } else if (capitalize === "never" && isUppercase) { + return false; + } + + return true; + } + + /** + * Process a comment to determine if it needs to be reported. + * + * @param {ASTNode} comment The comment node to process. + * @returns {void} + */ + function processComment(comment) { + const options = normalizedOptions[comment.type], + commentValid = isCommentValid(comment, options); + + if (!commentValid) { + const message = capitalize === "always" ? + ALWAYS_MESSAGE : + NEVER_MESSAGE; + + context.report({ + node: null, // Intentionally using loc instead + loc: comment.loc, + message, + fix(fixer) { + const match = comment.value.match(LETTER_PATTERN); + + return fixer.replaceTextRange( + + // Offset match.index by 2 to account for the first 2 characters that start the comment (// or /*) + [comment.range[0] + match.index + 2, comment.range[0] + match.index + 3], + capitalize === "always" ? match[0].toLocaleUpperCase() : match[0].toLocaleLowerCase() + ); + } + }); + } + } + + //---------------------------------------------------------------------- + // Public + //---------------------------------------------------------------------- + + return { + Program() { + const comments = sourceCode.getAllComments(); + + comments.forEach(processComment); + } + }; + } +}; diff --git a/tools/eslint/lib/rules/comma-dangle.js b/tools/eslint/lib/rules/comma-dangle.js index 763ee89fd5d55e..af7ab2767f5566 100644 --- a/tools/eslint/lib/rules/comma-dangle.js +++ b/tools/eslint/lib/rules/comma-dangle.js @@ -112,11 +112,11 @@ module.exports = { { type: "object", properties: { - arrays: {$refs: "#/defs/valueWithIgnore"}, - objects: {$refs: "#/defs/valueWithIgnore"}, - imports: {$refs: "#/defs/valueWithIgnore"}, - exports: {$refs: "#/defs/valueWithIgnore"}, - functions: {$refs: "#/defs/valueWithIgnore"} + arrays: { $refs: "#/defs/valueWithIgnore" }, + objects: { $refs: "#/defs/valueWithIgnore" }, + imports: { $refs: "#/defs/valueWithIgnore" }, + exports: { $refs: "#/defs/valueWithIgnore" }, + functions: { $refs: "#/defs/valueWithIgnore" } }, additionalProperties: false } @@ -171,15 +171,10 @@ module.exports = { function getTrailingToken(node, lastItem) { switch (node.type) { case "ObjectExpression": - case "ObjectPattern": case "ArrayExpression": - case "ArrayPattern": case "CallExpression": case "NewExpression": return sourceCode.getLastToken(node, 1); - case "FunctionDeclaration": - case "FunctionExpression": - return sourceCode.getTokenBefore(node.body, 1); default: { const nextToken = sourceCode.getTokenAfter(lastItem); diff --git a/tools/eslint/lib/rules/comma-spacing.js b/tools/eslint/lib/rules/comma-spacing.js index 72b5bad6badabe..f571cfa199675a 100644 --- a/tools/eslint/lib/rules/comma-spacing.js +++ b/tools/eslint/lib/rules/comma-spacing.js @@ -141,7 +141,7 @@ module.exports = { function addNullElementsToIgnoreList(node) { let previousToken = sourceCode.getFirstToken(node); - node.elements.forEach(function(element) { + node.elements.forEach(element => { let token; if (element === null) { @@ -164,7 +164,7 @@ module.exports = { return { "Program:exit"() { - tokensAndComments.forEach(function(token, i) { + tokensAndComments.forEach((token, i) => { if (!isComma(token)) { return; diff --git a/tools/eslint/lib/rules/comma-style.js b/tools/eslint/lib/rules/comma-style.js index f707ce80557e09..bb290f90b980d1 100644 --- a/tools/eslint/lib/rules/comma-style.js +++ b/tools/eslint/lib/rules/comma-style.js @@ -41,10 +41,22 @@ module.exports = { create(context) { const style = context.options[0] || "last", sourceCode = context.getSourceCode(); - let exceptions = {}; + const exceptions = { + ArrayPattern: true, + ArrowFunctionExpression: true, + CallExpression: true, + FunctionDeclaration: true, + FunctionExpression: true, + ImportDeclaration: true, + ObjectPattern: true, + }; if (context.options.length === 2 && context.options[1].hasOwnProperty("exceptions")) { - exceptions = context.options[1].exceptions; + const keys = Object.keys(context.options[1].exceptions); + + for (let i = 0; i < keys.length; i++) { + exceptions[keys[i]] = context.options[1].exceptions[keys[i]]; + } } //-------------------------------------------------------------------------- @@ -119,7 +131,7 @@ module.exports = { if (astUtils.isTokenOnSameLine(commaToken, currentItemToken) && astUtils.isTokenOnSameLine(previousItemToken, commaToken)) { - return; + // do nothing. } else if (!astUtils.isTokenOnSameLine(commaToken, currentItemToken) && !astUtils.isTokenOnSameLine(previousItemToken, commaToken)) { @@ -166,14 +178,14 @@ module.exports = { */ function validateComma(node, property) { const items = node[property], - arrayLiteral = (node.type === "ArrayExpression"); + arrayLiteral = (node.type === "ArrayExpression" || node.type === "ArrayPattern"); if (items.length > 1 || arrayLiteral) { // seed as opening [ let previousItemToken = sourceCode.getFirstToken(node); - items.forEach(function(item) { + items.forEach(item => { const commaToken = item ? sourceCode.getTokenBefore(item) : previousItemToken, currentItemToken = item ? sourceCode.getFirstToken(item) : sourceCode.getTokenAfter(commaToken), reportItem = item || currentItemToken, @@ -245,11 +257,46 @@ module.exports = { validateComma(node, "properties"); }; } + if (!exceptions.ObjectPattern) { + nodes.ObjectPattern = function(node) { + validateComma(node, "properties"); + }; + } if (!exceptions.ArrayExpression) { nodes.ArrayExpression = function(node) { validateComma(node, "elements"); }; } + if (!exceptions.ArrayPattern) { + nodes.ArrayPattern = function(node) { + validateComma(node, "elements"); + }; + } + if (!exceptions.FunctionDeclaration) { + nodes.FunctionDeclaration = function(node) { + validateComma(node, "params"); + }; + } + if (!exceptions.FunctionExpression) { + nodes.FunctionExpression = function(node) { + validateComma(node, "params"); + }; + } + if (!exceptions.ArrowFunctionExpression) { + nodes.ArrowFunctionExpression = function(node) { + validateComma(node, "params"); + }; + } + if (!exceptions.CallExpression) { + nodes.CallExpression = function(node) { + validateComma(node, "arguments"); + }; + } + if (!exceptions.ImportDeclaration) { + nodes.ImportDeclaration = function(node) { + validateComma(node, "specifiers"); + }; + } return nodes; } diff --git a/tools/eslint/lib/rules/complexity.js b/tools/eslint/lib/rules/complexity.js index 0d837e74d3b650..2f3e4040799872 100644 --- a/tools/eslint/lib/rules/complexity.js +++ b/tools/eslint/lib/rules/complexity.js @@ -91,7 +91,7 @@ module.exports = { } if (complexity > THRESHOLD) { - context.report(node, "Function '{{name}}' has a complexity of {{complexity}}.", { name, complexity }); + context.report({ node, message: "Function '{{name}}' has a complexity of {{complexity}}.", data: { name, complexity } }); } } diff --git a/tools/eslint/lib/rules/consistent-return.js b/tools/eslint/lib/rules/consistent-return.js index eed69c2cb78ac3..0c1a6a7493f663 100644 --- a/tools/eslint/lib/rules/consistent-return.js +++ b/tools/eslint/lib/rules/consistent-return.js @@ -33,6 +33,18 @@ function isUnreachable(segment) { return !segment.reachable; } +/** +* Checks whether a given node is a `constructor` method in an ES6 class +* @param {ASTNode} node A node to check +* @returns {boolean} `true` if the node is a `constructor` method +*/ +function isClassConstructor(node) { + return node.type === "FunctionExpression" && + node.parent && + node.parent.type === "MethodDefinition" && + node.parent.kind === "constructor"; +} + //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ @@ -77,7 +89,8 @@ module.exports = { */ if (!funcInfo.hasReturnValue || funcInfo.codePath.currentSegments.every(isUnreachable) || - astUtils.isES5Constructor(node) + astUtils.isES5Constructor(node) || + isClassConstructor(node) ) { return; } @@ -86,7 +99,7 @@ module.exports = { if (node.type === "Program") { // The head of program. - loc = {line: 1, column: 0}; + loc = { line: 1, column: 0 }; type = "program"; } else if (node.type === "ArrowFunctionExpression") { @@ -113,7 +126,7 @@ module.exports = { node, loc, message: "Expected to return a value at the end of this {{type}}.", - data: {type} + data: { type } }); } diff --git a/tools/eslint/lib/rules/consistent-this.js b/tools/eslint/lib/rules/consistent-this.js index 2a068ed1fc2add..35c2d56272a638 100644 --- a/tools/eslint/lib/rules/consistent-this.js +++ b/tools/eslint/lib/rules/consistent-this.js @@ -43,9 +43,7 @@ module.exports = { * @returns {void} */ function reportBadAssignment(node, alias) { - context.report(node, - "Designated alias '{{alias}}' is not assigned to 'this'.", - { alias }); + context.report({ node, message: "Designated alias '{{alias}}' is not assigned to 'this'.", data: { alias } }); } /** @@ -64,8 +62,7 @@ module.exports = { reportBadAssignment(node, name); } } else if (isThis) { - context.report(node, - "Unexpected alias '{{name}}' for 'this'.", { name }); + context.report({ node, message: "Unexpected alias '{{name}}' for 'this'.", data: { name } }); } } @@ -84,16 +81,14 @@ module.exports = { return; } - if (variable.defs.some(function(def) { - return def.node.type === "VariableDeclarator" && - def.node.init !== null; - })) { + if (variable.defs.some(def => def.node.type === "VariableDeclarator" && + def.node.init !== null)) { return; } // The alias has been declared and not assigned: check it was // assigned later in the same scope. - if (!variable.references.some(function(reference) { + if (!variable.references.some(reference => { const write = reference.writeExpr; return ( @@ -102,9 +97,7 @@ module.exports = { write.parent.operator === "=" ); })) { - variable.defs.map(function(def) { - return def.node; - }).forEach(function(node) { + variable.defs.map(def => def.node).forEach(node => { reportBadAssignment(node, alias); }); } @@ -117,7 +110,7 @@ module.exports = { function ensureWasAssigned() { const scope = context.getScope(); - aliases.forEach(function(alias) { + aliases.forEach(alias => { checkWasAssigned(alias, scope); }); } diff --git a/tools/eslint/lib/rules/constructor-super.js b/tools/eslint/lib/rules/constructor-super.js index 49271cee5899be..e84df7e81da025 100644 --- a/tools/eslint/lib/rules/constructor-super.js +++ b/tools/eslint/lib/rules/constructor-super.js @@ -261,8 +261,8 @@ module.exports = { const isRealLoop = toSegment.prevSegments.length >= 2; funcInfo.codePath.traverseSegments( - {first: toSegment, last: fromSegment}, - function(segment) { + { first: toSegment, last: fromSegment }, + segment => { const info = segInfoMap[segment.id]; const prevSegments = segment.prevSegments; diff --git a/tools/eslint/lib/rules/curly.js b/tools/eslint/lib/rules/curly.js index 02d74a1e037560..801552d69e151b 100644 --- a/tools/eslint/lib/rules/curly.js +++ b/tools/eslint/lib/rules/curly.js @@ -74,10 +74,11 @@ module.exports = { * @private */ function isCollapsedOneLiner(node) { - const before = sourceCode.getTokenBefore(node), - last = sourceCode.getLastToken(node); + const before = sourceCode.getTokenBefore(node); + const last = sourceCode.getLastToken(node); + const lastExcludingSemicolon = last.type === "Punctuator" && last.value === ";" ? sourceCode.getTokenBefore(last) : last; - return before.loc.start.line === last.loc.end.line; + return before.loc.start.line === lastExcludingSemicolon.loc.end.line; } /** @@ -195,7 +196,7 @@ module.exports = { return true; } - if (/^[(\[\/`+-]/.test(tokenAfter.value)) { + if (/^[([/`+-]/.test(tokenAfter.value)) { // If the next token starts with a character that would disrupt ASI, insert a semicolon. return true; @@ -289,7 +290,9 @@ module.exports = { } } else if (multiOrNest) { if (hasBlock && body.body.length === 1 && isOneLiner(body.body[0])) { - expected = false; + const leadingComments = sourceCode.getComments(body.body[0]).leading; + + expected = leadingComments.length > 0; } else if (!isOneLiner(body)) { expected = true; } @@ -337,14 +340,14 @@ module.exports = { * all have braces. * If all nodes shouldn't have braces, make sure they don't. */ - const expected = preparedChecks.some(function(preparedCheck) { + const expected = preparedChecks.some(preparedCheck => { if (preparedCheck.expected !== null) { return preparedCheck.expected; } return preparedCheck.actual; }); - preparedChecks.forEach(function(preparedCheck) { + preparedChecks.forEach(preparedCheck => { preparedCheck.expected = expected; }); } @@ -359,7 +362,7 @@ module.exports = { return { IfStatement(node) { if (node.parent.type !== "IfStatement") { - prepareIfChecks(node).forEach(function(preparedCheck) { + prepareIfChecks(node).forEach(preparedCheck => { preparedCheck.check(); }); } diff --git a/tools/eslint/lib/rules/default-case.js b/tools/eslint/lib/rules/default-case.js index e062798db235ab..070ff3c7a9666b 100644 --- a/tools/eslint/lib/rules/default-case.js +++ b/tools/eslint/lib/rules/default-case.js @@ -4,7 +4,7 @@ */ "use strict"; -const DEFAULT_COMMENT_PATTERN = /^no default$/; +const DEFAULT_COMMENT_PATTERN = /^no default$/i; //------------------------------------------------------------------------------ // Rule Definition @@ -67,9 +67,7 @@ module.exports = { return; } - const hasDefault = node.cases.some(function(v) { - return v.test === null; - }); + const hasDefault = node.cases.some(v => v.test === null); if (!hasDefault) { @@ -83,7 +81,7 @@ module.exports = { } if (!comment || !commentPattern.test(comment.value.trim())) { - context.report(node, "Expected a default case."); + context.report({ node, message: "Expected a default case." }); } } } diff --git a/tools/eslint/lib/rules/eqeqeq.js b/tools/eslint/lib/rules/eqeqeq.js index 4d61399f207ba7..d77607afb5f2aa 100644 --- a/tools/eslint/lib/rules/eqeqeq.js +++ b/tools/eslint/lib/rules/eqeqeq.js @@ -47,7 +47,9 @@ module.exports = { additionalItems: false } ] - } + }, + + fixable: "code" }, create(context) { @@ -112,22 +114,32 @@ module.exports = { function getOperatorLocation(node) { const opToken = sourceCode.getTokenAfter(node.left); - return {line: opToken.loc.start.line, column: opToken.loc.start.column}; + return { line: opToken.loc.start.line, column: opToken.loc.start.column }; } /** * Reports a message for this rule. * @param {ASTNode} node The binary expression node that was checked - * @param {string} message The message to report + * @param {string} expectedOperator The operator that was expected (either '==', '!=', '===', or '!==') * @returns {void} * @private */ - function report(node, message) { + function report(node, expectedOperator) { context.report({ node, loc: getOperatorLocation(node), - message, - data: { op: node.operator.charAt(0) } + message: "Expected '{{expectedOperator}}' and instead saw '{{actualOperator}}'.", + data: { expectedOperator, actualOperator: node.operator }, + fix(fixer) { + + // If the comparison is a `typeof` comparison or both sides are literals with the same type, then it's safe to fix. + if (isTypeOfBinary(node) || areLiteralsAndSameType(node)) { + const operatorToken = sourceCode.getTokensBetween(node.left, node.right).find(token => token.value === node.operator); + + return fixer.replaceText(operatorToken, expectedOperator); + } + return null; + } }); } @@ -137,7 +149,7 @@ module.exports = { if (node.operator !== "==" && node.operator !== "!=") { if (enforceInverseRuleForNull && isNull) { - report(node, "Expected '{{op}}=' and instead saw '{{op}}=='."); + report(node, node.operator.slice(0, -1)); } return; } @@ -151,7 +163,7 @@ module.exports = { return; } - report(node, "Expected '{{op}}==' and instead saw '{{op}}='."); + report(node, `${node.operator}=`); } }; diff --git a/tools/eslint/lib/rules/func-call-spacing.js b/tools/eslint/lib/rules/func-call-spacing.js index 417f2bdf313e17..5c416f0373fcac 100644 --- a/tools/eslint/lib/rules/func-call-spacing.js +++ b/tools/eslint/lib/rules/func-call-spacing.js @@ -120,7 +120,14 @@ module.exports = { loc: lastCalleeToken.loc.start, message: "Unexpected space between function name and paren.", fix(fixer) { - return fixer.removeRange([prevToken.range[1], parenToken.range[0]]); + + // Only autofix if there is no newline + // https://github.com/eslint/eslint/issues/7787 + if (!hasNewline) { + return fixer.removeRange([prevToken.range[1], parenToken.range[0]]); + } + + return null; } }); } else if (!never && !hasWhitespace) { diff --git a/tools/eslint/lib/rules/func-name-matching.js b/tools/eslint/lib/rules/func-name-matching.js index d4d760cbe45f1b..4eed7a68ea2b51 100644 --- a/tools/eslint/lib/rules/func-name-matching.js +++ b/tools/eslint/lib/rules/func-name-matching.js @@ -54,6 +54,17 @@ function isIdentifier(name, ecmaVersion) { // Rule Definition //------------------------------------------------------------------------------ +const alwaysOrNever = { enum: ["always", "never"] }; +const optionsObject = { + type: "object", + properties: { + includeCommonJSModuleExports: { + type: "boolean" + } + }, + additionalProperties: false +}; + module.exports = { meta: { docs: { @@ -62,24 +73,35 @@ module.exports = { recommended: false }, - schema: [ - { - type: "object", - properties: { - includeCommonJSModuleExports: { - type: "boolean" - } - }, - additionalProperties: false - } - ] + schema: { + anyOf: [{ + type: "array", + additionalItems: false, + items: [alwaysOrNever, optionsObject] + }, { + type: "array", + additionalItems: false, + items: [optionsObject] + }] + } }, create(context) { - - const includeModuleExports = context.options[0] && context.options[0].includeCommonJSModuleExports; + const options = (typeof context.options[0] === "object" ? context.options[0] : context.options[1]) || {}; + const nameMatches = typeof context.options[0] === "string" ? context.options[0] : "always"; + const includeModuleExports = options.includeCommonJSModuleExports; const ecmaVersion = context.parserOptions && context.parserOptions.ecmaVersion ? context.parserOptions.ecmaVersion : 5; + /** + * Compares identifiers based on the nameMatches option + * @param {string} x the first identifier + * @param {string} y the second identifier + * @returns {boolean} whether the two identifiers should warn. + */ + function shouldWarn(x, y) { + return (nameMatches === "always" && x !== y) || (nameMatches === "never" && x === y); + } + /** * Reports * @param {ASTNode} node The node to report @@ -89,10 +111,20 @@ module.exports = { * @returns {void} */ function report(node, name, funcName, isProp) { + let message; + + if (nameMatches === "always" && isProp) { + message = "Function name `{{funcName}}` should match property name `{{name}}`"; + } else if (nameMatches === "always") { + message = "Function name `{{funcName}}` should match variable name `{{name}}`"; + } else if (isProp) { + message = "Function name `{{funcName}}` should not match property name `{{name}}`"; + } else { + message = "Function name `{{funcName}}` should not match variable name `{{name}}`"; + } context.report({ node, - message: isProp ? "Function name `{{funcName}}` should match property name `{{name}}`" - : "Function name `{{funcName}}` should match variable name `{{name}}`", + message, data: { name, funcName @@ -110,7 +142,7 @@ module.exports = { if (!node.init || node.init.type !== "FunctionExpression") { return; } - if (node.init.id && node.id.name !== node.init.id.name) { + if (node.init.id && shouldWarn(node.id.name, node.init.id.name)) { report(node, node.id.name, node.init.id.name, false); } }, @@ -126,7 +158,7 @@ module.exports = { const isProp = node.left.type === "MemberExpression" ? true : false; const name = isProp ? astUtils.getStaticPropertyName(node.left) : node.left.name; - if (node.right.id && isIdentifier(name) && name !== node.right.id.name) { + if (node.right.id && isIdentifier(name) && shouldWarn(name, node.right.id.name)) { report(node, name, node.right.id.name, isProp); } }, @@ -135,12 +167,13 @@ module.exports = { if (node.value.type !== "FunctionExpression" || !node.value.id || node.computed && node.key.type !== "Literal") { return; } - if (node.key.type === "Identifier" && node.key.name !== node.value.id.name) { + if (node.key.type === "Identifier" && shouldWarn(node.key.name, node.value.id.name)) { report(node, node.key.name, node.value.id.name, true); - } else if (node.key.type === "Literal" && - isIdentifier(node.key.value, ecmaVersion) && - node.key.value !== node.value.id.name - ) { + } else if ( + node.key.type === "Literal" && + isIdentifier(node.key.value, ecmaVersion) && + shouldWarn(node.key.value, node.value.id.name) + ) { report(node, node.key.value, node.value.id.name, true); } } diff --git a/tools/eslint/lib/rules/func-names.js b/tools/eslint/lib/rules/func-names.js index 397ef37e91614d..0d8567149493dc 100644 --- a/tools/eslint/lib/rules/func-names.js +++ b/tools/eslint/lib/rules/func-names.js @@ -28,21 +28,23 @@ module.exports = { schema: [ { - enum: ["always", "never"] + enum: ["always", "as-needed", "never"] } ] }, create(context) { const never = context.options[0] === "never"; + const asNeeded = context.options[0] === "as-needed"; /** * Determines whether the current FunctionExpression node is a get, set, or * shorthand method in an object literal or a class. + * @param {ASTNode} node - A node to check. * @returns {boolean} True if the node is a get, set, or shorthand method. */ - function isObjectOrClassMethod() { - const parent = context.getAncestors().pop(); + function isObjectOrClassMethod(node) { + const parent = node.parent; return (parent.type === "MethodDefinition" || ( parent.type === "Property" && ( @@ -53,6 +55,23 @@ module.exports = { )); } + /** + * Determines whether the current FunctionExpression node has a name that would be + * inferred from context in a conforming ES6 environment. + * @param {ASTNode} node - A node to check. + * @returns {boolean} True if the node would have a name assigned automatically. + */ + function hasInferredName(node) { + const parent = node.parent; + + return isObjectOrClassMethod(node) || + (parent.type === "VariableDeclarator" && parent.id.type === "Identifier" && parent.init === node) || + (parent.type === "Property" && parent.value === node) || + (parent.type === "AssignmentExpression" && parent.left.type === "Identifier" && parent.right === node) || + (parent.type === "ExportDefaultDeclaration" && parent.declaration === node) || + (parent.type === "AssignmentPattern" && parent.right === node); + } + return { "FunctionExpression:exit"(node) { @@ -67,11 +86,11 @@ module.exports = { if (never) { if (name) { - context.report(node, "Unexpected function expression name."); + context.report({ node, message: "Unexpected function expression name." }); } } else { - if (!name && !isObjectOrClassMethod()) { - context.report(node, "Missing function expression name."); + if (!name && (asNeeded ? !hasInferredName(node) : !isObjectOrClassMethod(node))) { + context.report({ node, message: "Missing function expression name." }); } } } diff --git a/tools/eslint/lib/rules/func-style.js b/tools/eslint/lib/rules/func-style.js index e0974209c4bb78..123eae3d8a406f 100644 --- a/tools/eslint/lib/rules/func-style.js +++ b/tools/eslint/lib/rules/func-style.js @@ -44,7 +44,7 @@ module.exports = { stack.push(false); if (!enforceDeclarations && node.parent.type !== "ExportDefaultDeclaration") { - context.report(node, "Expected a function expression."); + context.report({ node, message: "Expected a function expression." }); } }, "FunctionDeclaration:exit"() { @@ -55,7 +55,7 @@ module.exports = { stack.push(false); if (enforceDeclarations && node.parent.type === "VariableDeclarator") { - context.report(node.parent, "Expected a function declaration."); + context.report({ node: node.parent, message: "Expected a function declaration." }); } }, "FunctionExpression:exit"() { @@ -78,7 +78,7 @@ module.exports = { const hasThisExpr = stack.pop(); if (enforceDeclarations && !hasThisExpr && node.parent.type === "VariableDeclarator") { - context.report(node.parent, "Expected a function declaration."); + context.report({ node: node.parent, message: "Expected a function declaration." }); } }; } diff --git a/tools/eslint/lib/rules/generator-star-spacing.js b/tools/eslint/lib/rules/generator-star-spacing.js index f9ec3a4af52c25..fc676d0cbbb85f 100644 --- a/tools/eslint/lib/rules/generator-star-spacing.js +++ b/tools/eslint/lib/rules/generator-star-spacing.js @@ -28,8 +28,8 @@ module.exports = { { type: "object", properties: { - before: {type: "boolean"}, - after: {type: "boolean"} + before: { type: "boolean" }, + after: { type: "boolean" } }, additionalProperties: false } diff --git a/tools/eslint/lib/rules/global-require.js b/tools/eslint/lib/rules/global-require.js index 3d6492cfde4671..bfd01433957e3e 100644 --- a/tools/eslint/lib/rules/global-require.js +++ b/tools/eslint/lib/rules/global-require.js @@ -23,10 +23,8 @@ const ACCEPTABLE_PARENTS = [ * @returns {Reference|null} Returns the found reference or null if none were found. */ function findReference(scope, node) { - const references = scope.references.filter(function(reference) { - return reference.identifier.range[0] === node.range[0] && - reference.identifier.range[1] === node.range[1]; - }); + const references = scope.references.filter(reference => reference.identifier.range[0] === node.range[0] && + reference.identifier.range[1] === node.range[1]); /* istanbul ignore else: correctly returns null */ if (references.length === 1) { @@ -65,12 +63,10 @@ module.exports = { const currentScope = context.getScope(); if (node.callee.name === "require" && !isShadowed(currentScope, node.callee)) { - const isGoodRequire = context.getAncestors().every(function(parent) { - return ACCEPTABLE_PARENTS.indexOf(parent.type) > -1; - }); + const isGoodRequire = context.getAncestors().every(parent => ACCEPTABLE_PARENTS.indexOf(parent.type) > -1); if (!isGoodRequire) { - context.report(node, "Unexpected require()."); + context.report({ node, message: "Unexpected require()." }); } } } diff --git a/tools/eslint/lib/rules/guard-for-in.js b/tools/eslint/lib/rules/guard-for-in.js index 7ccfec90c1c572..754830f6a64be3 100644 --- a/tools/eslint/lib/rules/guard-for-in.js +++ b/tools/eslint/lib/rules/guard-for-in.js @@ -33,7 +33,7 @@ module.exports = { const body = node.body.type === "BlockStatement" ? node.body.body[0] : node.body; if (body && body.type !== "IfStatement") { - context.report(node, "The body of a for-in should be wrapped in an if statement to filter unwanted properties from the prototype."); + context.report({ node, message: "The body of a for-in should be wrapped in an if statement to filter unwanted properties from the prototype." }); } } }; diff --git a/tools/eslint/lib/rules/handle-callback-err.js b/tools/eslint/lib/rules/handle-callback-err.js index e8c6d1b3b8f647..de36a0c1b002c6 100644 --- a/tools/eslint/lib/rules/handle-callback-err.js +++ b/tools/eslint/lib/rules/handle-callback-err.js @@ -59,9 +59,7 @@ module.exports = { * @returns {array} All parameters of the given scope. */ function getParameters(scope) { - return scope.variables.filter(function(variable) { - return variable.defs[0] && variable.defs[0].type === "Parameter"; - }); + return scope.variables.filter(variable => variable.defs[0] && variable.defs[0].type === "Parameter"); } /** @@ -76,7 +74,7 @@ module.exports = { if (firstParameter && matchesConfiguredErrorName(firstParameter.name)) { if (firstParameter.references.length === 0) { - context.report(node, "Expected error to be handled."); + context.report({ node, message: "Expected error to be handled." }); } } } diff --git a/tools/eslint/lib/rules/id-blacklist.js b/tools/eslint/lib/rules/id-blacklist.js index 8795cfc6be6964..f94f6d0a4684d4 100644 --- a/tools/eslint/lib/rules/id-blacklist.js +++ b/tools/eslint/lib/rules/id-blacklist.js @@ -67,9 +67,9 @@ module.exports = { * @private */ function report(node) { - context.report(node, "Identifier '{{name}}' is blacklisted.", { + context.report({ node, message: "Identifier '{{name}}' is blacklisted.", data: { name: node.name - }); + } }); } return { diff --git a/tools/eslint/lib/rules/id-length.js b/tools/eslint/lib/rules/id-length.js index 1747552707901c..6a6c69d1017e8c 100644 --- a/tools/eslint/lib/rules/id-length.js +++ b/tools/eslint/lib/rules/id-length.js @@ -50,7 +50,7 @@ module.exports = { const maxLength = typeof options.max !== "undefined" ? options.max : Infinity; const properties = options.properties !== "never"; const exceptions = (options.exceptions ? options.exceptions : []) - .reduce(function(obj, item) { + .reduce((obj, item) => { obj[item] = true; return obj; @@ -102,13 +102,13 @@ module.exports = { const isValidExpression = SUPPORTED_EXPRESSIONS[parent.type]; if (isValidExpression && (isValidExpression === true || isValidExpression(parent, node))) { - context.report( + context.report({ node, - isShort ? + message: isShort ? "Identifier name '{{name}}' is too short (< {{min}})." : "Identifier name '{{name}}' is too long (> {{max}}).", - { name, min: minLength, max: maxLength } - ); + data: { name, min: minLength, max: maxLength } + }); } } }; diff --git a/tools/eslint/lib/rules/id-match.js b/tools/eslint/lib/rules/id-match.js index 961a1859049d24..29d06c36024c57 100644 --- a/tools/eslint/lib/rules/id-match.js +++ b/tools/eslint/lib/rules/id-match.js @@ -75,10 +75,10 @@ module.exports = { * @private */ function report(node) { - context.report(node, "Identifier '{{name}}' does not match the pattern '{{pattern}}'.", { + context.report({ node, message: "Identifier '{{name}}' does not match the pattern '{{pattern}}'.", data: { name: node.name, pattern - }); + } }); } return { diff --git a/tools/eslint/lib/rules/indent.js b/tools/eslint/lib/rules/indent.js index 2b069011f99d02..6c3c27c8e1941a 100644 --- a/tools/eslint/lib/rules/indent.js +++ b/tools/eslint/lib/rules/indent.js @@ -113,6 +113,44 @@ module.exports = { minimum: 0 } } + }, + CallExpression: { + type: "object", + properties: { + parameters: { + oneOf: [ + { + type: "integer", + minimum: 0 + }, + { + enum: ["first"] + } + ] + } + } + }, + ArrayExpression: { + oneOf: [ + { + type: "integer", + minimum: 0 + }, + { + enum: ["first"] + } + ] + }, + ObjectExpression: { + oneOf: [ + { + type: "integer", + minimum: 0 + }, + { + enum: ["first"] + } + ] } }, additionalProperties: false @@ -142,7 +180,12 @@ module.exports = { FunctionExpression: { parameters: DEFAULT_PARAMETER_INDENT, body: DEFAULT_FUNCTION_BODY_INDENT - } + }, + CallExpression: { + arguments: DEFAULT_PARAMETER_INDENT + }, + ArrayExpression: 1, + ObjectExpression: 1 }; const sourceCode = context.getSourceCode(); @@ -187,6 +230,18 @@ module.exports = { if (typeof opts.FunctionExpression === "object") { Object.assign(options.FunctionExpression, opts.FunctionExpression); } + + if (typeof opts.CallExpression === "object") { + Object.assign(options.CallExpression, opts.CallExpression); + } + + if (typeof opts.ArrayExpression === "number" || typeof opts.ArrayExpression === "string") { + options.ArrayExpression = opts.ArrayExpression; + } + + if (typeof opts.ObjectExpression === "number" || typeof opts.ObjectExpression === "string") { + options.ObjectExpression = opts.ObjectExpression; + } } } @@ -229,10 +284,10 @@ module.exports = { * @param {int} gottenTabs Indentation tab count in the actual node/code * @param {Object=} loc Error line and column location * @param {boolean} isLastNodeCheck Is the error for last node check + * @param {int} lastNodeCheckEndOffset Number of charecters to skip from the end * @returns {void} */ function report(node, needed, gottenSpaces, gottenTabs, loc, isLastNodeCheck) { - if (gottenSpaces && gottenTabs) { // To avoid conflicts with `no-mixed-spaces-and-tabs`, don't report lines that have both spaces and tabs. @@ -242,8 +297,8 @@ module.exports = { const desiredIndent = (indentType === "space" ? " " : "\t").repeat(needed); const textRange = isLastNodeCheck - ? [node.range[1] - gottenSpaces - gottenTabs - 1, node.range[1] - 1] - : [node.range[0] - gottenSpaces - gottenTabs, node.range[0]]; + ? [node.range[1] - node.loc.end.column, node.range[1] - node.loc.end.column + gottenSpaces + gottenTabs] + : [node.range[0] - node.loc.start.column, node.range[0] - node.loc.start.column + gottenSpaces + gottenTabs]; context.report({ node, @@ -319,6 +374,24 @@ module.exports = { checkNodeIndent(node.alternate, neededIndent); } } + + if (node.type === "TryStatement" && node.handler) { + const catchToken = sourceCode.getFirstToken(node.handler); + + checkNodeIndent(catchToken, neededIndent); + } + + if (node.type === "TryStatement" && node.finalizer) { + const finallyToken = sourceCode.getTokenBefore(node.finalizer); + + checkNodeIndent(finallyToken, neededIndent); + } + + if (node.type === "DoWhileStatement") { + const whileToken = sourceCode.getTokenAfter(node.body); + + checkNodeIndent(whileToken, neededIndent); + } } /** @@ -354,6 +427,45 @@ module.exports = { } } + /** + * Check last node line indent this detects, that block closed correctly + * This function for more complicated return statement case, where closing parenthesis may be followed by ';' + * @param {ASTNode} node Node to examine + * @param {int} firstLineIndent first line needed indent + * @returns {void} + */ + function checkLastReturnStatementLineIndent(node, firstLineIndent) { + const nodeLastToken = sourceCode.getLastToken(node); + let lastToken = nodeLastToken; + + // in case if return statement ends with ');' we have traverse back to ')' + // otherwise we'll measure indent for ';' and replace ')' + while (lastToken.value !== ")") { + lastToken = sourceCode.getTokenBefore(lastToken); + } + + const textBeforeClosingParenthesis = sourceCode.getText(lastToken, lastToken.loc.start.column).slice(0, -1); + + if (textBeforeClosingParenthesis.trim()) { + + // There are tokens before the closing paren, don't report this case + return; + } + + const endIndent = getNodeIndent(lastToken, true); + + if (endIndent.goodChar !== firstLineIndent) { + report( + node, + firstLineIndent, + endIndent.space, + endIndent.tab, + { line: lastToken.loc.start.line, column: lastToken.loc.start.column }, + true + ); + } + } + /** * Check first node line indent is correct * @param {ASTNode} node Node to examine @@ -379,12 +491,17 @@ module.exports = { * if not present then return null * @param {ASTNode} node node to examine * @param {string} type type that is being looked for + * @param {string} stopAtList end points for the evaluating code * @returns {ASTNode|void} if found then node otherwise null */ - function getParentNodeByType(node, type) { + function getParentNodeByType(node, type, stopAtList) { let parent = node.parent; - while (parent.type !== type && parent.type !== "Program") { + if (!stopAtList) { + stopAtList = ["Program"]; + } + + while (parent.type !== type && stopAtList.indexOf(parent.type) === -1 && parent.type !== "Program") { parent = parent.parent; } @@ -401,16 +518,6 @@ module.exports = { return getParentNodeByType(node, "VariableDeclarator"); } - /** - * Returns the ExpressionStatement based on the current node - * if not present then return null - * @param {ASTNode} node node to examine - * @returns {ASTNode|void} if found then node otherwise null - */ - function getAssignmentExpressionNode(node) { - return getParentNodeByType(node, "AssignmentExpression"); - } - /** * Check to see if the node is part of the multi-line variable declaration. * Also if its on the same line as the varNode @@ -604,14 +711,7 @@ module.exports = { let elements = (node.type === "ArrayExpression") ? node.elements : node.properties; // filter out empty elements example would be [ , 2] so remove first element as espree considers it as null - elements = elements.filter(function(elem) { - return elem !== null; - }); - - // Skip if first element is in same line with this node - if (elements.length > 0 && elements[0].loc.start.line === node.loc.start.line) { - return; - } + elements = elements.filter(elem => elem !== null); let nodeIndent; let elementsIndent; @@ -620,41 +720,59 @@ module.exports = { // TODO - come up with a better strategy in future if (isNodeFirstInLine(node)) { const parent = node.parent; - let effectiveParent = parent; - if (parent.type === "MemberExpression") { - if (isNodeFirstInLine(parent)) { - effectiveParent = parent.parent.parent; - } else { - effectiveParent = parent.parent; - } - } - nodeIndent = getNodeIndent(effectiveParent).goodChar; - if (parentVarNode && parentVarNode.loc.start.line !== node.loc.start.line) { + nodeIndent = getNodeIndent(parent).goodChar; + if (!parentVarNode || parentVarNode.loc.start.line !== node.loc.start.line) { if (parent.type !== "VariableDeclarator" || parentVarNode === parentVarNode.parent.declarations[0]) { - if (parent.type === "VariableDeclarator" && parentVarNode.loc.start.line === effectiveParent.loc.start.line) { + if (parent.type === "VariableDeclarator" && parentVarNode.loc.start.line === parent.loc.start.line) { nodeIndent = nodeIndent + (indentSize * options.VariableDeclarator[parentVarNode.parent.kind]); - } else if ( - parent.type === "ObjectExpression" || - parent.type === "ArrayExpression" || - parent.type === "CallExpression" || - parent.type === "ArrowFunctionExpression" || - parent.type === "NewExpression" || - parent.type === "LogicalExpression" - ) { - nodeIndent = nodeIndent + indentSize; + } else if (parent.type === "ObjectExpression" || parent.type === "ArrayExpression") { + const parentElements = node.parent.type === "ObjectExpression" ? node.parent.properties : node.parent.elements; + + if (parentElements[0].loc.start.line === parent.loc.start.line && parentElements[0].loc.end.line !== parent.loc.start.line) { + + /* + * If the first element of the array spans multiple lines, don't increase the expected indentation of the rest. + * e.g. [{ + * foo: 1 + * }, + * { + * bar: 1 + * }] + * the second object is not indented. + */ + } else if (typeof options[parent.type] === "number") { + nodeIndent += options[parent.type] * indentSize; + } else { + nodeIndent = parentElements[0].loc.start.column; + } + } else if (parent.type === "CallExpression" || parent.type === "NewExpression") { + if (typeof options.CallExpression.arguments === "number") { + nodeIndent += options.CallExpression.arguments * indentSize; + } else if (options.CallExpression.arguments === "first") { + if (parent.arguments.indexOf(node) !== -1) { + nodeIndent = parent.arguments[0].loc.start.column; + } + } else { + nodeIndent += indentSize; + } + } else if (parent.type === "LogicalExpression" || parent.type === "ArrowFunctionExpression") { + nodeIndent += indentSize; } } - } else if (!parentVarNode && !isFirstArrayElementOnSameLine(parent) && effectiveParent.type !== "MemberExpression" && effectiveParent.type !== "ExpressionStatement" && effectiveParent.type !== "AssignmentExpression" && effectiveParent.type !== "Property") { + } else if (!parentVarNode && !isFirstArrayElementOnSameLine(parent) && parent.type !== "MemberExpression" && parent.type !== "ExpressionStatement" && parent.type !== "AssignmentExpression" && parent.type !== "Property") { nodeIndent = nodeIndent + indentSize; } - elementsIndent = nodeIndent + indentSize; - checkFirstNodeLineIndent(node, nodeIndent); } else { nodeIndent = getNodeIndent(node).goodChar; - elementsIndent = nodeIndent + indentSize; + } + + if (options[node.type] === "first") { + elementsIndent = elements.length ? elements[0].loc.start.column : 0; // If there are no elements, elementsIndent doesn't matter. + } else { + elementsIndent = nodeIndent + indentSize * options[node.type]; } /* @@ -675,7 +793,7 @@ module.exports = { } } - checkLastNodeLineIndent(node, elementsIndent - indentSize); + checkLastNodeLineIndent(node, nodeIndent + (isNodeInVarOnTop(node, parentVarNode) ? options.VariableDeclarator[parentVarNode.parent.kind] * indentSize : 0)); } /** @@ -717,11 +835,13 @@ module.exports = { * not from the beginning of the block. */ const statementsWithProperties = [ - "IfStatement", "WhileStatement", "ForStatement", "ForInStatement", "ForOfStatement", "DoWhileStatement", "ClassDeclaration" + "IfStatement", "WhileStatement", "ForStatement", "ForInStatement", "ForOfStatement", "DoWhileStatement", "ClassDeclaration", "TryStatement" ]; if (node.parent && statementsWithProperties.indexOf(node.parent.type) !== -1 && isNodeBodyBlock(node)) { indent = getNodeIndent(node.parent).goodChar; + } else if (node.parent && node.parent.type === "CatchClause") { + indent = getNodeIndent(node.parent.parent).goodChar; } else { indent = getNodeIndent(node).goodChar; } @@ -750,7 +870,7 @@ module.exports = { * @returns {ASTNode[]} Filtered elements */ function filterOutSameLineVars(node) { - return node.declarations.reduce(function(finalCollection, elem) { + return node.declarations.reduce((finalCollection, elem) => { const lastElem = finalCollection[finalCollection.length - 1]; if ((elem.loc.start.line !== node.loc.start.line && !lastElem) || @@ -832,6 +952,20 @@ module.exports = { } } + /** + * Checks wether a return statement is wrapped in () + * @param {ASTNode} node node to examine + * @returns {boolean} the result + */ + function isWrappedInParenthesis(node) { + const regex = /^return\s*?\(\s*?\);*?/; + + const statementWithoutArgument = sourceCode.getText(node).replace( + sourceCode.getText(node.argument), ""); + + return regex.test(statementWithoutArgument); + } + return { Program(node) { if (node.body.length > 0) { @@ -876,6 +1010,7 @@ module.exports = { }, MemberExpression(node) { + if (typeof options.MemberExpression === "undefined") { return; } @@ -888,11 +1023,11 @@ module.exports = { // alter the expectation of correct indentation. Skip them. // TODO: Add appropriate configuration options for variable // declarations and assignments. - if (getVariableDeclaratorNode(node)) { + if (getParentNodeByType(node, "VariableDeclarator", ["FunctionExpression", "ArrowFunctionExpression"])) { return; } - if (getAssignmentExpressionNode(node)) { + if (getParentNodeByType(node, "AssignmentExpression", ["FunctionExpression"])) { return; } @@ -952,7 +1087,34 @@ module.exports = { } else if (options.FunctionExpression.parameters !== null) { checkNodesIndent(node.params, getNodeIndent(node).goodChar + indentSize * options.FunctionExpression.parameters); } + }, + + ReturnStatement(node) { + if (isSingleLineNode(node)) { + return; + } + + const firstLineIndent = getNodeIndent(node).goodChar; + + // in case if return statement is wrapped in parenthesis + if (isWrappedInParenthesis(node)) { + checkLastReturnStatementLineIndent(node, firstLineIndent); + } else { + checkNodeIndent(node, firstLineIndent); + } + }, + + CallExpression(node) { + if (isSingleLineNode(node)) { + return; + } + if (options.CallExpression.arguments === "first" && node.arguments.length) { + checkNodesIndent(node.arguments.slice(1), node.arguments[0].loc.start.column); + } else if (options.CallExpression.arguments !== null) { + checkNodesIndent(node.arguments, getNodeIndent(node).goodChar + indentSize * options.CallExpression.arguments); + } } + }; } diff --git a/tools/eslint/lib/rules/jsx-quotes.js b/tools/eslint/lib/rules/jsx-quotes.js index 2b6a57b961d88f..5653922d9495d5 100644 --- a/tools/eslint/lib/rules/jsx-quotes.js +++ b/tools/eslint/lib/rules/jsx-quotes.js @@ -48,7 +48,7 @@ module.exports = { schema: [ { - enum: [ "prefer-single", "prefer-double" ] + enum: ["prefer-single", "prefer-double"] } ] }, diff --git a/tools/eslint/lib/rules/key-spacing.js b/tools/eslint/lib/rules/key-spacing.js index b195d31d32a4ee..8d7564a5bbf246 100644 --- a/tools/eslint/lib/rules/key-spacing.js +++ b/tools/eslint/lib/rules/key-spacing.js @@ -417,8 +417,8 @@ module.exports = { function report(property, side, whitespace, expected, mode) { const diff = whitespace.length - expected, nextColon = getNextColon(property.key), - tokenBeforeColon = sourceCode.getTokenBefore(nextColon), - tokenAfterColon = sourceCode.getTokenAfter(nextColon), + tokenBeforeColon = sourceCode.getTokenOrCommentBefore(nextColon), + tokenAfterColon = sourceCode.getTokenOrCommentAfter(nextColon), isKeySide = side === "key", locStart = isKeySide ? tokenBeforeColon.loc.start : tokenAfterColon.loc.start, isExtra = diff > 0, @@ -514,7 +514,7 @@ module.exports = { return [node.properties]; } - return node.properties.reduce(function(groups, property) { + return node.properties.reduce((groups, property) => { const currentGroup = last(groups), prev = last(currentGroup); @@ -579,7 +579,7 @@ module.exports = { * @returns {void} */ function verifyAlignment(node) { - createGroups(node).forEach(function(group) { + createGroups(node).forEach(group => { verifyGroupAlignment(group.filter(isKeyValueProperty)); }); } diff --git a/tools/eslint/lib/rules/keyword-spacing.js b/tools/eslint/lib/rules/keyword-spacing.js index 4a6a024552111c..1dfc291f6e827b 100644 --- a/tools/eslint/lib/rules/keyword-spacing.js +++ b/tools/eslint/lib/rules/keyword-spacing.js @@ -16,10 +16,10 @@ const astUtils = require("../ast-utils"), // Constants //------------------------------------------------------------------------------ -const PREV_TOKEN = /^[\)\]\}>]$/; -const NEXT_TOKEN = /^(?:[\(\[\{<~!]|\+\+?|--?)$/; -const PREV_TOKEN_M = /^[\)\]\}>*]$/; -const NEXT_TOKEN_M = /^[\{*]$/; +const PREV_TOKEN = /^[)\]}>]$/; +const NEXT_TOKEN = /^(?:[([{<~!]|\+\+?|--?)$/; +const PREV_TOKEN_M = /^[)\]}>*]$/; +const NEXT_TOKEN_M = /^[{*]$/; const TEMPLATE_OPEN_PAREN = /\$\{$/; const TEMPLATE_CLOSE_PAREN = /^\}/; const CHECK_TYPE = /^(?:JSXElement|RegularExpression|String|Template)$/; @@ -77,16 +77,16 @@ module.exports = { { type: "object", properties: { - before: {type: "boolean"}, - after: {type: "boolean"}, + before: { type: "boolean" }, + after: { type: "boolean" }, overrides: { type: "object", - properties: KEYS.reduce(function(retv, key) { + properties: KEYS.reduce((retv, key) => { retv[key] = { type: "object", properties: { - before: {type: "boolean"}, - after: {type: "boolean"} + before: { type: "boolean" }, + after: { type: "boolean" } }, additionalProperties: false }; diff --git a/tools/eslint/lib/rules/lines-around-comment.js b/tools/eslint/lib/rules/lines-around-comment.js index 094fefa74f4646..83751cd6a50ad6 100644 --- a/tools/eslint/lib/rules/lines-around-comment.js +++ b/tools/eslint/lib/rules/lines-around-comment.js @@ -21,16 +21,10 @@ const lodash = require("lodash"), * @returns {Array} An array of line numbers. */ function getEmptyLineNums(lines) { - const emptyLines = lines.map(function(line, i) { - return { - code: line.trim(), - num: i + 1 - }; - }).filter(function(line) { - return !line.code; - }).map(function(line) { - return line.num; - }); + const emptyLines = lines.map((line, i) => ({ + code: line.trim(), + num: i + 1 + })).filter(line => !line.code).map(line => line.num); return emptyLines; } @@ -43,7 +37,7 @@ function getEmptyLineNums(lines) { function getCommentLineNums(comments) { const lines = []; - comments.forEach(function(token) { + comments.forEach(token => { const start = token.loc.start.line; const end = token.loc.end.line; diff --git a/tools/eslint/lib/rules/lines-around-directive.js b/tools/eslint/lib/rules/lines-around-directive.js index f0f0ebd0b9037b..b1e54e940b8f64 100644 --- a/tools/eslint/lib/rules/lines-around-directive.js +++ b/tools/eslint/lib/rules/lines-around-directive.js @@ -63,15 +63,32 @@ module.exports = { return node.loc.start.line - tokenLineBefore >= 2; } + /** + * Gets the last token of a node that is on the same line as the rest of the node. + * This will usually be the last token of the node, but it will be the second-to-last token if the node has a trailing + * semicolon on a different line. + * @param {ASTNode} node A directive node + * @returns {Token} The last token of the node on the line + */ + function getLastTokenOnLine(node) { + const lastToken = sourceCode.getLastToken(node); + const secondToLastToken = sourceCode.getTokenBefore(lastToken); + + return lastToken.type === "Punctuator" && lastToken.value === ";" && lastToken.loc.start.line > secondToLastToken.loc.end.line + ? secondToLastToken + : lastToken; + } + /** * Check if node is followed by a blank newline. * @param {ASTNode} node Node to check. * @returns {boolean} Whether or not the passed in node is followed by a blank newline. */ function hasNewlineAfter(node) { - const tokenAfter = sourceCode.getTokenOrCommentAfter(node); + const lastToken = getLastTokenOnLine(node); + const tokenAfter = sourceCode.getTokenOrCommentAfter(lastToken); - return tokenAfter.loc.start.line - node.loc.end.line >= 2; + return tokenAfter.loc.start.line - lastToken.loc.end.line >= 2; } /** @@ -91,10 +108,12 @@ module.exports = { location }, fix(fixer) { + const lastToken = getLastTokenOnLine(node); + if (expected) { - return location === "before" ? fixer.insertTextBefore(node, "\n") : fixer.insertTextAfter(node, "\n"); + return location === "before" ? fixer.insertTextBefore(node, "\n") : fixer.insertTextAfter(lastToken, "\n"); } - return fixer.removeRange(location === "before" ? [node.range[0] - 1, node.range[0]] : [node.range[1], node.range[1] + 1]); + return fixer.removeRange(location === "before" ? [node.range[0] - 1, node.range[0]] : [lastToken.range[1], lastToken.range[1] + 1]); } }); } diff --git a/tools/eslint/lib/rules/max-depth.js b/tools/eslint/lib/rules/max-depth.js index 35b7e9ce8946de..74c13ffa9fad2e 100644 --- a/tools/eslint/lib/rules/max-depth.js +++ b/tools/eslint/lib/rules/max-depth.js @@ -91,8 +91,7 @@ module.exports = { const len = ++functionStack[functionStack.length - 1]; if (len > maxDepth) { - context.report(node, "Blocks are nested too deeply ({{depth}}).", - { depth: len }); + context.report({ node, message: "Blocks are nested too deeply ({{depth}}).", data: { depth: len } }); } } diff --git a/tools/eslint/lib/rules/max-len.js b/tools/eslint/lib/rules/max-len.js index d1f6df2996f9aa..dd5a4e1ef62553 100644 --- a/tools/eslint/lib/rules/max-len.js +++ b/tools/eslint/lib/rules/max-len.js @@ -39,6 +39,9 @@ const OPTIONS_SCHEMA = { ignoreTemplateLiterals: { type: "boolean" }, + ignoreRegExpLiterals: { + type: "boolean" + }, ignoreTrailingComments: { type: "boolean" } @@ -100,7 +103,7 @@ module.exports = { function computeLineLength(line, tabWidth) { let extraCharacterCount = 0; - line.replace(/\t/g, function(match, offset) { + line.replace(/\t/g, (match, offset) => { const totalOffset = offset + extraCharacterCount, previousTabStopOffset = tabWidth ? totalOffset % tabWidth : 0, spaceCount = tabWidth - previousTabStopOffset; @@ -129,6 +132,7 @@ module.exports = { ignoreComments = options.ignoreComments || false, ignoreStrings = options.ignoreStrings || false, ignoreTemplateLiterals = options.ignoreTemplateLiterals || false, + ignoreRegExpLiterals = options.ignoreRegExpLiterals || false, ignoreTrailingComments = options.ignoreTrailingComments || options.ignoreComments || false, ignoreUrls = options.ignoreUrls || false, maxCommentLength = options.comments; @@ -209,9 +213,7 @@ module.exports = { * @returns {ASTNode[]} An array of string nodes. */ function getAllStrings() { - return sourceCode.ast.tokens.filter(function(token) { - return token.type === "String"; - }); + return sourceCode.ast.tokens.filter(token => token.type === "String"); } /** @@ -220,9 +222,17 @@ module.exports = { * @returns {ASTNode[]} An array of template literal nodes. */ function getAllTemplateLiterals() { - return sourceCode.ast.tokens.filter(function(token) { - return token.type === "Template"; - }); + return sourceCode.ast.tokens.filter(token => token.type === "Template"); + } + + + /** + * Retrieves an array containing all RegExp literals in the source code. + * + * @returns {ASTNode[]} An array of RegExp literal nodes. + */ + function getAllRegExpLiterals() { + return sourceCode.ast.tokens.filter(token => token.type === "RegularExpression"); } @@ -264,7 +274,10 @@ module.exports = { const templateLiterals = getAllTemplateLiterals(sourceCode); const templateLiteralsByLine = templateLiterals.reduce(groupByLineNumber, {}); - lines.forEach(function(line, i) { + const regExpLiterals = getAllRegExpLiterals(sourceCode); + const regExpLiteralsByLine = regExpLiterals.reduce(groupByLineNumber, {}); + + lines.forEach((line, i) => { // i is zero-indexed, line numbers are one-indexed const lineNumber = i + 1; @@ -299,7 +312,8 @@ module.exports = { if (ignorePattern && ignorePattern.test(line) || ignoreUrls && URL_REGEXP.test(line) || ignoreStrings && stringsByLine[lineNumber] || - ignoreTemplateLiterals && templateLiteralsByLine[lineNumber] + ignoreTemplateLiterals && templateLiteralsByLine[lineNumber] || + ignoreRegExpLiterals && regExpLiteralsByLine[lineNumber] ) { // ignore this line diff --git a/tools/eslint/lib/rules/max-lines.js b/tools/eslint/lib/rules/max-lines.js index a54ad9e3538dbc..08cf9f6084b2a1 100644 --- a/tools/eslint/lib/rules/max-lines.js +++ b/tools/eslint/lib/rules/max-lines.js @@ -114,26 +114,18 @@ module.exports = { return { "Program:exit"() { - let lines = sourceCode.lines.map(function(text, i) { - return { lineNumber: i + 1, text }; - }); + let lines = sourceCode.lines.map((text, i) => ({ lineNumber: i + 1, text })); if (skipBlankLines) { - lines = lines.filter(function(l) { - return l.text.trim() !== ""; - }); + lines = lines.filter(l => l.text.trim() !== ""); } if (skipComments) { const comments = sourceCode.getAllComments(); - const commentLines = lodash.flatten(comments.map(function(comment) { - return getLinesWithoutCode(comment); - })); + const commentLines = lodash.flatten(comments.map(comment => getLinesWithoutCode(comment))); - lines = lines.filter(function(l) { - return !lodash.includes(commentLines, l.lineNumber); - }); + lines = lines.filter(l => !lodash.includes(commentLines, l.lineNumber)); } if (lines.length > max) { diff --git a/tools/eslint/lib/rules/max-nested-callbacks.js b/tools/eslint/lib/rules/max-nested-callbacks.js index 7e0c3d24738862..a89f49ae02094e 100644 --- a/tools/eslint/lib/rules/max-nested-callbacks.js +++ b/tools/eslint/lib/rules/max-nested-callbacks.js @@ -81,9 +81,9 @@ module.exports = { } if (callbackStack.length > THRESHOLD) { - const opts = {num: callbackStack.length, max: THRESHOLD}; + const opts = { num: callbackStack.length, max: THRESHOLD }; - context.report(node, "Too many nested callbacks ({{num}}). Maximum allowed is {{max}}.", opts); + context.report({ node, message: "Too many nested callbacks ({{num}}). Maximum allowed is {{max}}.", data: opts }); } } diff --git a/tools/eslint/lib/rules/max-params.js b/tools/eslint/lib/rules/max-params.js index fc84efcd40b285..bbf087092e5057 100644 --- a/tools/eslint/lib/rules/max-params.js +++ b/tools/eslint/lib/rules/max-params.js @@ -66,10 +66,10 @@ module.exports = { */ function checkFunction(node) { if (node.params.length > numParams) { - context.report(node, "This function has too many parameters ({{count}}). Maximum allowed is {{max}}.", { + context.report({ node, message: "This function has too many parameters ({{count}}). Maximum allowed is {{max}}.", data: { count: node.params.length, max: numParams - }); + } }); } } diff --git a/tools/eslint/lib/rules/max-statements.js b/tools/eslint/lib/rules/max-statements.js index 1232930c6e68f1..63d51fa571b7b0 100644 --- a/tools/eslint/lib/rules/max-statements.js +++ b/tools/eslint/lib/rules/max-statements.js @@ -84,10 +84,20 @@ module.exports = { */ function reportIfTooManyStatements(node, count, max) { if (count > max) { - context.report( + const messageEnd = " has too many statements ({{count}}). Maximum allowed is {{max}}."; + let name = "This function"; + + if (node.id) { + name = `Function '${node.id.name}'`; + } else if (node.parent.type === "MethodDefinition" || node.parent.type === "Property") { + name = `Function '${context.getSource(node.parent.key)}'`; + } + + context.report({ node, - "This function has too many statements ({{count}}). Maximum allowed is {{max}}.", - { count, max }); + message: name + messageEnd, + data: { count, max } + }); } } @@ -110,7 +120,7 @@ module.exports = { const count = functionStack.pop(); if (ignoreTopLevelFunctions && functionStack.length === 0) { - topLevelFunctions.push({ node, count}); + topLevelFunctions.push({ node, count }); } else { reportIfTooManyStatements(node, count, maxStatements); } @@ -146,7 +156,7 @@ module.exports = { return; } - topLevelFunctions.forEach(function(element) { + topLevelFunctions.forEach(element => { const count = element.count; const node = element.node; diff --git a/tools/eslint/lib/rules/new-cap.js b/tools/eslint/lib/rules/new-cap.js index 6fcd582a694d1a..e7f7f1ab893396 100644 --- a/tools/eslint/lib/rules/new-cap.js +++ b/tools/eslint/lib/rules/new-cap.js @@ -227,7 +227,7 @@ module.exports = { callee = callee.property; } - context.report(node, callee.loc.start, message); + context.report({ node, loc: callee.loc.start, message }); } //-------------------------------------------------------------------------- diff --git a/tools/eslint/lib/rules/new-parens.js b/tools/eslint/lib/rules/new-parens.js index 29f4b5c2082152..b0fc5ba97950b7 100644 --- a/tools/eslint/lib/rules/new-parens.js +++ b/tools/eslint/lib/rules/new-parens.js @@ -29,20 +29,6 @@ function isClosingParen(token) { return token.type === "Punctuator" && token.value === ")"; } -/** - * Checks whether the given node is inside of another given node. - * - * @param {ASTNode|Token} inner - The inner node to check. - * @param {ASTNode|Token} outer - The outer node to check. - * @returns {boolean} `true` if the `inner` is in `outer`. - */ -function isInRange(inner, outer) { - const ir = inner.range; - const or = outer.range; - - return or[0] <= ir[0] && ir[1] <= or[1]; -} - //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ @@ -65,14 +51,15 @@ module.exports = { return { NewExpression(node) { - let token = sourceCode.getTokenAfter(node.callee); - - // Skip ')' - while (token && isClosingParen(token)) { - token = sourceCode.getTokenAfter(token); + if (node.arguments.length !== 0) { + return; // shortcut: if there are arguments, there have to be parens } - if (!(token && isOpeningParen(token) && isInRange(token, node))) { + const lastToken = sourceCode.getLastToken(node); + const hasLastParen = lastToken && isClosingParen(lastToken); + const hasParens = hasLastParen && isOpeningParen(sourceCode.getTokenBefore(lastToken)); + + if (!hasParens) { context.report({ node, message: "Missing '()' invoking a constructor.", diff --git a/tools/eslint/lib/rules/newline-after-var.js b/tools/eslint/lib/rules/newline-after-var.js index 440652b1c10696..51130e23db9ffe 100644 --- a/tools/eslint/lib/rules/newline-after-var.js +++ b/tools/eslint/lib/rules/newline-after-var.js @@ -21,7 +21,9 @@ module.exports = { { enum: ["never", "always"] } - ] + ], + + fixable: "whitespace" }, create(context) { @@ -35,7 +37,7 @@ module.exports = { const mode = context.options[0] === "never" ? "never" : "always"; // Cache starting and ending line numbers of comments for faster lookup - const commentEndLine = sourceCode.getAllComments().reduce(function(result, token) { + const commentEndLine = sourceCode.getAllComments().reduce((result, token) => { result[token.loc.start.line] = token.loc.end.line; return result; }, {}); @@ -119,6 +121,17 @@ module.exports = { return !token || (token.type === "Punctuator" && token.value === "}"); } + /** + * Gets the last line of a group of consecutive comments + * @param {number} commentStartLine The starting line of the group + * @returns {number} The number of the last comment line of the group + */ + function getLastCommentLineOfBlock(commentStartLine) { + const currentCommentEnd = commentEndLine[commentStartLine]; + + return commentEndLine[currentCommentEnd + 1] ? getLastCommentLineOfBlock(currentCommentEnd + 1) : currentCommentEnd; + } + /** * Determine if a token starts more than one line after a comment ends * @param {token} token The token being checked @@ -126,14 +139,7 @@ module.exports = { * @returns {boolean} True if `token` does not start immediately after a comment */ function hasBlankLineAfterComment(token, commentStartLine) { - const commentEnd = commentEndLine[commentStartLine]; - - // If there's another comment, repeat check for blank line - if (commentEndLine[commentEnd + 1]) { - return hasBlankLineAfterComment(token, commentEnd + 1); - } - - return (token.loc.start.line > commentEndLine[commentStartLine] + 1); + return token.loc.start.line > getLastCommentLineOfBlock(commentStartLine) + 1; } /** @@ -145,8 +151,18 @@ module.exports = { * @returns {void} */ function checkForBlankLine(node) { + + /* + * lastToken is the last token on the node's line. It will usually also be the last token of the node, but it will + * sometimes be second-last if there is a semicolon on a different line. + */ const lastToken = getLastToken(node), - nextToken = sourceCode.getTokenAfter(node), + + /* + * If lastToken is the last token of the node, nextToken should be the token after the node. Otherwise, nextToken + * is the last token of the node. + */ + nextToken = lastToken === sourceCode.getLastToken(node) ? sourceCode.getTokenAfter(node) : sourceCode.getLastToken(node), nextLineNum = lastToken.loc.end.line + 1; // Ignore if there is no following statement @@ -180,7 +196,17 @@ module.exports = { const hasNextLineComment = (typeof commentEndLine[nextLineNum] !== "undefined"); if (mode === "never" && noNextLineToken && !hasNextLineComment) { - context.report(node, NEVER_MESSAGE, { identifier: node.name }); + context.report({ + node, + message: NEVER_MESSAGE, + data: { identifier: node.name }, + fix(fixer) { + const NEWLINE_REGEX = /\r\n|\r|\n|\u2028|\u2029/; + const linesBetween = sourceCode.getText().slice(lastToken.range[1], nextToken.range[0]).split(NEWLINE_REGEX); + + return fixer.replaceTextRange([lastToken.range[1], nextToken.range[0]], `${linesBetween.slice(0, -1).join("")}\n${linesBetween[linesBetween.length - 1]}`); + } + }); } // Token on the next line, or comment without blank line @@ -190,7 +216,18 @@ module.exports = { hasNextLineComment && !hasBlankLineAfterComment(nextToken, nextLineNum) ) ) { - context.report(node, ALWAYS_MESSAGE, { identifier: node.name }); + context.report({ + node, + message: ALWAYS_MESSAGE, + data: { identifier: node.name }, + fix(fixer) { + if ((noNextLineToken ? getLastCommentLineOfBlock(nextLineNum) : lastToken.loc.end.line) === nextToken.loc.start.line) { + return fixer.insertTextBefore(nextToken, "\n\n"); + } + + return fixer.insertTextBeforeRange([nextToken.range[0] - nextToken.loc.start.column, nextToken.range[1]], "\n"); + } + }); } } diff --git a/tools/eslint/lib/rules/newline-before-return.js b/tools/eslint/lib/rules/newline-before-return.js index 7d297fd0035313..e8cd74b2c7b728 100644 --- a/tools/eslint/lib/rules/newline-before-return.js +++ b/tools/eslint/lib/rules/newline-before-return.js @@ -36,9 +36,7 @@ module.exports = { function isPrecededByTokens(node, testTokens) { const tokenBefore = sourceCode.getTokenBefore(node); - return testTokens.some(function(token) { - return tokenBefore.value === token; - }); + return testTokens.some(token => tokenBefore.value === token); } /** @@ -82,7 +80,7 @@ module.exports = { return numLinesComments; } - comments.forEach(function(comment) { + comments.forEach(comment => { numLinesComments++; if (comment.type === "Block") { diff --git a/tools/eslint/lib/rules/no-alert.js b/tools/eslint/lib/rules/no-alert.js index 96b5d64c6c4e6b..f2cfc3a87762d2 100644 --- a/tools/eslint/lib/rules/no-alert.js +++ b/tools/eslint/lib/rules/no-alert.js @@ -41,10 +41,8 @@ function report(context, node, identifierName) { * @returns {Reference|null} Returns the found reference or null if none were found. */ function findReference(scope, node) { - const references = scope.references.filter(function(reference) { - return reference.identifier.range[0] === node.range[0] && - reference.identifier.range[1] === node.range[1]; - }); + const references = scope.references.filter(reference => reference.identifier.range[0] === node.range[0] && + reference.identifier.range[1] === node.range[1]); if (references.length === 1) { return references[0]; diff --git a/tools/eslint/lib/rules/no-array-constructor.js b/tools/eslint/lib/rules/no-array-constructor.js index 2c29217d720fcc..70dc8b4cd5ded8 100644 --- a/tools/eslint/lib/rules/no-array-constructor.js +++ b/tools/eslint/lib/rules/no-array-constructor.js @@ -34,7 +34,7 @@ module.exports = { node.callee.type === "Identifier" && node.callee.name === "Array" ) { - context.report(node, "The array literal notation [] is preferrable."); + context.report({ node, message: "The array literal notation [] is preferrable." }); } } diff --git a/tools/eslint/lib/rules/no-await-in-loop.js b/tools/eslint/lib/rules/no-await-in-loop.js new file mode 100644 index 00000000000000..a75f7f2934bc23 --- /dev/null +++ b/tools/eslint/lib/rules/no-await-in-loop.js @@ -0,0 +1,75 @@ +/** + * @fileoverview Rule to disallow uses of await inside of loops. + * @author Nat Mote (nmote) + */ +"use strict"; + +// Node types which are considered loops. +const loopTypes = new Set([ + "ForStatement", + "ForOfStatement", + "ForInStatement", + "WhileStatement", + "DoWhileStatement", +]); + +// Node types at which we should stop looking for loops. For example, it is fine to declare an async +// function within a loop, and use await inside of that. +const boundaryTypes = new Set([ + "FunctionDeclaration", + "FunctionExpression", + "ArrowFunctionExpression", +]); + +module.exports = { + meta: { + docs: { + description: "disallow `await` inside of loops", + category: "Possible Errors", + recommended: false, + }, + schema: [], + }, + create(context) { + return { + AwaitExpression(node) { + const ancestors = context.getAncestors(); + + // Reverse so that we can traverse from the deepest node upwards. + ancestors.reverse(); + + // Create a set of all the ancestors plus this node so that we can check + // if this use of await appears in the body of the loop as opposed to + // the right-hand side of a for...of, for example. + const ancestorSet = new Set(ancestors).add(node); + + for (let i = 0; i < ancestors.length; i++) { + const ancestor = ancestors[i]; + + if (boundaryTypes.has(ancestor.type)) { + + // Short-circuit out if we encounter a boundary type. Loops above + // this do not matter. + return; + } + if (loopTypes.has(ancestor.type)) { + + // Only report if we are actually in the body or another part that gets executed on + // every iteration. + if ( + ancestorSet.has(ancestor.body) || + ancestorSet.has(ancestor.test) || + ancestorSet.has(ancestor.update) + ) { + context.report({ + node, + message: "Unexpected `await` inside a loop." + }); + return; + } + } + } + }, + }; + } +}; diff --git a/tools/eslint/lib/rules/no-bitwise.js b/tools/eslint/lib/rules/no-bitwise.js index 2c6456912f70f8..28028028cae090 100644 --- a/tools/eslint/lib/rules/no-bitwise.js +++ b/tools/eslint/lib/rules/no-bitwise.js @@ -57,7 +57,7 @@ module.exports = { * @returns {void} */ function report(node) { - context.report(node, "Unexpected use of '{{operator}}'.", { operator: node.operator }); + context.report({ node, message: "Unexpected use of '{{operator}}'.", data: { operator: node.operator } }); } /** diff --git a/tools/eslint/lib/rules/no-caller.js b/tools/eslint/lib/rules/no-caller.js index 16c5fa414b0cb8..55a37b7d86406a 100644 --- a/tools/eslint/lib/rules/no-caller.js +++ b/tools/eslint/lib/rules/no-caller.js @@ -29,7 +29,7 @@ module.exports = { propertyName = node.property.name; if (objectName === "arguments" && !node.computed && propertyName && propertyName.match(/^calle[er]$/)) { - context.report(node, "Avoid arguments.{{property}}.", { property: propertyName }); + context.report({ node, message: "Avoid arguments.{{property}}.", data: { property: propertyName } }); } } diff --git a/tools/eslint/lib/rules/no-catch-shadow.js b/tools/eslint/lib/rules/no-catch-shadow.js index 7f2523333239a7..7cffae3b99d758 100644 --- a/tools/eslint/lib/rules/no-catch-shadow.js +++ b/tools/eslint/lib/rules/no-catch-shadow.js @@ -58,8 +58,7 @@ module.exports = { } if (paramIsShadowing(scope, node.param.name)) { - context.report(node, "Value of '{{name}}' may be overwritten in IE 8 and earlier.", - { name: node.param.name }); + context.report({ node, message: "Value of '{{name}}' may be overwritten in IE 8 and earlier.", data: { name: node.param.name } }); } } }; diff --git a/tools/eslint/lib/rules/no-class-assign.js b/tools/eslint/lib/rules/no-class-assign.js index cbd4b1da81fe42..4b0443abc72858 100644 --- a/tools/eslint/lib/rules/no-class-assign.js +++ b/tools/eslint/lib/rules/no-class-assign.js @@ -30,11 +30,8 @@ module.exports = { * @returns {void} */ function checkVariable(variable) { - astUtils.getModifyingReferences(variable.references).forEach(function(reference) { - context.report( - reference.identifier, - "'{{name}}' is a class.", - {name: reference.identifier.name}); + astUtils.getModifyingReferences(variable.references).forEach(reference => { + context.report({ node: reference.identifier, message: "'{{name}}' is a class.", data: { name: reference.identifier.name } }); }); } diff --git a/tools/eslint/lib/rules/no-cond-assign.js b/tools/eslint/lib/rules/no-cond-assign.js index 2d66f55a5ba77b..3e94d12a539942 100644 --- a/tools/eslint/lib/rules/no-cond-assign.js +++ b/tools/eslint/lib/rules/no-cond-assign.js @@ -125,9 +125,9 @@ module.exports = { const ancestor = findConditionalAncestor(node); if (ancestor) { - context.report(ancestor, "Unexpected assignment within {{type}}.", { + context.report({ node: ancestor, message: "Unexpected assignment within {{type}}.", data: { type: NODE_DESCRIPTIONS[ancestor.type] || ancestor.type - }); + } }); } } diff --git a/tools/eslint/lib/rules/no-confusing-arrow.js b/tools/eslint/lib/rules/no-confusing-arrow.js index 5e1b051423d674..d6edbcc810e4fb 100644 --- a/tools/eslint/lib/rules/no-confusing-arrow.js +++ b/tools/eslint/lib/rules/no-confusing-arrow.js @@ -36,7 +36,7 @@ module.exports = { schema: [{ type: "object", properties: { - allowParens: {type: "boolean"} + allowParens: { type: "boolean" } }, additionalProperties: false }] @@ -55,7 +55,7 @@ module.exports = { const body = node.body; if (isConditional(body) && !(config.allowParens && astUtils.isParenthesised(sourceCode, body))) { - context.report(node, "Arrow function used ambiguously with a conditional expression."); + context.report({ node, message: "Arrow function used ambiguously with a conditional expression." }); } } diff --git a/tools/eslint/lib/rules/no-const-assign.js b/tools/eslint/lib/rules/no-const-assign.js index 232e9446fd7955..db1848a9819f00 100644 --- a/tools/eslint/lib/rules/no-const-assign.js +++ b/tools/eslint/lib/rules/no-const-assign.js @@ -30,11 +30,8 @@ module.exports = { * @returns {void} */ function checkVariable(variable) { - astUtils.getModifyingReferences(variable.references).forEach(function(reference) { - context.report( - reference.identifier, - "'{{name}}' is constant.", - {name: reference.identifier.name}); + astUtils.getModifyingReferences(variable.references).forEach(reference => { + context.report({ node: reference.identifier, message: "'{{name}}' is constant.", data: { name: reference.identifier.name } }); }); } diff --git a/tools/eslint/lib/rules/no-constant-condition.js b/tools/eslint/lib/rules/no-constant-condition.js index f78ddbc2e972b0..7178d5dbecc10e 100644 --- a/tools/eslint/lib/rules/no-constant-condition.js +++ b/tools/eslint/lib/rules/no-constant-condition.js @@ -122,7 +122,7 @@ module.exports = { */ function checkConstantCondition(node) { if (node.test && isConstant(node.test, true)) { - context.report(node, "Unexpected constant condition."); + context.report({ node, message: "Unexpected constant condition." }); } } diff --git a/tools/eslint/lib/rules/no-continue.js b/tools/eslint/lib/rules/no-continue.js index b8956da4b75025..2615fba13e2401 100644 --- a/tools/eslint/lib/rules/no-continue.js +++ b/tools/eslint/lib/rules/no-continue.js @@ -24,7 +24,7 @@ module.exports = { return { ContinueStatement(node) { - context.report(node, "Unexpected use of continue statement."); + context.report({ node, message: "Unexpected use of continue statement." }); } }; diff --git a/tools/eslint/lib/rules/no-control-regex.js b/tools/eslint/lib/rules/no-control-regex.js index 466f5666ac181f..1ebf9800009371 100644 --- a/tools/eslint/lib/rules/no-control-regex.js +++ b/tools/eslint/lib/rules/no-control-regex.js @@ -85,7 +85,7 @@ module.exports = { stringControlChars = regexStr.slice(subStrIndex, -1) .split(consecutiveSlashes) .filter(Boolean) - .map(function(x) { + .map(x => { const match = x.match(stringControlCharWithoutSlash) || [x]; return `\\${match[0]}`; @@ -93,7 +93,7 @@ module.exports = { } } - return controlChars.map(function(x) { + return controlChars.map(x => { const hexCode = `0${x.charCodeAt(0).toString(16)}`.slice(-2); return `\\x${hexCode}`; diff --git a/tools/eslint/lib/rules/no-debugger.js b/tools/eslint/lib/rules/no-debugger.js index 6356d5269b61f1..897b3dbb6094f9 100644 --- a/tools/eslint/lib/rules/no-debugger.js +++ b/tools/eslint/lib/rules/no-debugger.js @@ -24,7 +24,7 @@ module.exports = { return { DebuggerStatement(node) { - context.report(node, "Unexpected 'debugger' statement."); + context.report({ node, message: "Unexpected 'debugger' statement." }); } }; diff --git a/tools/eslint/lib/rules/no-delete-var.js b/tools/eslint/lib/rules/no-delete-var.js index dce202dc834c7e..adc1b5bb9c2c01 100644 --- a/tools/eslint/lib/rules/no-delete-var.js +++ b/tools/eslint/lib/rules/no-delete-var.js @@ -26,7 +26,7 @@ module.exports = { UnaryExpression(node) { if (node.operator === "delete" && node.argument.type === "Identifier") { - context.report(node, "Variables should not be deleted."); + context.report({ node, message: "Variables should not be deleted." }); } } }; diff --git a/tools/eslint/lib/rules/no-div-regex.js b/tools/eslint/lib/rules/no-div-regex.js index c5ffa7ce7e2e7a..84a9b9a3aaa9a6 100644 --- a/tools/eslint/lib/rules/no-div-regex.js +++ b/tools/eslint/lib/rules/no-div-regex.js @@ -29,7 +29,7 @@ module.exports = { const token = sourceCode.getFirstToken(node); if (token.type === "RegularExpression" && token.value[1] === "=") { - context.report(node, "A regular expression literal can be confused with '/='."); + context.report({ node, message: "A regular expression literal can be confused with '/='." }); } } }; diff --git a/tools/eslint/lib/rules/no-dupe-args.js b/tools/eslint/lib/rules/no-dupe-args.js index 0d420eb92aaaf9..cdb38035c0a01f 100644 --- a/tools/eslint/lib/rules/no-dupe-args.js +++ b/tools/eslint/lib/rules/no-dupe-args.js @@ -54,7 +54,7 @@ module.exports = { context.report({ node, message: "Duplicate param '{{name}}'.", - data: {name: variable.name} + data: { name: variable.name } }); } } diff --git a/tools/eslint/lib/rules/no-dupe-class-members.js b/tools/eslint/lib/rules/no-dupe-class-members.js index 3b857a67fb9e65..07b999fab19bb9 100644 --- a/tools/eslint/lib/rules/no-dupe-class-members.js +++ b/tools/eslint/lib/rules/no-dupe-class-members.js @@ -38,8 +38,8 @@ module.exports = { if (!stateMap[key]) { stateMap[key] = { - nonStatic: {init: false, get: false, set: false}, - static: {init: false, get: false, set: false} + nonStatic: { init: false, get: false, set: false }, + static: { init: false, get: false, set: false } }; } @@ -101,7 +101,7 @@ module.exports = { } if (isDuplicate) { - context.report(node, "Duplicate name '{{name}}'.", {name}); + context.report({ node, message: "Duplicate name '{{name}}'.", data: { name } }); } } }; diff --git a/tools/eslint/lib/rules/no-dupe-keys.js b/tools/eslint/lib/rules/no-dupe-keys.js index f34c323f1ed491..f056b1fcbeb43e 100644 --- a/tools/eslint/lib/rules/no-dupe-keys.js +++ b/tools/eslint/lib/rules/no-dupe-keys.js @@ -42,7 +42,7 @@ class ObjectInfo { const name = astUtils.getStaticPropertyName(node); if (!this.properties.has(name)) { - this.properties.set(name, {get: false, set: false}); + this.properties.set(name, { get: false, set: false }); } return this.properties.get(name); } @@ -123,7 +123,7 @@ module.exports = { node: info.node, loc: node.key.loc, message: "Duplicate key '{{name}}'.", - data: {name}, + data: { name }, }); } diff --git a/tools/eslint/lib/rules/no-duplicate-case.js b/tools/eslint/lib/rules/no-duplicate-case.js index 5b20fc3d582980..07823f284c1c3d 100644 --- a/tools/eslint/lib/rules/no-duplicate-case.js +++ b/tools/eslint/lib/rules/no-duplicate-case.js @@ -28,11 +28,11 @@ module.exports = { SwitchStatement(node) { const mapping = {}; - node.cases.forEach(function(switchCase) { + node.cases.forEach(switchCase => { const key = sourceCode.getText(switchCase.test); if (mapping[key]) { - context.report(switchCase, "Duplicate case label."); + context.report({ node: switchCase, message: "Duplicate case label." }); } else { mapping[key] = switchCase; } diff --git a/tools/eslint/lib/rules/no-else-return.js b/tools/eslint/lib/rules/no-else-return.js index 07b596238caf2b..43564346b043e2 100644 --- a/tools/eslint/lib/rules/no-else-return.js +++ b/tools/eslint/lib/rules/no-else-return.js @@ -33,7 +33,7 @@ module.exports = { * @returns {void} */ function displayReport(node) { - context.report(node, "Unnecessary 'else' after 'return'."); + context.report({ node, message: "Unnecessary 'else' after 'return'." }); } /** diff --git a/tools/eslint/lib/rules/no-empty-character-class.js b/tools/eslint/lib/rules/no-empty-character-class.js index 723cebc9450f00..f36c6c9f0d8b19 100644 --- a/tools/eslint/lib/rules/no-empty-character-class.js +++ b/tools/eslint/lib/rules/no-empty-character-class.js @@ -21,7 +21,7 @@ plain-English description of the following regexp: 4. `[gimuy]*`: optional regexp flags 5. `$`: fix the match at the end of the string */ -const regex = /^\/([^\\[]|\\.|\[([^\\\]]|\\.)+\])*\/[gimuy]*$/; +const regex = /^\/([^\\[]|\\.|\[([^\\\]]|\\.)+])*\/[gimuy]*$/; //------------------------------------------------------------------------------ // Rule Definition @@ -47,7 +47,7 @@ module.exports = { const token = sourceCode.getFirstToken(node); if (token.type === "RegularExpression" && !regex.test(token.value)) { - context.report(node, "Empty class."); + context.report({ node, message: "Empty class." }); } } diff --git a/tools/eslint/lib/rules/no-empty-function.js b/tools/eslint/lib/rules/no-empty-function.js index 8299f40685ca52..65f9c9e1515342 100644 --- a/tools/eslint/lib/rules/no-empty-function.js +++ b/tools/eslint/lib/rules/no-empty-function.js @@ -108,7 +108,7 @@ module.exports = { properties: { allow: { type: "array", - items: {enum: ALLOW_OPTIONS}, + items: { enum: ALLOW_OPTIONS }, uniqueItems: true } }, diff --git a/tools/eslint/lib/rules/no-empty-pattern.js b/tools/eslint/lib/rules/no-empty-pattern.js index 77302fc8d73f9d..11f50b54142e04 100644 --- a/tools/eslint/lib/rules/no-empty-pattern.js +++ b/tools/eslint/lib/rules/no-empty-pattern.js @@ -23,12 +23,12 @@ module.exports = { return { ObjectPattern(node) { if (node.properties.length === 0) { - context.report(node, "Unexpected empty object pattern."); + context.report({ node, message: "Unexpected empty object pattern." }); } }, ArrayPattern(node) { if (node.elements.length === 0) { - context.report(node, "Unexpected empty array pattern."); + context.report({ node, message: "Unexpected empty array pattern." }); } } }; diff --git a/tools/eslint/lib/rules/no-empty.js b/tools/eslint/lib/rules/no-empty.js index 8514b9cf89d0c8..a9b0776c933b07 100644 --- a/tools/eslint/lib/rules/no-empty.js +++ b/tools/eslint/lib/rules/no-empty.js @@ -63,13 +63,13 @@ module.exports = { return; } - context.report(node, "Empty block statement."); + context.report({ node, message: "Empty block statement." }); }, SwitchStatement(node) { if (typeof node.cases === "undefined" || node.cases.length === 0) { - context.report(node, "Empty switch statement."); + context.report({ node, message: "Empty switch statement." }); } } }; diff --git a/tools/eslint/lib/rules/no-eq-null.js b/tools/eslint/lib/rules/no-eq-null.js index 62215d05f1b0eb..7e915a8c726f9f 100644 --- a/tools/eslint/lib/rules/no-eq-null.js +++ b/tools/eslint/lib/rules/no-eq-null.js @@ -30,7 +30,7 @@ module.exports = { if (node.right.type === "Literal" && node.right.raw === "null" && badOperator || node.left.type === "Literal" && node.left.raw === "null" && badOperator) { - context.report(node, "Use ‘===’ to compare with ‘null’."); + context.report({ node, message: "Use ‘===’ to compare with ‘null’." }); } } }; diff --git a/tools/eslint/lib/rules/no-eval.js b/tools/eslint/lib/rules/no-eval.js index af87e4289fcc31..fe1456cba0a431 100644 --- a/tools/eslint/lib/rules/no-eval.js +++ b/tools/eslint/lib/rules/no-eval.js @@ -86,7 +86,7 @@ module.exports = { { type: "object", properties: { - allowIndirect: {type: "boolean"} + allowIndirect: { type: "boolean" } }, additionalProperties: false } diff --git a/tools/eslint/lib/rules/no-ex-assign.js b/tools/eslint/lib/rules/no-ex-assign.js index 6ffa8408677292..20869d5cd107c9 100644 --- a/tools/eslint/lib/rules/no-ex-assign.js +++ b/tools/eslint/lib/rules/no-ex-assign.js @@ -30,10 +30,8 @@ module.exports = { * @returns {void} */ function checkVariable(variable) { - astUtils.getModifyingReferences(variable.references).forEach(function(reference) { - context.report( - reference.identifier, - "Do not assign to the exception parameter."); + astUtils.getModifyingReferences(variable.references).forEach(reference => { + context.report({ node: reference.identifier, message: "Do not assign to the exception parameter." }); }); } diff --git a/tools/eslint/lib/rules/no-extend-native.js b/tools/eslint/lib/rules/no-extend-native.js index 27de9b5bd36deb..c44a2e894699e9 100644 --- a/tools/eslint/lib/rules/no-extend-native.js +++ b/tools/eslint/lib/rules/no-extend-native.js @@ -44,14 +44,10 @@ module.exports = { const config = context.options[0] || {}; const exceptions = config.exceptions || []; - let modifiedBuiltins = Object.keys(globals.builtin).filter(function(builtin) { - return builtin[0].toUpperCase() === builtin[0]; - }); + let modifiedBuiltins = Object.keys(globals.builtin).filter(builtin => builtin[0].toUpperCase() === builtin[0]); if (exceptions.length) { - modifiedBuiltins = modifiedBuiltins.filter(function(builtIn) { - return exceptions.indexOf(builtIn) === -1; - }); + modifiedBuiltins = modifiedBuiltins.filter(builtIn => exceptions.indexOf(builtIn) === -1); } return { @@ -72,7 +68,7 @@ module.exports = { return; } - modifiedBuiltins.forEach(function(builtin) { + modifiedBuiltins.forEach(builtin => { if (lhs.object.object.name === builtin) { context.report({ node, diff --git a/tools/eslint/lib/rules/no-extra-boolean-cast.js b/tools/eslint/lib/rules/no-extra-boolean-cast.js index 89a193b2d12435..123a7cacc5256a 100644 --- a/tools/eslint/lib/rules/no-extra-boolean-cast.js +++ b/tools/eslint/lib/rules/no-extra-boolean-cast.js @@ -17,10 +17,13 @@ module.exports = { recommended: true }, - schema: [] + schema: [], + + fixable: "code" }, create(context) { + const sourceCode = context.getSourceCode(); // Node types which have a test which will coerce values to booleans. const BOOLEAN_NODE_TYPES = [ @@ -70,7 +73,11 @@ module.exports = { grandparent.callee.type === "Identifier" && grandparent.callee.name === "Boolean") ) { - context.report(node, "Redundant double negation."); + context.report({ + node, + message: "Redundant double negation.", + fix: fixer => fixer.replaceText(parent, sourceCode.getText(node.argument)) + }); } }, CallExpression(node) { @@ -81,7 +88,11 @@ module.exports = { } if (isInBooleanContext(node, parent)) { - context.report(node, "Redundant Boolean call."); + context.report({ + node, + message: "Redundant Boolean call.", + fix: fixer => fixer.replaceText(node, sourceCode.getText(node.arguments[0])) + }); } } }; diff --git a/tools/eslint/lib/rules/no-extra-label.js b/tools/eslint/lib/rules/no-extra-label.js index b34e075163472d..22afbf405b7ea9 100644 --- a/tools/eslint/lib/rules/no-extra-label.js +++ b/tools/eslint/lib/rules/no-extra-label.js @@ -23,10 +23,13 @@ module.exports = { recommended: false }, - schema: [] + schema: [], + + fixable: "code" }, create(context) { + const sourceCode = context.getSourceCode(); let scopeInfo = null; /** @@ -37,7 +40,7 @@ module.exports = { */ function enterBreakableStatement(node) { scopeInfo = { - label: astUtils.getLabel(node), + label: node.parent.type === "LabeledStatement" ? node.parent.label : null, breakable: true, upper: scopeInfo }; @@ -64,7 +67,7 @@ module.exports = { function enterLabeledStatement(node) { if (!astUtils.isBreakableStatement(node.body)) { scopeInfo = { - label: node.label.name, + label: node.label, breakable: false, upper: scopeInfo }; @@ -99,22 +102,24 @@ module.exports = { } const labelNode = node.label; - const label = labelNode.name; - let info = scopeInfo; - while (info) { - if (info.breakable || info.label === label) { - if (info.breakable && info.label === label) { + for (let info = scopeInfo; info !== null; info = info.upper) { + if (info.breakable || info.label && info.label.name === labelNode.name) { + if (info.breakable && info.label && info.label.name === labelNode.name) { context.report({ node: labelNode, message: "This label '{{name}}' is unnecessary.", - data: labelNode + data: labelNode, + fix(fixer) { + return fixer.replaceTextRange( + [info.label.range[0], labelNode.range[1]], + sourceCode.text.slice(info.label.parent.body.range[0], sourceCode.getFirstToken(node).range[1]) + ); + } }); } return; } - - info = info.upper; } } diff --git a/tools/eslint/lib/rules/no-extra-parens.js b/tools/eslint/lib/rules/no-extra-parens.js index efa3d53bbd3328..004d431701a574 100644 --- a/tools/eslint/lib/rules/no-extra-parens.js +++ b/tools/eslint/lib/rules/no-extra-parens.js @@ -42,9 +42,9 @@ module.exports = { { type: "object", properties: { - conditionalAssign: {type: "boolean"}, - nestedBinaryExpressions: {type: "boolean"}, - returnAssign: {type: "boolean"} + conditionalAssign: { type: "boolean" }, + nestedBinaryExpressions: { type: "boolean" }, + returnAssign: { type: "boolean" } }, additionalProperties: false } @@ -348,12 +348,12 @@ module.exports = { report(node.callee); } if (node.arguments.length === 1) { - if (hasDoubleExcessParens(node.arguments[0]) && precedence(node.arguments[0]) >= precedence({type: "AssignmentExpression"})) { + if (hasDoubleExcessParens(node.arguments[0]) && precedence(node.arguments[0]) >= precedence({ type: "AssignmentExpression" })) { report(node.arguments[0]); } } else { - [].forEach.call(node.arguments, function(arg) { - if (hasExcessParens(arg) && precedence(arg) >= precedence({type: "AssignmentExpression"})) { + [].forEach.call(node.arguments, arg => { + if (hasExcessParens(arg) && precedence(arg) >= precedence({ type: "AssignmentExpression" })) { report(arg); } }); @@ -381,8 +381,8 @@ module.exports = { return { ArrayExpression(node) { - [].forEach.call(node.elements, function(e) { - if (e && hasExcessParens(e) && precedence(e) >= precedence({type: "AssignmentExpression"})) { + [].forEach.call(node.elements, e => { + if (e && hasExcessParens(e) && precedence(e) >= precedence({ type: "AssignmentExpression" })) { report(e); } }); @@ -394,7 +394,7 @@ module.exports = { } if (node.body.type !== "BlockStatement") { - if (sourceCode.getFirstToken(node.body).value !== "{" && hasExcessParens(node.body) && precedence(node.body) >= precedence({type: "AssignmentExpression"})) { + if (sourceCode.getFirstToken(node.body).value !== "{" && hasExcessParens(node.body) && precedence(node.body) >= precedence({ type: "AssignmentExpression" })) { report(node.body); return; } @@ -402,7 +402,6 @@ module.exports = { // Object literals *must* be parenthesised if (node.body.type === "ObjectExpression" && hasDoubleExcessParens(node.body)) { report(node.body); - return; } } }, @@ -425,15 +424,15 @@ module.exports = { return; } - if (hasExcessParens(node.test) && precedence(node.test) >= precedence({type: "LogicalExpression", operator: "||"})) { + if (hasExcessParens(node.test) && precedence(node.test) >= precedence({ type: "LogicalExpression", operator: "||" })) { report(node.test); } - if (hasExcessParens(node.consequent) && precedence(node.consequent) >= precedence({type: "AssignmentExpression"})) { + if (hasExcessParens(node.consequent) && precedence(node.consequent) >= precedence({ type: "AssignmentExpression" })) { report(node.consequent); } - if (hasExcessParens(node.alternate) && precedence(node.alternate) >= precedence({type: "AssignmentExpression"})) { + if (hasExcessParens(node.alternate) && precedence(node.alternate) >= precedence({ type: "AssignmentExpression" })) { report(node.alternate); } }, @@ -509,7 +508,7 @@ module.exports = { !( (node.object.type === "Literal" && typeof node.object.value === "number" && - /^[0-9]+$/.test(sourceCode.getFirstToken(node.object).value)) + astUtils.isDecimalInteger(node.object)) || // RegExp literal is allowed to have parens (#1589) @@ -532,10 +531,10 @@ module.exports = { NewExpression: dryCallNew, ObjectExpression(node) { - [].forEach.call(node.properties, function(e) { + [].forEach.call(node.properties, e => { const v = e.value; - if (v && hasExcessParens(v) && precedence(v) >= precedence({type: "AssignmentExpression"})) { + if (v && hasExcessParens(v) && precedence(v) >= precedence({ type: "AssignmentExpression" })) { report(v); } }); @@ -558,7 +557,7 @@ module.exports = { }, SequenceExpression(node) { - [].forEach.call(node.expressions, function(e) { + [].forEach.call(node.expressions, e => { if (hasExcessParens(e) && precedence(e) >= precedence(node)) { report(e); } @@ -591,7 +590,7 @@ module.exports = { VariableDeclarator(node) { if (node.init && hasExcessParens(node.init) && - precedence(node.init) >= precedence({type: "AssignmentExpression"}) && + precedence(node.init) >= precedence({ type: "AssignmentExpression" }) && // RegExp literal is allowed to have parens (#1589) !(node.init.type === "Literal" && node.init.regex)) { diff --git a/tools/eslint/lib/rules/no-fallthrough.js b/tools/eslint/lib/rules/no-fallthrough.js index 380a53634be1cb..30d13da06ddc8f 100644 --- a/tools/eslint/lib/rules/no-fallthrough.js +++ b/tools/eslint/lib/rules/no-fallthrough.js @@ -109,7 +109,7 @@ module.exports = { if (fallthroughCase && !hasFallthroughComment(node, context, fallthroughCommentPattern)) { context.report({ message: "Expected a 'break' statement before '{{type}}'.", - data: {type: node.test ? "case" : "default"}, + data: { type: node.test ? "case" : "default" }, node }); } diff --git a/tools/eslint/lib/rules/no-func-assign.js b/tools/eslint/lib/rules/no-func-assign.js index daa6fa52ba7301..ea86365b2914eb 100644 --- a/tools/eslint/lib/rules/no-func-assign.js +++ b/tools/eslint/lib/rules/no-func-assign.js @@ -30,11 +30,8 @@ module.exports = { * @returns {void} */ function checkReference(references) { - astUtils.getModifyingReferences(references).forEach(function(reference) { - context.report( - reference.identifier, - "'{{name}}' is a function.", - {name: reference.identifier.name}); + astUtils.getModifyingReferences(references).forEach(reference => { + context.report({ node: reference.identifier, message: "'{{name}}' is a function.", data: { name: reference.identifier.name } }); }); } diff --git a/tools/eslint/lib/rules/no-global-assign.js b/tools/eslint/lib/rules/no-global-assign.js index 2bc38cb5d70bb6..caf2500231e14a 100644 --- a/tools/eslint/lib/rules/no-global-assign.js +++ b/tools/eslint/lib/rules/no-global-assign.js @@ -23,7 +23,7 @@ module.exports = { properties: { exceptions: { type: "array", - items: {type: "string"}, + items: { type: "string" }, uniqueItems: true } }, diff --git a/tools/eslint/lib/rules/no-implicit-globals.js b/tools/eslint/lib/rules/no-implicit-globals.js index fd49f0c5ac3011..f0962cdc7a864a 100644 --- a/tools/eslint/lib/rules/no-implicit-globals.js +++ b/tools/eslint/lib/rules/no-implicit-globals.js @@ -25,27 +25,27 @@ module.exports = { Program() { const scope = context.getScope(); - scope.variables.forEach(function(variable) { + scope.variables.forEach(variable => { if (variable.writeable) { return; } - variable.defs.forEach(function(def) { + variable.defs.forEach(def => { if (def.type === "FunctionName" || (def.type === "Variable" && def.parent.kind === "var")) { - context.report(def.node, "Implicit global variable, assign as global property instead."); + context.report({ node: def.node, message: "Implicit global variable, assign as global property instead." }); } }); }); - scope.implicit.variables.forEach(function(variable) { + scope.implicit.variables.forEach(variable => { const scopeVariable = scope.set.get(variable.name); if (scopeVariable && scopeVariable.writeable) { return; } - variable.defs.forEach(function(def) { - context.report(def.node, "Implicit global variable, assign as global property instead."); + variable.defs.forEach(def => { + context.report({ node: def.node, message: "Implicit global variable, assign as global property instead." }); }); }); } diff --git a/tools/eslint/lib/rules/no-implied-eval.js b/tools/eslint/lib/rules/no-implied-eval.js index 9b48e896821363..4daadd8fb8733d 100644 --- a/tools/eslint/lib/rules/no-implied-eval.js +++ b/tools/eslint/lib/rules/no-implied-eval.js @@ -21,7 +21,7 @@ module.exports = { }, create(context) { - const CALLEE_RE = /set(?:Timeout|Interval)|execScript/; + const CALLEE_RE = /^(setTimeout|setInterval|execScript)$/; /* * Figures out if we should inspect a given binary expression. Is a stack @@ -105,7 +105,7 @@ module.exports = { // remove the entire substack, to avoid duplicate reports const substack = impliedEvalAncestorsStack.pop(); - context.report(substack[0], "Implied eval. Consider passing a function instead of a string."); + context.report({ node: substack[0], message: "Implied eval. Consider passing a function instead of a string." }); } } diff --git a/tools/eslint/lib/rules/no-inline-comments.js b/tools/eslint/lib/rules/no-inline-comments.js index d51a59a183c199..46815d15418f6a 100644 --- a/tools/eslint/lib/rules/no-inline-comments.js +++ b/tools/eslint/lib/rules/no-inline-comments.js @@ -46,7 +46,7 @@ module.exports = { // Should be empty if there was only whitespace around the comment if (!isDirective && (preamble || postamble)) { - context.report(node, "Unexpected comment inline with code."); + context.report({ node, message: "Unexpected comment inline with code." }); } } diff --git a/tools/eslint/lib/rules/no-inner-declarations.js b/tools/eslint/lib/rules/no-inner-declarations.js index e5a186133cc34e..01cc67863ffff5 100644 --- a/tools/eslint/lib/rules/no-inner-declarations.js +++ b/tools/eslint/lib/rules/no-inner-declarations.js @@ -36,8 +36,8 @@ module.exports = { generation = 1; while (ancestor && ["Program", "FunctionDeclaration", - "FunctionExpression", "ArrowFunctionExpression" - ].indexOf(ancestor.type) < 0) { + "FunctionExpression", "ArrowFunctionExpression" + ].indexOf(ancestor.type) < 0) { generation += 1; ancestor = ancestors.pop(); } @@ -63,14 +63,12 @@ module.exports = { body.distance === 2); if (!valid) { - context.report(node, "Move {{type}} declaration to {{body}} root.", - { - type: (node.type === "FunctionDeclaration" ? + context.report({ node, message: "Move {{type}} declaration to {{body}} root.", data: { + type: (node.type === "FunctionDeclaration" ? "function" : "variable"), - body: (body.type === "Program" ? + body: (body.type === "Program" ? "program" : "function body") - } - ); + } }); } } diff --git a/tools/eslint/lib/rules/no-invalid-this.js b/tools/eslint/lib/rules/no-invalid-this.js index fe2bc3a1baa647..64ef4882e252ec 100644 --- a/tools/eslint/lib/rules/no-invalid-this.js +++ b/tools/eslint/lib/rules/no-invalid-this.js @@ -114,7 +114,7 @@ module.exports = { const current = stack.getCurrent(); if (current && !current.valid) { - context.report(node, "Unexpected 'this'."); + context.report({ node, message: "Unexpected 'this'." }); } } }; diff --git a/tools/eslint/lib/rules/no-irregular-whitespace.js b/tools/eslint/lib/rules/no-irregular-whitespace.js index 74a3c10fed1c9d..b1949fbc735479 100644 --- a/tools/eslint/lib/rules/no-irregular-whitespace.js +++ b/tools/eslint/lib/rules/no-irregular-whitespace.js @@ -76,7 +76,7 @@ module.exports = { const locStart = node.loc.start; const locEnd = node.loc.end; - errors = errors.filter(function(error) { + errors = errors.filter(error => { const errorLoc = error[1]; if (errorLoc.line >= locStart.line && errorLoc.line <= locEnd.line) { @@ -142,7 +142,7 @@ module.exports = { function checkForIrregularWhitespace(node) { const sourceLines = sourceCode.lines; - sourceLines.forEach(function(sourceLine, lineIndex) { + sourceLines.forEach((sourceLine, lineIndex) => { const lineNumber = lineIndex + 1; let match; @@ -233,7 +233,7 @@ module.exports = { } // If we have any errors remaining report on them - errors.forEach(function(error) { + errors.forEach(error => { context.report.apply(context, error); }); }; diff --git a/tools/eslint/lib/rules/no-iterator.js b/tools/eslint/lib/rules/no-iterator.js index faa5153335bd76..3677dd94d9f938 100644 --- a/tools/eslint/lib/rules/no-iterator.js +++ b/tools/eslint/lib/rules/no-iterator.js @@ -29,7 +29,7 @@ module.exports = { if (node.property && (node.property.type === "Identifier" && node.property.name === "__iterator__" && !node.computed) || (node.property.type === "Literal" && node.property.value === "__iterator__")) { - context.report(node, "Reserved name '__iterator__'."); + context.report({ node, message: "Reserved name '__iterator__'." }); } } }; diff --git a/tools/eslint/lib/rules/no-label-var.js b/tools/eslint/lib/rules/no-label-var.js index 450c9a91fca893..00133685613609 100644 --- a/tools/eslint/lib/rules/no-label-var.js +++ b/tools/eslint/lib/rules/no-label-var.js @@ -57,7 +57,7 @@ module.exports = { // Recursively find the identifier walking up the scope, starting // with the innermost scope. if (findIdentifier(scope, node.label.name)) { - context.report(node, "Found identifier with same name as label."); + context.report({ node, message: "Found identifier with same name as label." }); } } diff --git a/tools/eslint/lib/rules/no-lone-blocks.js b/tools/eslint/lib/rules/no-lone-blocks.js index 9945147129cd81..9528421ca5bd39 100644 --- a/tools/eslint/lib/rules/no-lone-blocks.js +++ b/tools/eslint/lib/rules/no-lone-blocks.js @@ -34,10 +34,10 @@ module.exports = { function report(node) { const parent = context.getAncestors().pop(); - context.report(node, parent.type === "Program" ? + context.report({ node, message: parent.type === "Program" ? "Block is redundant." : "Nested block is redundant." - ); + }); } /** diff --git a/tools/eslint/lib/rules/no-lonely-if.js b/tools/eslint/lib/rules/no-lonely-if.js index 19517bc3dc491a..31f47b90e06595 100644 --- a/tools/eslint/lib/rules/no-lonely-if.js +++ b/tools/eslint/lib/rules/no-lonely-if.js @@ -55,7 +55,7 @@ module.exports = { node.consequent.type !== "BlockStatement" && lastIfToken.value !== ";" && tokenAfterElseBlock && ( node.consequent.loc.end.line === tokenAfterElseBlock.loc.start.line || - /^[(\[\/+`-]/.test(tokenAfterElseBlock.value) || + /^[([/+`-]/.test(tokenAfterElseBlock.value) || lastIfToken.value === "++" || lastIfToken.value === "--" ) diff --git a/tools/eslint/lib/rules/no-loop-func.js b/tools/eslint/lib/rules/no-loop-func.js index 6db7a95f7c7254..b8bed958652e46 100644 --- a/tools/eslint/lib/rules/no-loop-func.js +++ b/tools/eslint/lib/rules/no-loop-func.js @@ -185,7 +185,7 @@ module.exports = { if (references.length > 0 && !references.every(isSafe.bind(null, node, loopNode)) ) { - context.report(node, "Don't make functions within a loop."); + context.report({ node, message: "Don't make functions within a loop." }); } } diff --git a/tools/eslint/lib/rules/no-mixed-operators.js b/tools/eslint/lib/rules/no-mixed-operators.js index 12779f8e738c68..b066d74a0c40e0 100644 --- a/tools/eslint/lib/rules/no-mixed-operators.js +++ b/tools/eslint/lib/rules/no-mixed-operators.js @@ -62,9 +62,7 @@ function normalizeOptions(options) { * @returns {boolean} `true` if such group existed. */ function includesBothInAGroup(groups, left, right) { - return groups.some(function(group) { - return group.indexOf(left) !== -1 && group.indexOf(right) !== -1; - }); + return groups.some(group => group.indexOf(left) !== -1 && group.indexOf(right) !== -1); } //------------------------------------------------------------------------------ @@ -86,7 +84,7 @@ module.exports = { type: "array", items: { type: "array", - items: {enum: ALL_OPERATORS}, + items: { enum: ALL_OPERATORS }, minItems: 2, uniqueItems: true }, diff --git a/tools/eslint/lib/rules/no-mixed-requires.js b/tools/eslint/lib/rules/no-mixed-requires.js index 89ba345c248f61..4d51d3ab3a07a4 100644 --- a/tools/eslint/lib/rules/no-mixed-requires.js +++ b/tools/eslint/lib/rules/no-mixed-requires.js @@ -169,7 +169,7 @@ module.exports = { function isMixed(declarations) { const contains = {}; - declarations.forEach(function(declaration) { + declarations.forEach(declaration => { const type = getDeclarationType(declaration.init); contains[type] = true; @@ -190,7 +190,7 @@ module.exports = { function isGrouped(declarations) { const found = {}; - declarations.forEach(function(declaration) { + declarations.forEach(declaration => { if (getDeclarationType(declaration.init) === DECL_REQUIRE) { found[inferModuleType(declaration.init)] = true; } @@ -205,15 +205,9 @@ module.exports = { VariableDeclaration(node) { if (isMixed(node.declarations)) { - context.report( - node, - "Do not mix 'require' and other declarations." - ); + context.report({ node, message: "Do not mix 'require' and other declarations." }); } else if (grouping && !isGrouped(node.declarations)) { - context.report( - node, - "Do not mix core, module, file and computed requires." - ); + context.report({ node, message: "Do not mix core, module, file and computed requires." }); } } }; diff --git a/tools/eslint/lib/rules/no-mixed-spaces-and-tabs.js b/tools/eslint/lib/rules/no-mixed-spaces-and-tabs.js index 0e2dcb1b8a8672..2b8e89d3c87123 100644 --- a/tools/eslint/lib/rules/no-mixed-spaces-and-tabs.js +++ b/tools/eslint/lib/rules/no-mixed-spaces-and-tabs.js @@ -89,11 +89,11 @@ module.exports = { const lines = sourceCode.lines, comments = sourceCode.getAllComments(); - comments.forEach(function(comment) { + comments.forEach(comment => { ignoredLocs.push(comment.loc); }); - ignoredLocs.sort(function(first, second) { + ignoredLocs.sort((first, second) => { if (beforeLoc(first, second.start.line, second.start.column)) { return 1; } @@ -114,7 +114,7 @@ module.exports = { regex = /^(?=[\t ]* \t)/; } - lines.forEach(function(line, i) { + lines.forEach((line, i) => { const match = regex.exec(line); if (match) { @@ -132,7 +132,7 @@ module.exports = { return; } - context.report(node, { line: lineNumber, column }, "Mixed spaces and tabs."); + context.report({ node, loc: { line: lineNumber, column }, message: "Mixed spaces and tabs." }); } }); } diff --git a/tools/eslint/lib/rules/no-multi-spaces.js b/tools/eslint/lib/rules/no-multi-spaces.js index 43e26a4415353e..64eeebec55a383 100644 --- a/tools/eslint/lib/rules/no-multi-spaces.js +++ b/tools/eslint/lib/rules/no-multi-spaces.js @@ -47,7 +47,7 @@ module.exports = { lastCommentIndex = 0; if (options && options.exceptions) { - Object.keys(options.exceptions).forEach(function(key) { + Object.keys(options.exceptions).forEach(key => { if (options.exceptions[key]) { exceptions[key] = true; } else { diff --git a/tools/eslint/lib/rules/no-multi-str.js b/tools/eslint/lib/rules/no-multi-str.js index 092226f7cad355..6cf5840e30264b 100644 --- a/tools/eslint/lib/rules/no-multi-str.js +++ b/tools/eslint/lib/rules/no-multi-str.js @@ -42,7 +42,7 @@ module.exports = { const lineBreak = /\n/; if (lineBreak.test(node.raw) && !isJSXElement(node.parent)) { - context.report(node, "Multiline support is limited to browsers supporting ES5 only."); + context.report({ node, message: "Multiline support is limited to browsers supporting ES5 only." }); } } }; diff --git a/tools/eslint/lib/rules/no-multiple-empty-lines.js b/tools/eslint/lib/rules/no-multiple-empty-lines.js index 9d44064d23f1d3..c45c7aa1678927 100644 --- a/tools/eslint/lib/rules/no-multiple-empty-lines.js +++ b/tools/eslint/lib/rules/no-multiple-empty-lines.js @@ -5,6 +5,8 @@ */ "use strict"; +const astUtils = require("../ast-utils"); + //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ @@ -56,8 +58,6 @@ module.exports = { } const sourceCode = context.getSourceCode(); - const fullLines = sourceCode.text.match(/.*(\r\n|\r|\n|\u2028|\u2029)/g) || []; - const lineStartLocations = fullLines.reduce((startIndices, nextLine) => startIndices.concat(startIndices[startIndices.length - 1] + nextLine.length), [0]); // Swallow the final newline, as some editors add it automatically and we don't want it to cause an issue const allLines = sourceCode.lines[sourceCode.lines.length - 1] === "" ? sourceCode.lines.slice(0, -1) : sourceCode.lines; @@ -81,7 +81,12 @@ module.exports = { return allLines // Given a list of lines, first get a list of line numbers that are non-empty. - .reduce((nonEmptyLineNumbers, line, index) => nonEmptyLineNumbers.concat(line.trim() || templateLiteralLines.has(index + 1) ? [index + 1] : []), []) + .reduce((nonEmptyLineNumbers, line, index) => { + if (line.trim() || templateLiteralLines.has(index + 1)) { + nonEmptyLineNumbers.push(index + 1); + } + return nonEmptyLineNumbers; + }, []) // Add a value at the end to allow trailing empty lines to be checked. .concat(allLines.length + 1) @@ -104,10 +109,15 @@ module.exports = { if (lineNumber - lastLineNumber - 1 > maxAllowed) { context.report({ node, - loc: {start: {line: lastLineNumber + 1, column: 0}, end: {line: lineNumber, column: 0}}, + loc: { start: { line: lastLineNumber + 1, column: 0 }, end: { line: lineNumber, column: 0 } }, message, - data: {max: maxAllowed, pluralizedLines: maxAllowed === 1 ? "line" : "lines"}, - fix: fixer => fixer.removeRange([lineStartLocations[lastLineNumber], lineStartLocations[lineNumber - maxAllowed - 1]]) + data: { max: maxAllowed, pluralizedLines: maxAllowed === 1 ? "line" : "lines" }, + fix(fixer) { + return fixer.removeRange([ + astUtils.getRangeIndexFromLocation(sourceCode, { line: lastLineNumber + 1, column: 0 }), + astUtils.getRangeIndexFromLocation(sourceCode, { line: lineNumber - maxAllowed, column: 0 }) + ]); + } }); } diff --git a/tools/eslint/lib/rules/no-native-reassign.js b/tools/eslint/lib/rules/no-native-reassign.js index 2b1c41b2d100b0..f721fc278fe3ec 100644 --- a/tools/eslint/lib/rules/no-native-reassign.js +++ b/tools/eslint/lib/rules/no-native-reassign.js @@ -27,7 +27,7 @@ module.exports = { properties: { exceptions: { type: "array", - items: {type: "string"}, + items: { type: "string" }, uniqueItems: true } }, diff --git a/tools/eslint/lib/rules/no-negated-condition.js b/tools/eslint/lib/rules/no-negated-condition.js index ea8b1210774f16..8ea8559ea1c96f 100644 --- a/tools/eslint/lib/rules/no-negated-condition.js +++ b/tools/eslint/lib/rules/no-negated-condition.js @@ -69,12 +69,12 @@ module.exports = { } if (isNegatedIf(node)) { - context.report(node, "Unexpected negated condition."); + context.report({ node, message: "Unexpected negated condition." }); } }, ConditionalExpression(node) { if (isNegatedIf(node)) { - context.report(node, "Unexpected negated condition."); + context.report({ node, message: "Unexpected negated condition." }); } } }; diff --git a/tools/eslint/lib/rules/no-negated-in-lhs.js b/tools/eslint/lib/rules/no-negated-in-lhs.js index 6631336ea74d9f..143518060b33bd 100644 --- a/tools/eslint/lib/rules/no-negated-in-lhs.js +++ b/tools/eslint/lib/rules/no-negated-in-lhs.js @@ -29,7 +29,7 @@ module.exports = { BinaryExpression(node) { if (node.operator === "in" && node.left.type === "UnaryExpression" && node.left.operator === "!") { - context.report(node, "The 'in' expression's left operand is negated."); + context.report({ node, message: "The 'in' expression's left operand is negated." }); } } }; diff --git a/tools/eslint/lib/rules/no-nested-ternary.js b/tools/eslint/lib/rules/no-nested-ternary.js index 50265913b02ecf..4fe49fc9c01e58 100644 --- a/tools/eslint/lib/rules/no-nested-ternary.js +++ b/tools/eslint/lib/rules/no-nested-ternary.js @@ -26,7 +26,7 @@ module.exports = { ConditionalExpression(node) { if (node.alternate.type === "ConditionalExpression" || node.consequent.type === "ConditionalExpression") { - context.report(node, "Do not nest ternary expressions."); + context.report({ node, message: "Do not nest ternary expressions." }); } } }; diff --git a/tools/eslint/lib/rules/no-new-func.js b/tools/eslint/lib/rules/no-new-func.js index e78bcc0772a024..17ca7c9f03d6b3 100644 --- a/tools/eslint/lib/rules/no-new-func.js +++ b/tools/eslint/lib/rules/no-new-func.js @@ -34,7 +34,7 @@ module.exports = { */ function validateCallee(node) { if (node.callee.name === "Function") { - context.report(node, "The Function constructor is eval."); + context.report({ node, message: "The Function constructor is eval." }); } } diff --git a/tools/eslint/lib/rules/no-new-object.js b/tools/eslint/lib/rules/no-new-object.js index d11a2ebc615350..d4d77b55147a62 100644 --- a/tools/eslint/lib/rules/no-new-object.js +++ b/tools/eslint/lib/rules/no-new-object.js @@ -26,7 +26,7 @@ module.exports = { NewExpression(node) { if (node.callee.name === "Object") { - context.report(node, "The object literal notation {} is preferrable."); + context.report({ node, message: "The object literal notation {} is preferrable." }); } } }; diff --git a/tools/eslint/lib/rules/no-new-require.js b/tools/eslint/lib/rules/no-new-require.js index eed2028de351fa..f9ea1f84bf3bb3 100644 --- a/tools/eslint/lib/rules/no-new-require.js +++ b/tools/eslint/lib/rules/no-new-require.js @@ -26,7 +26,7 @@ module.exports = { NewExpression(node) { if (node.callee.type === "Identifier" && node.callee.name === "require") { - context.report(node, "Unexpected use of new with require."); + context.report({ node, message: "Unexpected use of new with require." }); } } }; diff --git a/tools/eslint/lib/rules/no-new-symbol.js b/tools/eslint/lib/rules/no-new-symbol.js index c65e7c9df90afb..5743a4748a9275 100644 --- a/tools/eslint/lib/rules/no-new-symbol.js +++ b/tools/eslint/lib/rules/no-new-symbol.js @@ -28,11 +28,11 @@ module.exports = { const variable = globalScope.set.get("Symbol"); if (variable && variable.defs.length === 0) { - variable.references.forEach(function(ref) { + variable.references.forEach(ref => { const node = ref.identifier; if (node.parent && node.parent.type === "NewExpression") { - context.report(node, "`Symbol` cannot be called as a constructor."); + context.report({ node, message: "`Symbol` cannot be called as a constructor." }); } }); } diff --git a/tools/eslint/lib/rules/no-new-wrappers.js b/tools/eslint/lib/rules/no-new-wrappers.js index 67e69ee0fefe0a..65bf79b87c50b3 100644 --- a/tools/eslint/lib/rules/no-new-wrappers.js +++ b/tools/eslint/lib/rules/no-new-wrappers.js @@ -28,7 +28,7 @@ module.exports = { const wrapperObjects = ["String", "Number", "Boolean", "Math", "JSON"]; if (wrapperObjects.indexOf(node.callee.name) > -1) { - context.report(node, "Do not use {{fn}} as a constructor.", { fn: node.callee.name }); + context.report({ node, message: "Do not use {{fn}} as a constructor.", data: { fn: node.callee.name } }); } } }; diff --git a/tools/eslint/lib/rules/no-new.js b/tools/eslint/lib/rules/no-new.js index 639ae22685a96b..e0f45de1bd298b 100644 --- a/tools/eslint/lib/rules/no-new.js +++ b/tools/eslint/lib/rules/no-new.js @@ -28,7 +28,7 @@ module.exports = { ExpressionStatement(node) { if (node.expression.type === "NewExpression") { - context.report(node, "Do not use 'new' for side effects."); + context.report({ node, message: "Do not use 'new' for side effects." }); } } }; diff --git a/tools/eslint/lib/rules/no-obj-calls.js b/tools/eslint/lib/rules/no-obj-calls.js index bd9b6ee4f04f76..0ca8a5effb6e86 100644 --- a/tools/eslint/lib/rules/no-obj-calls.js +++ b/tools/eslint/lib/rules/no-obj-calls.js @@ -28,8 +28,8 @@ module.exports = { if (node.callee.type === "Identifier") { const name = node.callee.name; - if (name === "Math" || name === "JSON") { - context.report(node, "'{{name}}' is not a function.", { name }); + if (name === "Math" || name === "JSON" || name === "Reflect") { + context.report({ node, message: "'{{name}}' is not a function.", data: { name } }); } } } diff --git a/tools/eslint/lib/rules/no-octal-escape.js b/tools/eslint/lib/rules/no-octal-escape.js index 25a5b022e92402..04bfb6aae3357c 100644 --- a/tools/eslint/lib/rules/no-octal-escape.js +++ b/tools/eslint/lib/rules/no-octal-escape.js @@ -36,8 +36,7 @@ module.exports = { // \0 is actually not considered an octal if (match[2] !== "0" || typeof match[3] !== "undefined") { - context.report(node, "Don't use octal: '\\{{octalDigit}}'. Use '\\u....' instead.", - { octalDigit }); + context.report({ node, message: "Don't use octal: '\\{{octalDigit}}'. Use '\\u....' instead.", data: { octalDigit } }); } } } diff --git a/tools/eslint/lib/rules/no-octal.js b/tools/eslint/lib/rules/no-octal.js index ebc5e3252d9771..58082d0d1cfb04 100644 --- a/tools/eslint/lib/rules/no-octal.js +++ b/tools/eslint/lib/rules/no-octal.js @@ -26,7 +26,7 @@ module.exports = { Literal(node) { if (typeof node.value === "number" && /^0[0-7]/.test(node.raw)) { - context.report(node, "Octal literals should not be used."); + context.report({ node, message: "Octal literals should not be used." }); } } }; diff --git a/tools/eslint/lib/rules/no-param-reassign.js b/tools/eslint/lib/rules/no-param-reassign.js index c20f340d7ab43a..31f5be3cb25972 100644 --- a/tools/eslint/lib/rules/no-param-reassign.js +++ b/tools/eslint/lib/rules/no-param-reassign.js @@ -22,7 +22,7 @@ module.exports = { { type: "object", properties: { - props: {type: "boolean"} + props: { type: "boolean" } }, additionalProperties: false } @@ -102,15 +102,9 @@ module.exports = { (index === 0 || references[index - 1].identifier !== identifier) ) { if (reference.isWrite()) { - context.report( - identifier, - "Assignment to function parameter '{{name}}'.", - {name: identifier.name}); + context.report({ node: identifier, message: "Assignment to function parameter '{{name}}'.", data: { name: identifier.name } }); } else if (props && isModifyingProp(reference)) { - context.report( - identifier, - "Assignment to property of function parameter '{{name}}'.", - {name: identifier.name}); + context.report({ node: identifier, message: "Assignment to property of function parameter '{{name}}'.", data: { name: identifier.name } }); } } } diff --git a/tools/eslint/lib/rules/no-path-concat.js b/tools/eslint/lib/rules/no-path-concat.js index 6b27678aedc8f8..1e153a43b6c683 100644 --- a/tools/eslint/lib/rules/no-path-concat.js +++ b/tools/eslint/lib/rules/no-path-concat.js @@ -39,7 +39,7 @@ module.exports = { (right.type === "Identifier" && MATCHER.test(right.name))) ) { - context.report(node, "Use path.join() or path.resolve() instead of + to create paths."); + context.report({ node, message: "Use path.join() or path.resolve() instead of + to create paths." }); } } diff --git a/tools/eslint/lib/rules/no-process-env.js b/tools/eslint/lib/rules/no-process-env.js index a2ae1fd408ac44..ef58b38e3cccd4 100644 --- a/tools/eslint/lib/rules/no-process-env.js +++ b/tools/eslint/lib/rules/no-process-env.js @@ -28,7 +28,7 @@ module.exports = { propertyName = node.property.name; if (objectName === "process" && !node.computed && propertyName && propertyName === "env") { - context.report(node, "Unexpected use of process.env."); + context.report({ node, message: "Unexpected use of process.env." }); } } diff --git a/tools/eslint/lib/rules/no-process-exit.js b/tools/eslint/lib/rules/no-process-exit.js index 69023e58e1b109..c0c2455545afab 100644 --- a/tools/eslint/lib/rules/no-process-exit.js +++ b/tools/eslint/lib/rules/no-process-exit.js @@ -33,7 +33,7 @@ module.exports = { if (callee.type === "MemberExpression" && callee.object.name === "process" && callee.property.name === "exit" ) { - context.report(node, "Don't use process.exit(); throw an error instead."); + context.report({ node, message: "Don't use process.exit(); throw an error instead." }); } } diff --git a/tools/eslint/lib/rules/no-proto.js b/tools/eslint/lib/rules/no-proto.js index 03eb88273c4bc2..933746f559cd4b 100644 --- a/tools/eslint/lib/rules/no-proto.js +++ b/tools/eslint/lib/rules/no-proto.js @@ -29,7 +29,7 @@ module.exports = { if (node.property && (node.property.type === "Identifier" && node.property.name === "__proto__" && !node.computed) || (node.property.type === "Literal" && node.property.value === "__proto__")) { - context.report(node, "The '__proto__' property is deprecated."); + context.report({ node, message: "The '__proto__' property is deprecated." }); } } }; diff --git a/tools/eslint/lib/rules/no-prototype-builtins.js b/tools/eslint/lib/rules/no-prototype-builtins.js index e9f46881597333..b9f040eaf67497 100644 --- a/tools/eslint/lib/rules/no-prototype-builtins.js +++ b/tools/eslint/lib/rules/no-prototype-builtins.js @@ -41,7 +41,7 @@ module.exports = { context.report({ message: "Do not access Object.prototype method '{{prop}}' from target object.", loc: node.callee.property.loc.start, - data: {prop: propName}, + data: { prop: propName }, node }); } diff --git a/tools/eslint/lib/rules/no-redeclare.js b/tools/eslint/lib/rules/no-redeclare.js index fcd4943460b421..deb896289b76f0 100644 --- a/tools/eslint/lib/rules/no-redeclare.js +++ b/tools/eslint/lib/rules/no-redeclare.js @@ -21,7 +21,7 @@ module.exports = { { type: "object", properties: { - builtinGlobals: {type: "boolean"} + builtinGlobals: { type: "boolean" } }, additionalProperties: false } @@ -40,20 +40,15 @@ module.exports = { * @private */ function findVariablesInScope(scope) { - scope.variables.forEach(function(variable) { + scope.variables.forEach(variable => { const hasBuiltin = options.builtinGlobals && "writeable" in variable; const count = (hasBuiltin ? 1 : 0) + variable.identifiers.length; if (count >= 2) { - variable.identifiers.sort(function(a, b) { - return a.range[1] - b.range[1]; - }); + variable.identifiers.sort((a, b) => a.range[1] - b.range[1]); for (let i = (hasBuiltin ? 0 : 1), l = variable.identifiers.length; i < l; i++) { - context.report( - variable.identifiers[i], - "'{{a}}' is already defined.", - {a: variable.name}); + context.report({ node: variable.identifiers[i], message: "'{{a}}' is already defined.", data: { a: variable.name } }); } } }); diff --git a/tools/eslint/lib/rules/no-regex-spaces.js b/tools/eslint/lib/rules/no-regex-spaces.js index c6e26ac3980020..05ac86e87a9db3 100644 --- a/tools/eslint/lib/rules/no-regex-spaces.js +++ b/tools/eslint/lib/rules/no-regex-spaces.js @@ -46,7 +46,7 @@ module.exports = { context.report({ node, message: "Spaces are hard to count. Use {{{count}}}.", - data: {count}, + data: { count }, fix(fixer) { return fixer.replaceTextRange( [valueStart + regexResults.index, valueStart + regexResults.index + count], diff --git a/tools/eslint/lib/rules/no-restricted-globals.js b/tools/eslint/lib/rules/no-restricted-globals.js index 07ff8b532d2307..603a6b2d3762ae 100644 --- a/tools/eslint/lib/rules/no-restricted-globals.js +++ b/tools/eslint/lib/rules/no-restricted-globals.js @@ -40,9 +40,9 @@ module.exports = { * @private */ function reportReference(reference) { - context.report(reference.identifier, "Unexpected use of '{{name}}'.", { + context.report({ node: reference.identifier, message: "Unexpected use of '{{name}}'.", data: { name: reference.identifier.name - }); + } }); } /** @@ -60,14 +60,14 @@ module.exports = { const scope = context.getScope(); // Report variables declared elsewhere (ex: variables defined as "global" by eslint) - scope.variables.forEach(function(variable) { + scope.variables.forEach(variable => { if (!variable.defs.length && isRestricted(variable.name)) { variable.references.forEach(reportReference); } }); // Report variables not declared at all - scope.through.forEach(function(reference) { + scope.through.forEach(reference => { if (isRestricted(reference.identifier.name)) { reportReference(reference); } diff --git a/tools/eslint/lib/rules/no-restricted-imports.js b/tools/eslint/lib/rules/no-restricted-imports.js index 87f9af2a6477e0..c245f22a0a4494 100644 --- a/tools/eslint/lib/rules/no-restricted-imports.js +++ b/tools/eslint/lib/rules/no-restricted-imports.js @@ -8,6 +8,16 @@ // Rule Definition //------------------------------------------------------------------------------ +const ignore = require("ignore"); + +const arrayOfStrings = { + type: "array", + items: { + type: "string" + }, + uniqueItems: true +}; + module.exports = { meta: { docs: { @@ -17,31 +27,55 @@ module.exports = { }, schema: { - type: "array", - items: { - type: "string" - }, - uniqueItems: true + anyOf: [ + arrayOfStrings, + { + type: "array", + items: [{ + type: "object", + properties: { + paths: arrayOfStrings, + patterns: arrayOfStrings + }, + additionalProperties: false + }], + additionalItems: false + } + ] } }, create(context) { - const restrictedImports = context.options; + const options = Array.isArray(context.options) ? context.options : []; + const isStringArray = typeof options[0] !== "object"; + const restrictedPaths = new Set(isStringArray ? context.options : options[0].paths || []); + const restrictedPatterns = isStringArray ? [] : options[0].patterns || []; // if no imports are restricted we don"t need to check - if (restrictedImports.length === 0) { + if (restrictedPaths.size === 0 && restrictedPatterns.length === 0) { return {}; } + const ig = ignore().add(restrictedPatterns); + return { ImportDeclaration(node) { if (node && node.source && node.source.value) { - const value = node.source.value.trim(); + const importName = node.source.value.trim(); - if (restrictedImports.indexOf(value) !== -1) { - context.report(node, "'{{importName}}' import is restricted from being used.", { - importName: value + if (restrictedPaths.has(importName)) { + context.report({ + node, + message: "'{{importName}}' import is restricted from being used.", + data: { importName } + }); + } + if (restrictedPatterns.length > 0 && ig.ignores(importName)) { + context.report({ + node, + message: "'{{importName}}' import is restricted from being used by a pattern.", + data: { importName } }); } } diff --git a/tools/eslint/lib/rules/no-restricted-modules.js b/tools/eslint/lib/rules/no-restricted-modules.js index 1a46c40a81dbe2..3a9634de9e18d1 100644 --- a/tools/eslint/lib/rules/no-restricted-modules.js +++ b/tools/eslint/lib/rules/no-restricted-modules.js @@ -8,6 +8,16 @@ // Rule Definition //------------------------------------------------------------------------------ +const ignore = require("ignore"); + +const arrayOfStrings = { + type: "array", + items: { + type: "string" + }, + uniqueItems: true +}; + module.exports = { meta: { docs: { @@ -17,24 +27,37 @@ module.exports = { }, schema: { - type: "array", - items: { - type: "string" - }, - uniqueItems: true + anyOf: [ + arrayOfStrings, + { + type: "array", + items: [{ + type: "object", + properties: { + paths: arrayOfStrings, + patterns: arrayOfStrings + }, + additionalProperties: false + }], + additionalItems: false + } + ] } }, create(context) { + const options = Array.isArray(context.options) ? context.options : []; + const isStringArray = typeof options[0] !== "object"; + const restrictedPaths = new Set(isStringArray ? context.options : options[0].paths || []); + const restrictedPatterns = isStringArray ? [] : options[0].patterns || []; - // trim restricted module names - const restrictedModules = context.options; - - // if no modules are restricted we don't need to check the CallExpressions - if (restrictedModules.length === 0) { + // if no imports are restricted we don"t need to check + if (restrictedPaths.size === 0 && restrictedPatterns.length === 0) { return {}; } + const ig = ignore().add(restrictedPatterns); + /** * Function to check if a node is a string literal. * @param {ASTNode} node The node to check. @@ -53,36 +76,30 @@ module.exports = { return node.callee.type === "Identifier" && node.callee.name === "require"; } - /** - * Function to check if a node has an argument that is an restricted module and return its name. - * @param {ASTNode} node The node to check - * @returns {undefined|string} restricted module name or undefined if node argument isn't restricted. - */ - function getRestrictedModuleName(node) { - let moduleName; - - // node has arguments and first argument is string - if (node.arguments.length && isString(node.arguments[0])) { - const argumentValue = node.arguments[0].value.trim(); - - // check if argument value is in restricted modules array - if (restrictedModules.indexOf(argumentValue) !== -1) { - moduleName = argumentValue; - } - } - - return moduleName; - } - return { CallExpression(node) { if (isRequireCall(node)) { - const restrictedModuleName = getRestrictedModuleName(node); - if (restrictedModuleName) { - context.report(node, "'{{moduleName}}' module is restricted from being used.", { - moduleName: restrictedModuleName - }); + // node has arguments and first argument is string + if (node.arguments.length && isString(node.arguments[0])) { + const moduleName = node.arguments[0].value.trim(); + + // check if argument value is in restricted modules array + if (restrictedPaths.has(moduleName)) { + context.report({ + node, + message: "'{{moduleName}}' module is restricted from being used.", + data: { moduleName } + }); + } + + if (restrictedPatterns.length > 0 && ig.ignores(moduleName)) { + context.report({ + node, + message: "'{{moduleName}}' module is restricted from being used by a pattern.", + data: { moduleName } + }); + } } } } diff --git a/tools/eslint/lib/rules/no-restricted-properties.js b/tools/eslint/lib/rules/no-restricted-properties.js index f8bd47ba4b2c18..b6c584c57e32e3 100644 --- a/tools/eslint/lib/rules/no-restricted-properties.js +++ b/tools/eslint/lib/rules/no-restricted-properties.js @@ -77,9 +77,9 @@ module.exports = { const propertyName = option.property; if (typeof objectName === "undefined") { - globallyRestrictedProperties.set(propertyName, {message: option.message}); + globallyRestrictedProperties.set(propertyName, { message: option.message }); } else if (typeof propertyName === "undefined") { - globallyRestrictedObjects.set(objectName, {message: option.message}); + globallyRestrictedObjects.set(objectName, { message: option.message }); } else { if (!restrictedProperties.has(objectName)) { restrictedProperties.set(objectName, new Map()); @@ -109,18 +109,18 @@ module.exports = { if (matchedObjectProperty) { const message = matchedObjectProperty.message ? ` ${matchedObjectProperty.message}` : ""; - context.report(node, "'{{objectName}}.{{propertyName}}' is restricted from being used.{{message}}", { + context.report({ node, message: "'{{objectName}}.{{propertyName}}' is restricted from being used.{{message}}", data: { objectName, propertyName, message - }); + } }); } else if (globalMatchedProperty) { const message = globalMatchedProperty.message ? ` ${globalMatchedProperty.message}` : ""; - context.report(node, "'{{propertyName}}' is restricted from being used.{{message}}", { + context.report({ node, message: "'{{propertyName}}' is restricted from being used.{{message}}", data: { propertyName, message - }); + } }); } } diff --git a/tools/eslint/lib/rules/no-restricted-syntax.js b/tools/eslint/lib/rules/no-restricted-syntax.js index ab6c36923a69b0..830452d995dab4 100644 --- a/tools/eslint/lib/rules/no-restricted-syntax.js +++ b/tools/eslint/lib/rules/no-restricted-syntax.js @@ -22,9 +22,7 @@ module.exports = { type: "array", items: [ { - enum: Object.keys(nodeTypes).map(function(k) { - return nodeTypes[k]; - }) + enum: Object.keys(nodeTypes).map(k => nodeTypes[k]) } ], uniqueItems: true, @@ -40,10 +38,10 @@ module.exports = { * @returns {void} */ function warn(node) { - context.report(node, "Using '{{type}}' is not allowed.", node); + context.report({ node, message: "Using '{{type}}' is not allowed.", data: node }); } - return context.options.reduce(function(result, nodeType) { + return context.options.reduce((result, nodeType) => { result[nodeType] = warn; return result; diff --git a/tools/eslint/lib/rules/no-return-await.js b/tools/eslint/lib/rules/no-return-await.js new file mode 100644 index 00000000000000..bc0498cb044d70 --- /dev/null +++ b/tools/eslint/lib/rules/no-return-await.js @@ -0,0 +1,94 @@ +/** + * @fileoverview Disallows unnecessary `return await` + * @author Jordan Harband + */ +"use strict"; + +const astUtils = require("../ast-utils"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +const message = "Redundant use of `await` on a return value."; + +module.exports = { + meta: { + docs: { + description: "disallow unnecessary `return await`", + category: "Best Practices", + recommended: false // TODO: set to true + }, + fixable: false, + schema: [ + ] + }, + + create(context) { + + /** + * Reports a found unnecessary `await` expression. + * @param {ASTNode} node The node representing the `await` expression to report + * @returns {void} + */ + function reportUnnecessaryAwait(node) { + context.report({ + node: context.getSourceCode().getFirstToken(node), + loc: node.loc, + message, + }); + } + + /** + * Determines whether a thrown error from this node will be caught/handled within this function rather than immediately halting + * this function. For example, a statement in a `try` block will always have an error handler. A statement in + * a `catch` block will only have an error handler if there is also a `finally` block. + * @param {ASTNode} node A node representing a location where an could be thrown + * @returns {boolean} `true` if a thrown error will be caught/handled in this function + */ + function hasErrorHandler(node) { + let ancestor = node; + + while (!astUtils.isFunction(ancestor) && ancestor.type !== "Program") { + if (ancestor.parent.type === "TryStatement" && (ancestor === ancestor.parent.block || ancestor === ancestor.parent.handler && ancestor.parent.finalizer)) { + return true; + } + ancestor = ancestor.parent; + } + return false; + } + + /** + * Checks if a node is placed in tail call position. Once `return` arguments (or arrow function expressions) can be a complex expression, + * an `await` expression could or could not be unnecessary by the definition of this rule. So we're looking for `await` expressions that are in tail position. + * @param {ASTNode} node A node representing the `await` expression to check + * @returns {boolean} The checking result + */ + function isInTailCallPosition(node) { + if (node.parent.type === "ArrowFunctionExpression") { + return true; + } + if (node.parent.type === "ReturnStatement") { + return !hasErrorHandler(node.parent); + } + if (node.parent.type === "ConditionalExpression" && (node === node.parent.consequent || node === node.parent.alternate)) { + return isInTailCallPosition(node.parent); + } + if (node.parent.type === "LogicalExpression" && node === node.parent.right) { + return isInTailCallPosition(node.parent); + } + if (node.parent.type === "SequenceExpression" && node === node.parent.expressions[node.parent.expressions.length - 1]) { + return isInTailCallPosition(node.parent); + } + return false; + } + + return { + AwaitExpression(node) { + if (isInTailCallPosition(node) && !hasErrorHandler(node)) { + reportUnnecessaryAwait(node); + } + }, + }; + } +}; diff --git a/tools/eslint/lib/rules/no-script-url.js b/tools/eslint/lib/rules/no-script-url.js index fd2f1e8c3e8954..98f988ff1a3b96 100644 --- a/tools/eslint/lib/rules/no-script-url.js +++ b/tools/eslint/lib/rules/no-script-url.js @@ -31,7 +31,7 @@ module.exports = { const value = node.value.toLowerCase(); if (value.indexOf("javascript:") === 0) { - context.report(node, "Script URL is a form of eval."); + context.report({ node, message: "Script URL is a form of eval." }); } } } diff --git a/tools/eslint/lib/rules/no-self-compare.js b/tools/eslint/lib/rules/no-self-compare.js index 17ce77a939d53e..54f907f594be06 100644 --- a/tools/eslint/lib/rules/no-self-compare.js +++ b/tools/eslint/lib/rules/no-self-compare.js @@ -31,7 +31,7 @@ module.exports = { if (operators.indexOf(node.operator) > -1 && (node.left.type === "Identifier" && node.right.type === "Identifier" && node.left.name === node.right.name || node.left.type === "Literal" && node.right.type === "Literal" && node.left.value === node.right.value)) { - context.report(node, "Comparing to itself is potentially pointless."); + context.report({ node, message: "Comparing to itself is potentially pointless." }); } } }; diff --git a/tools/eslint/lib/rules/no-sequences.js b/tools/eslint/lib/rules/no-sequences.js index 49f20ea43ff61a..67f9d8212fd4e5 100644 --- a/tools/eslint/lib/rules/no-sequences.js +++ b/tools/eslint/lib/rules/no-sequences.js @@ -101,7 +101,7 @@ module.exports = { const child = sourceCode.getTokenAfter(node.expressions[0]); - context.report(node, child.loc.start, "Unexpected use of comma operator."); + context.report({ node, loc: child.loc.start, message: "Unexpected use of comma operator." }); } }; diff --git a/tools/eslint/lib/rules/no-shadow.js b/tools/eslint/lib/rules/no-shadow.js index 27ea10ef9217aa..e093d48c810aeb 100644 --- a/tools/eslint/lib/rules/no-shadow.js +++ b/tools/eslint/lib/rules/no-shadow.js @@ -27,8 +27,8 @@ module.exports = { { type: "object", properties: { - builtinGlobals: {type: "boolean"}, - hoist: {enum: ["all", "functions", "never"]}, + builtinGlobals: { type: "boolean" }, + hoist: { enum: ["all", "functions", "never"] }, allow: { type: "array", items: { diff --git a/tools/eslint/lib/rules/no-sparse-arrays.js b/tools/eslint/lib/rules/no-sparse-arrays.js index 31bd6f2bbffb00..3044896c612d17 100644 --- a/tools/eslint/lib/rules/no-sparse-arrays.js +++ b/tools/eslint/lib/rules/no-sparse-arrays.js @@ -33,7 +33,7 @@ module.exports = { const emptySpot = node.elements.indexOf(null) > -1; if (emptySpot) { - context.report(node, "Unexpected comma in middle of array."); + context.report({ node, message: "Unexpected comma in middle of array." }); } } diff --git a/tools/eslint/lib/rules/no-tabs.js b/tools/eslint/lib/rules/no-tabs.js index d57ac324c1d58b..19983c57ba9ed4 100644 --- a/tools/eslint/lib/rules/no-tabs.js +++ b/tools/eslint/lib/rules/no-tabs.js @@ -17,7 +17,7 @@ const regex = /\t/; module.exports = { meta: { docs: { - description: "disallow tabs in file", + description: "disallow all tabs", category: "Stylistic Issues", recommended: false }, @@ -31,14 +31,10 @@ module.exports = { const match = regex.exec(line); if (match) { - context.report( - node, - { - line: index + 1, - column: match.index + 1 - }, - "Unexpected tab character." - ); + context.report({ node, loc: { + line: index + 1, + column: match.index + 1 + }, message: "Unexpected tab character." }); } }); } diff --git a/tools/eslint/lib/rules/no-ternary.js b/tools/eslint/lib/rules/no-ternary.js index 2408cd9c39a0ea..3e254f68126f5a 100644 --- a/tools/eslint/lib/rules/no-ternary.js +++ b/tools/eslint/lib/rules/no-ternary.js @@ -25,7 +25,7 @@ module.exports = { return { ConditionalExpression(node) { - context.report(node, "Ternary operator used."); + context.report({ node, message: "Ternary operator used." }); } }; diff --git a/tools/eslint/lib/rules/no-this-before-super.js b/tools/eslint/lib/rules/no-this-before-super.js index 80a769a481a44a..c8d5dc4698d7b0 100644 --- a/tools/eslint/lib/rules/no-this-before-super.js +++ b/tools/eslint/lib/rules/no-this-before-super.js @@ -179,7 +179,7 @@ module.exports = { return; } - codePath.traverseSegments(function(segment, controller) { + codePath.traverseSegments((segment, controller) => { const info = segInfoMap[segment.id]; for (let i = 0; i < info.invalidNodes.length; ++i) { @@ -236,8 +236,8 @@ module.exports = { // Update information inside of the loop. funcInfo.codePath.traverseSegments( - {first: toSegment, last: fromSegment}, - function(segment, controller) { + { first: toSegment, last: fromSegment }, + (segment, controller) => { const info = segInfoMap[segment.id]; if (info.superCalled) { diff --git a/tools/eslint/lib/rules/no-throw-literal.js b/tools/eslint/lib/rules/no-throw-literal.js index 034361c7a620c9..0d1f42985f89ec 100644 --- a/tools/eslint/lib/rules/no-throw-literal.js +++ b/tools/eslint/lib/rules/no-throw-literal.js @@ -65,10 +65,10 @@ module.exports = { ThrowStatement(node) { if (!couldBeError(node.argument)) { - context.report(node, "Expected an object to be thrown."); + context.report({ node, message: "Expected an object to be thrown." }); } else if (node.argument.type === "Identifier") { if (node.argument.name === "undefined") { - context.report(node, "Do not throw undefined."); + context.report({ node, message: "Do not throw undefined." }); } } diff --git a/tools/eslint/lib/rules/no-undef-init.js b/tools/eslint/lib/rules/no-undef-init.js index ca9f0272ba5bf5..9df40e9cebb186 100644 --- a/tools/eslint/lib/rules/no-undef-init.js +++ b/tools/eslint/lib/rules/no-undef-init.js @@ -41,7 +41,7 @@ module.exports = { context.report({ node, message: "It's not necessary to initialize '{{name}}' to undefined.", - data: {name}, + data: { name }, fix(fixer) { if (node.id.type === "ArrayPattern" || node.id.type === "ObjectPattern") { diff --git a/tools/eslint/lib/rules/no-undef.js b/tools/eslint/lib/rules/no-undef.js index 2cd2980f840581..74a33dd9973234 100644 --- a/tools/eslint/lib/rules/no-undef.js +++ b/tools/eslint/lib/rules/no-undef.js @@ -52,7 +52,7 @@ module.exports = { "Program:exit"(/* node */) { const globalScope = context.getScope(); - globalScope.through.forEach(function(ref) { + globalScope.through.forEach(ref => { const identifier = ref.identifier; if (!considerTypeOf && hasTypeOfOperator(identifier)) { diff --git a/tools/eslint/lib/rules/no-undefined.js b/tools/eslint/lib/rules/no-undefined.js index 2aad3d0d1f4b55..18e1d98641dc86 100644 --- a/tools/eslint/lib/rules/no-undefined.js +++ b/tools/eslint/lib/rules/no-undefined.js @@ -28,7 +28,7 @@ module.exports = { const parent = context.getAncestors().pop(); if (!parent || parent.type !== "MemberExpression" || node !== parent.property || parent.computed) { - context.report(node, "Unexpected use of undefined."); + context.report({ node, message: "Unexpected use of undefined." }); } } } diff --git a/tools/eslint/lib/rules/no-underscore-dangle.js b/tools/eslint/lib/rules/no-underscore-dangle.js index abc5967b5348be..6803cc68fc7e81 100644 --- a/tools/eslint/lib/rules/no-underscore-dangle.js +++ b/tools/eslint/lib/rules/no-underscore-dangle.js @@ -57,9 +57,7 @@ module.exports = { * @private */ function isAllowed(identifier) { - return ALLOWED_VARIABLES.some(function(ident) { - return ident === identifier; - }); + return ALLOWED_VARIABLES.some(ident => ident === identifier); } /** diff --git a/tools/eslint/lib/rules/no-unexpected-multiline.js b/tools/eslint/lib/rules/no-unexpected-multiline.js index 5208813dadada0..bae4833983b14e 100644 --- a/tools/eslint/lib/rules/no-unexpected-multiline.js +++ b/tools/eslint/lib/rules/no-unexpected-multiline.js @@ -45,7 +45,7 @@ module.exports = { } if (openParen.loc.start.line !== nodeExpressionEnd.loc.end.line) { - context.report(node, openParen.loc.start, msg, { char: openParen.value }); + context.report({ node, loc: openParen.loc.start, message: msg, data: { char: openParen.value } }); } } @@ -66,7 +66,7 @@ module.exports = { if (node.tag.loc.end.line === node.quasi.loc.start.line) { return; } - context.report(node, node.loc.start, TAGGED_TEMPLATE_MESSAGE); + context.report({ node, loc: node.loc.start, message: TAGGED_TEMPLATE_MESSAGE }); }, CallExpression(node) { diff --git a/tools/eslint/lib/rules/no-unneeded-ternary.js b/tools/eslint/lib/rules/no-unneeded-ternary.js index c755f5f4b4fd11..cba83ea48140ec 100644 --- a/tools/eslint/lib/rules/no-unneeded-ternary.js +++ b/tools/eslint/lib/rules/no-unneeded-ternary.js @@ -5,6 +5,19 @@ "use strict"; +const astUtils = require("../ast-utils"); + +// Operators that always result in a boolean value +const BOOLEAN_OPERATORS = new Set(["==", "===", "!=", "!==", ">", ">=", "<", "<=", "in", "instanceof"]); +const OPERATOR_INVERSES = { + "==": "!=", + "!=": "==", + "===": "!==", + "!==": "===" + + // Operators like < and >= are not true inverses, since both will return false with NaN. +}; + //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ @@ -27,12 +40,15 @@ module.exports = { }, additionalProperties: false } - ] + ], + + fixable: "code" }, create(context) { const options = context.options[0] || {}; const defaultAssignment = options.defaultAssignment !== false; + const sourceCode = context.getSourceCode(); /** * Test if the node is a boolean literal @@ -44,6 +60,34 @@ module.exports = { return node.type === "Literal" && typeof node.value === "boolean"; } + /** + * Creates an expression that represents the boolean inverse of the expression represented by the original node + * @param {ASTNode} node A node representing an expression + * @returns {string} A string representing an inverted expression + */ + function invertExpression(node) { + if (node.type === "BinaryExpression" && Object.prototype.hasOwnProperty.call(OPERATOR_INVERSES, node.operator)) { + const operatorToken = sourceCode.getTokensBetween(node.left, node.right).find(token => token.value === node.operator); + + return sourceCode.getText().slice(node.range[0], operatorToken.range[0]) + OPERATOR_INVERSES[node.operator] + sourceCode.getText().slice(operatorToken.range[1], node.range[1]); + } + + if (astUtils.getPrecedence(node) < astUtils.getPrecedence({ type: "UnaryExpression" })) { + return `!(${astUtils.getParenthesisedText(sourceCode, node)})`; + } + return `!${astUtils.getParenthesisedText(sourceCode, node)}`; + } + + /** + * Tests if a given node always evaluates to a boolean value + * @param {ASTNode} node - An expression node + * @returns {boolean} True if it is determined that the node will always evaluate to a boolean value + */ + function isBooleanExpression(node) { + return node.type === "BinaryExpression" && BOOLEAN_OPERATORS.has(node.operator) || + node.type === "UnaryExpression" && node.operator === "!"; + } + /** * Test if the node matches the pattern id ? id : expression * @param {ASTNode} node - The ConditionalExpression to check. @@ -60,9 +104,34 @@ module.exports = { ConditionalExpression(node) { if (isBooleanLiteral(node.alternate) && isBooleanLiteral(node.consequent)) { - context.report(node, node.consequent.loc.start, "Unnecessary use of boolean literals in conditional expression."); + context.report({ + node, + loc: node.consequent.loc.start, + message: "Unnecessary use of boolean literals in conditional expression.", + fix(fixer) { + if (node.consequent.value === node.alternate.value) { + + // Replace `foo ? true : true` with just `true`, but don't replace `foo() ? true : true` + return node.test.type === "Identifier" ? fixer.replaceText(node, node.consequent.value.toString()) : null; + } + if (node.alternate.value) { + + // Replace `foo() ? false : true` with `!(foo())` + return fixer.replaceText(node, invertExpression(node.test)); + } + + // Replace `foo ? true : false` with `foo` if `foo` is guaranteed to be a boolean, or `!!foo` otherwise. + + return fixer.replaceText(node, isBooleanExpression(node.test) ? astUtils.getParenthesisedText(sourceCode, node.test) : `!${invertExpression(node.test)}`); + } + }); } else if (!defaultAssignment && matchesDefaultAssignment(node)) { - context.report(node, node.consequent.loc.start, "Unnecessary use of conditional expression for default assignment."); + context.report({ + node, + loc: node.consequent.loc.start, + message: "Unnecessary use of conditional expression for default assignment.", + fix: fixer => fixer.replaceText(node, `${astUtils.getParenthesisedText(sourceCode, node.test)} || ${astUtils.getParenthesisedText(sourceCode, node.alternate)}`) + }); } } }; diff --git a/tools/eslint/lib/rules/no-unused-expressions.js b/tools/eslint/lib/rules/no-unused-expressions.js index cdabca204a64df..548e02f463e71a 100644 --- a/tools/eslint/lib/rules/no-unused-expressions.js +++ b/tools/eslint/lib/rules/no-unused-expressions.js @@ -108,7 +108,7 @@ module.exports = { return { ExpressionStatement(node) { if (!isValidExpression(node.expression) && !isDirective(node, context.getAncestors())) { - context.report(node, "Expected an assignment or function call and instead saw an expression."); + context.report({ node, message: "Expected an assignment or function call and instead saw an expression." }); } } }; diff --git a/tools/eslint/lib/rules/no-unused-vars.js b/tools/eslint/lib/rules/no-unused-vars.js index 683176e944f357..ac8f2ed1c0a20a 100644 --- a/tools/eslint/lib/rules/no-unused-vars.js +++ b/tools/eslint/lib/rules/no-unused-vars.js @@ -156,28 +156,6 @@ module.exports = { return false; } - /** - * Checks whether a given node is inside of a loop or not. - * - * @param {ASTNode} node - A node to check. - * @returns {boolean} `true` if the node is inside of a loop. - * @private - */ - function isInsideOfLoop(node) { - while (node) { - if (astUtils.isLoop(node)) { - return true; - } - if (astUtils.isFunction(node)) { - return false; - } - - node = node.parent; - } - - return false; - } - /** * Checks the position of given nodes. * @@ -215,7 +193,7 @@ module.exports = { const granpa = parent.parent; const refScope = ref.from.variableScope; const varScope = ref.resolved.scope.variableScope; - const canBeUsedLater = refScope !== varScope || isInsideOfLoop(id); + const canBeUsedLater = refScope !== varScope || astUtils.isInLoop(id); /* * Inherits the previous node if this reference is in the node. @@ -390,15 +368,11 @@ module.exports = { * @private */ function isUsedVariable(variable) { - const functionNodes = variable.defs.filter(function(def) { - return def.type === "FunctionName"; - }).map(function(def) { - return def.node; - }), + const functionNodes = variable.defs.filter(def => def.type === "FunctionName").map(def => def.node), isFunctionDefinition = functionNodes.length > 0; let rhsNode = null; - return variable.references.some(function(ref) { + return variable.references.some(ref => { if (isForInRef(ref)) { return true; } diff --git a/tools/eslint/lib/rules/no-use-before-define.js b/tools/eslint/lib/rules/no-use-before-define.js index 01c899ca3920c4..ea1cf301f29af4 100644 --- a/tools/eslint/lib/rules/no-use-before-define.js +++ b/tools/eslint/lib/rules/no-use-before-define.js @@ -29,7 +29,7 @@ function parseOptions(options) { classes = options.classes !== false; } - return {functions, classes}; + return { functions, classes }; } /** @@ -154,8 +154,8 @@ module.exports = { { type: "object", properties: { - functions: {type: "boolean"}, - classes: {type: "boolean"} + functions: { type: "boolean" }, + classes: { type: "boolean" } }, additionalProperties: false } @@ -187,7 +187,7 @@ module.exports = { * @private */ function findVariablesInScope(scope) { - scope.references.forEach(function(reference) { + scope.references.forEach(reference => { const variable = reference.resolved; // Skips when the reference is: diff --git a/tools/eslint/lib/rules/no-useless-call.js b/tools/eslint/lib/rules/no-useless-call.js index 2be665992a08e5..eb67bcb3b25271 100644 --- a/tools/eslint/lib/rules/no-useless-call.js +++ b/tools/eslint/lib/rules/no-useless-call.js @@ -96,10 +96,7 @@ module.exports = { const thisArg = node.arguments[0]; if (isValidThisArg(expectedThis, thisArg, sourceCode)) { - context.report( - node, - "unnecessary '.{{name}}()'.", - {name: node.callee.property.name}); + context.report({ node, message: "unnecessary '.{{name}}()'.", data: { name: node.callee.property.name } }); } } }; diff --git a/tools/eslint/lib/rules/no-useless-concat.js b/tools/eslint/lib/rules/no-useless-concat.js index d9cf6a2c354b8b..ed0ef66a2441e1 100644 --- a/tools/eslint/lib/rules/no-useless-concat.js +++ b/tools/eslint/lib/rules/no-useless-concat.js @@ -93,10 +93,11 @@ module.exports = { operatorToken = sourceCode.getTokenAfter(operatorToken); } - context.report( + context.report({ node, - operatorToken.loc.start, - "Unexpected string concatenation of literals."); + loc: operatorToken.loc.start, + message: "Unexpected string concatenation of literals." + }); } } }; diff --git a/tools/eslint/lib/rules/no-useless-escape.js b/tools/eslint/lib/rules/no-useless-escape.js index 629a52a7ec9b9f..b9266bbbafa69a 100644 --- a/tools/eslint/lib/rules/no-useless-escape.js +++ b/tools/eslint/lib/rules/no-useless-escape.js @@ -5,57 +5,70 @@ "use strict"; +const astUtils = require("../ast-utils"); + //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ -const VALID_STRING_ESCAPES = [ - "\\", - "n", - "r", - "v", - "t", - "b", - "f", - "u", - "x", - "\n", - "\r" -]; - -const VALID_REGEX_ESCAPES = [ - "\\", - ".", - "-", - "^", - "$", - "*", - "+", - "?", - "{", - "}", - "[", - "]", - "|", - "(", - ")", - "b", - "B", - "c", - "d", - "D", - "f", - "n", - "r", - "s", - "S", - "t", - "v", - "w", - "W", - "x", - "u" -]; +/** +* Returns the union of two sets. +* @param {Set} setA The first set +* @param {Set} setB The second set +* @returns {Set} The union of the two sets +*/ +function union(setA, setB) { + return new Set(function *() { + yield* setA; + yield* setB; + }()); +} + +const VALID_STRING_ESCAPES = new Set("\\nrvtbfux\n\r\u2028\u2029"); +const REGEX_GENERAL_ESCAPES = new Set("\\bcdDfnrsStvwWxu0123456789]"); +const REGEX_NON_CHARCLASS_ESCAPES = union(REGEX_GENERAL_ESCAPES, new Set("^/.$*+?[{}|()B")); + +/** +* Parses a regular expression into a list of characters with character class info. +* @param {string} regExpText The raw text used to create the regular expression +* @returns {Object[]} A list of characters, each with info on escaping and whether they're in a character class. +* @example +* +* parseRegExp('a\\b[cd-]') +* +* returns: +* [ +* {text: 'a', index: 0, escaped: false, inCharClass: false, startsCharClass: false, endsCharClass: false}, +* {text: 'b', index: 2, escaped: true, inCharClass: false, startsCharClass: false, endsCharClass: false}, +* {text: 'c', index: 4, escaped: false, inCharClass: true, startsCharClass: true, endsCharClass: false}, +* {text: 'd', index: 5, escaped: false, inCharClass: true, startsCharClass: false, endsCharClass: false}, +* {text: '-', index: 6, escaped: false, inCharClass: true, startsCharClass: false, endsCharClass: false} +* ] +*/ +function parseRegExp(regExpText) { + const charList = []; + + regExpText.split("").reduce((state, char, index) => { + if (!state.escapeNextChar) { + if (char === "\\") { + return Object.assign(state, { escapeNextChar: true }); + } + if (char === "[" && !state.inCharClass) { + return Object.assign(state, { inCharClass: true, startingCharClass: true }); + } + if (char === "]" && state.inCharClass) { + if (charList.length && charList[charList.length - 1].inCharClass) { + charList[charList.length - 1].endsCharClass = true; + } + return Object.assign(state, { inCharClass: false, startingCharClass: false }); + } + } + charList.push({ text: char, index, escaped: state.escapeNextChar, inCharClass: state.inCharClass, startsCharClass: state.startingCharClass, endsCharClass: false }); + return Object.assign(state, { escapeNextChar: false, startingCharClass: false }); + }, { escapeNextChar: false, inCharClass: false, startingCharClass: false }); + + return charList; +} module.exports = { meta: { @@ -69,20 +82,36 @@ module.exports = { }, create(context) { + const sourceCode = context.getSourceCode(); + + /** + * Reports a node + * @param {ASTNode} node The node to report + * @param {number} startOffset The backslash's offset from the start of the node + * @param {string} character The uselessly escaped character (not including the backslash) + * @returns {void} + */ + function report(node, startOffset, character) { + context.report({ + node, + loc: astUtils.getLocationFromRangeIndex(sourceCode, astUtils.getRangeIndexFromLocation(sourceCode, node.loc.start) + startOffset), + message: "Unnecessary escape character: \\{{character}}.", + data: { character } + }); + } /** - * Checks if the escape character in given slice is unnecessary. + * Checks if the escape character in given string slice is unnecessary. * * @private - * @param {string[]} escapes - list of valid escapes * @param {ASTNode} node - node to validate. * @param {string} match - string slice to validate. * @returns {void} */ - function validate(escapes, node, match) { + function validateString(node, match) { const isTemplateElement = node.type === "TemplateElement"; const escapedChar = match[0][1]; - let isUnnecessaryEscape = escapes.indexOf(escapedChar) === -1; + let isUnnecessaryEscape = !VALID_STRING_ESCAPES.has(escapedChar); let isQuoteEscape; if (isTemplateElement) { @@ -105,17 +134,7 @@ module.exports = { } if (isUnnecessaryEscape && !isQuoteEscape) { - context.report({ - node, - loc: { - line: node.loc.start.line, - column: node.loc.start.column + match.index - }, - message: "Unnecessary escape character: {{character}}.", - data: { - character: match[0] - } - }); + report(node, match.index + 1, match[0].slice(1)); } } @@ -127,10 +146,12 @@ module.exports = { */ function check(node) { const isTemplateElement = node.type === "TemplateElement"; - const value = isTemplateElement ? node.value.raw : node.raw; - const pattern = /\\[^\d]/g; - let nodeEscapes, - match; + + if (isTemplateElement && node.parent && node.parent.parent && node.parent.parent.type === "TaggedTemplateExpression") { + + // Don't report tagged template literals, because the backslash character is accessible to the tag function. + return; + } if (typeof node.value === "string" || isTemplateElement) { @@ -138,20 +159,46 @@ module.exports = { * JSXAttribute doesn't have any escape sequence: https://facebook.github.io/jsx/. * In addition, backticks are not supported by JSX yet: https://github.com/facebook/jsx/issues/25. */ - if (node.parent.type === "JSXAttribute") { + if (node.parent.type === "JSXAttribute" || node.parent.type === "JSXElement") { return; } - nodeEscapes = VALID_STRING_ESCAPES; + const value = isTemplateElement ? node.value.raw : node.raw.slice(1, -1); + const pattern = /\\[^\d]/g; + let match; + + while ((match = pattern.exec(value))) { + validateString(node, match); + } } else if (node.regex) { - nodeEscapes = VALID_REGEX_ESCAPES; - } else { - return; - } + parseRegExp(node.regex.pattern) - while ((match = pattern.exec(value))) { - validate(nodeEscapes, node, match); + /* + * The '-' character is a special case, because it's only valid to escape it if it's in a character + * class, and is not at either edge of the character class. To account for this, don't consider '-' + * characters to be valid in general, and filter out '-' characters that appear in the middle of a + * character class. + */ + .filter(charInfo => !(charInfo.text === "-" && charInfo.inCharClass && !charInfo.startsCharClass && !charInfo.endsCharClass)) + + /* + * The '^' character is also a special case; it must always be escaped outside of character classes, but + * it only needs to be escaped in character classes if it's at the beginning of the character class. To + * account for this, consider it to be a valid escape character outside of character classes, and filter + * out '^' characters that appear at the start of a character class. + */ + .filter(charInfo => !(charInfo.text === "^" && charInfo.startsCharClass)) + + // Filter out characters that aren't escaped. + .filter(charInfo => charInfo.escaped) + + // Filter out characters that are valid to escape, based on their position in the regular expression. + .filter(charInfo => !(charInfo.inCharClass ? REGEX_GENERAL_ESCAPES : REGEX_NON_CHARCLASS_ESCAPES).has(charInfo.text)) + + // Report all the remaining characters. + .forEach(charInfo => report(node, charInfo.index, charInfo.text)); } + } return { diff --git a/tools/eslint/lib/rules/no-useless-return.js b/tools/eslint/lib/rules/no-useless-return.js new file mode 100644 index 00000000000000..e2a6da03183501 --- /dev/null +++ b/tools/eslint/lib/rules/no-useless-return.js @@ -0,0 +1,293 @@ +/** + * @fileoverview Disallow redundant return statements + * @author Teddy Katz + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("../ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Adds all elements of 2nd argument into 1st argument. + * + * @param {Array} array - The destination array to add. + * @param {Array} elements - The source array to add. + * @returns {void} + */ +const pushAll = Function.apply.bind(Array.prototype.push); + +/** + * Removes the given element from the array. + * + * @param {Array} array - The source array to remove. + * @param {any} element - The target item to remove. + * @returns {void} + */ +function remove(array, element) { + const index = array.indexOf(element); + + if (index !== -1) { + array.splice(index, 1); + } +} + +/** + * Checks whether it can remove the given return statement or not. + * + * @param {ASTNode} node - The return statement node to check. + * @returns {boolean} `true` if the node is removeable. + */ +function isRemovable(node) { + const parent = node.parent; + + return ( + parent.type === "Program" || + parent.type === "BlockStatement" || + parent.type === "SwitchCase" + ); +} + +/** + * Checks whether the given return statement is in a `finally` block or not. + * + * @param {ASTNode} node - The return statement node to check. + * @returns {boolean} `true` if the node is in a `finally` block. + */ +function isInFinally(node) { + while (node && node.parent && !astUtils.isFunction(node)) { + if (node.parent.type === "TryStatement" && node.parent.finalizer === node) { + return true; + } + + node = node.parent; + } + + return false; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = { + meta: { + docs: { + description: "disallow redundant return statements", + category: "Best Practices", + recommended: false + }, + fixable: "code", + schema: [] + }, + + create(context) { + const segmentInfoMap = new WeakMap(); + const usedUnreachableSegments = new WeakSet(); + let scopeInfo = null; + + /** + * Checks whether the given segment is terminated by a return statement or not. + * + * @param {CodePathSegment} segment - The segment to check. + * @returns {boolean} `true` if the segment is terminated by a return statement, or if it's still a part of unreachable. + */ + function isReturned(segment) { + const info = segmentInfoMap.get(segment); + + return !info || info.returned; + } + + /** + * Collects useless return statements from the given previous segments. + * + * A previous segment may be an unreachable segment. + * In that case, the information object of the unreachable segment is not + * initialized because `onCodePathSegmentStart` event is not notified for + * unreachable segments. + * This goes to the previous segments of the unreachable segment recursively + * if the unreachable segment was generated by a return statement. Otherwise, + * this ignores the unreachable segment. + * + * This behavior would simulate code paths for the case that the return + * statement does not exist. + * + * @param {ASTNode[]} uselessReturns - The collected return statements. + * @param {CodePathSegment[]} prevSegments - The previous segments to traverse. + * @param {WeakSet} [traversedSegments] A set of segments that have already been traversed in this call + * @returns {ASTNode[]} `uselessReturns`. + */ + function getUselessReturns(uselessReturns, prevSegments, traversedSegments) { + if (!traversedSegments) { + traversedSegments = new WeakSet(); + } + for (const segment of prevSegments) { + if (!segment.reachable) { + if (!traversedSegments.has(segment)) { + traversedSegments.add(segment); + getUselessReturns( + uselessReturns, + segment.allPrevSegments.filter(isReturned), + traversedSegments + ); + } + continue; + } + + pushAll(uselessReturns, segmentInfoMap.get(segment).uselessReturns); + } + + return uselessReturns; + } + + /** + * Removes the return statements on the given segment from the useless return + * statement list. + * + * This segment may be an unreachable segment. + * In that case, the information object of the unreachable segment is not + * initialized because `onCodePathSegmentStart` event is not notified for + * unreachable segments. + * This goes to the previous segments of the unreachable segment recursively + * if the unreachable segment was generated by a return statement. Otherwise, + * this ignores the unreachable segment. + * + * This behavior would simulate code paths for the case that the return + * statement does not exist. + * + * @param {CodePathSegment} segment - The segment to get return statements. + * @returns {void} + */ + function markReturnStatementsOnSegmentAsUsed(segment) { + if (!segment.reachable) { + usedUnreachableSegments.add(segment); + segment.allPrevSegments + .filter(isReturned) + .filter(prevSegment => !usedUnreachableSegments.has(prevSegment)) + .forEach(markReturnStatementsOnSegmentAsUsed); + return; + } + + const info = segmentInfoMap.get(segment); + + for (const node of info.uselessReturns) { + remove(scopeInfo.uselessReturns, node); + } + info.uselessReturns = []; + } + + /** + * Removes the return statements on the current segments from the useless + * return statement list. + * + * This function will be called at every statement except FunctionDeclaration, + * BlockStatement, and BreakStatement. + * + * - FunctionDeclarations are always executed whether it's returned or not. + * - BlockStatements do nothing. + * - BreakStatements go the next merely. + * + * @returns {void} + */ + function markReturnStatementsOnCurrentSegmentsAsUsed() { + scopeInfo + .codePath + .currentSegments + .forEach(markReturnStatementsOnSegmentAsUsed); + } + + //---------------------------------------------------------------------- + // Public + //---------------------------------------------------------------------- + + return { + + // Makes and pushs a new scope information. + onCodePathStart(codePath) { + scopeInfo = { + upper: scopeInfo, + uselessReturns: [], + codePath, + }; + }, + + // Reports useless return statements if exist. + onCodePathEnd() { + for (const node of scopeInfo.uselessReturns) { + context.report({ + node, + loc: node.loc, + message: "Unnecessary return statement.", + fix(fixer) { + return isRemovable(node) ? fixer.remove(node) : null; + }, + }); + } + + scopeInfo = scopeInfo.upper; + }, + + // Initializes segments. + // NOTE: This event is notified for only reachable segments. + onCodePathSegmentStart(segment) { + const info = { + uselessReturns: getUselessReturns([], segment.allPrevSegments), + returned: false, + }; + + // Stores the info. + segmentInfoMap.set(segment, info); + }, + + // Adds ReturnStatement node to check whether it's useless or not. + ReturnStatement(node) { + if (node.argument) { + markReturnStatementsOnCurrentSegmentsAsUsed(); + } + if (node.argument || astUtils.isInLoop(node) || isInFinally(node)) { + return; + } + + for (const segment of scopeInfo.codePath.currentSegments) { + const info = segmentInfoMap.get(segment); + + if (info) { + info.uselessReturns.push(node); + info.returned = true; + } + } + scopeInfo.uselessReturns.push(node); + }, + + // Registers for all statement nodes except FunctionDeclaration, BlockStatement, BreakStatement. + // Removes return statements of the current segments from the useless return statement list. + ClassDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed, + ContinueStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + DebuggerStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + DoWhileStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + EmptyStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + ExpressionStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + ForInStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + ForOfStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + ForStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + IfStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + ImportDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed, + LabeledStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + SwitchStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + ThrowStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + TryStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + VariableDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed, + WhileStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + WithStatement: markReturnStatementsOnCurrentSegmentsAsUsed, + ExportNamedDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed, + ExportDefaultDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed, + ExportAllDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed, + }; + } +}; diff --git a/tools/eslint/lib/rules/no-var.js b/tools/eslint/lib/rules/no-var.js index 0e98170e65e7c1..3c22f009c63bb6 100644 --- a/tools/eslint/lib/rules/no-var.js +++ b/tools/eslint/lib/rules/no-var.js @@ -5,10 +5,67 @@ "use strict"; +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("../ast-utils"); + //------------------------------------------------------------------------------ // Helpers //------------------------------------------------------------------------------ +/** + * Finds the nearest function scope or global scope walking up the scope + * hierarchy. + * + * @param {escope.Scope} scope - The scope to traverse. + * @returns {escope.Scope} a function scope or global scope containing the given + * scope. + */ +function getEnclosingFunctionScope(scope) { + while (scope.type !== "function" && scope.type !== "global") { + scope = scope.upper; + } + return scope; +} + +/** + * Checks whether the given variable has any references from a more specific + * function expression (i.e. a closure). + * + * @param {escope.Variable} variable - A variable to check. + * @returns {boolean} `true` if the variable is used from a closure. + */ +function isReferencedInClosure(variable) { + const enclosingFunctionScope = getEnclosingFunctionScope(variable.scope); + + return variable.references.some(reference => + getEnclosingFunctionScope(reference.from) !== enclosingFunctionScope); +} + +/** + * Checks whether the given node is the assignee of a loop. + * + * @param {ASTNode} node - A VariableDeclaration node to check. + * @returns {boolean} `true` if the declaration is assigned as part of loop + * iteration. + */ +function isLoopAssignee(node) { + return (node.parent.type === "ForOfStatement" || node.parent.type === "ForInStatement") && + node === node.parent.left; +} + +/** + * Checks whether the given variable declaration is immediately initialized. + * + * @param {ASTNode} node - A VariableDeclaration node to check. + * @returns {boolean} `true` if the declaration has an initializer. + */ +function isDeclarationInitialized(node) { + return node.declarations.every(declarator => declarator.init !== null); +} + const SCOPE_NODE_TYPE = /^(?:Program|BlockStatement|SwitchStatement|ForStatement|ForInStatement|ForOfStatement)$/; /** @@ -97,6 +154,8 @@ module.exports = { * - A variable is declared on a SwitchCase node. * - A variable is redeclared. * - A variable is used from outside the scope. + * - A variable is used from a closure within a loop. + * - A variable might be used before it is assigned within a loop. * * ## A variable is declared on a SwitchCase node. * @@ -115,6 +174,25 @@ module.exports = { * The language spec disallows accesses from outside of the scope for * `let` declarations. Those variables would cause reference errors. * + * ## A variable is used from a closure within a loop. + * + * A `var` declaration within a loop shares the same variable instance + * across all loop iterations, while a `let` declaration creates a new + * instance for each iteration. This means if a variable in a loop is + * referenced by any closure, changing it from `var` to `let` would + * change the behavior in a way that is generally unsafe. + * + * ## A variable might be used before it is assigned within a loop. + * + * Within a loop, a `let` declaration without an initializer will be + * initialized to null, while a `var` declaration will retain its value + * from the previous iteration, so it is only safe to change `var` to + * `let` if we can statically determine that the variable is always + * assigned a value before its first access in the loop body. To keep + * the implementation simple, we only convert `var` to `let` within + * loops when the variable is a loop assignee or the declaration has an + * initializer. + * * @param {ASTNode} node - A variable declaration node to check. * @returns {boolean} `true` if it can fix the node. */ @@ -122,11 +200,22 @@ module.exports = { const variables = context.getDeclaredVariables(node); const scopeNode = getScopeNode(node); - return !( - node.parent.type === "SwitchCase" || - variables.some(isRedeclared) || - variables.some(isUsedFromOutsideOf(scopeNode)) - ); + if (node.parent.type === "SwitchCase" || + variables.some(isRedeclared) || + variables.some(isUsedFromOutsideOf(scopeNode))) { + return false; + } + + if (astUtils.isInLoop(node)) { + if (variables.some(isReferencedInClosure)) { + return false; + } + if (!isLoopAssignee(node) && !isDeclarationInitialized(node)) { + return false; + } + } + + return true; } /** diff --git a/tools/eslint/lib/rules/no-void.js b/tools/eslint/lib/rules/no-void.js index 16a36fb3a56df1..5202fa49a8543a 100644 --- a/tools/eslint/lib/rules/no-void.js +++ b/tools/eslint/lib/rules/no-void.js @@ -28,7 +28,7 @@ module.exports = { return { UnaryExpression(node) { if (node.operator === "void") { - context.report(node, "Expected 'undefined' and instead saw 'void'."); + context.report({ node, message: "Expected 'undefined' and instead saw 'void'." }); } } }; diff --git a/tools/eslint/lib/rules/no-warning-comments.js b/tools/eslint/lib/rules/no-warning-comments.js index 511bd9bb48d6ed..bda43086865a1c 100644 --- a/tools/eslint/lib/rules/no-warning-comments.js +++ b/tools/eslint/lib/rules/no-warning-comments.js @@ -54,7 +54,7 @@ module.exports = { * @returns {RegExp} The term converted to a RegExp */ function convertToRegExp(term) { - const escaped = term.replace(/[-\/\\$\^*+?.()|\[\]{}]/g, "\\$&"); + const escaped = term.replace(/[-/\\$^*+?.()|[\]{}]/g, "\\$&"); let prefix; /* @@ -95,7 +95,7 @@ module.exports = { function commentContainsWarningTerm(comment) { const matches = []; - warningRegExps.forEach(function(regex, index) { + warningRegExps.forEach((regex, index) => { if (regex.test(comment)) { matches.push(warningTerms[index]); } @@ -116,7 +116,7 @@ module.exports = { const matches = commentContainsWarningTerm(node.value); - matches.forEach(function(matchedTerm) { + matches.forEach(matchedTerm => { context.report({ node, message: "Unexpected '{{matchedTerm}}' comment.", diff --git a/tools/eslint/lib/rules/no-with.js b/tools/eslint/lib/rules/no-with.js index 6d5bfd8e61605e..be9e3463606404 100644 --- a/tools/eslint/lib/rules/no-with.js +++ b/tools/eslint/lib/rules/no-with.js @@ -24,7 +24,7 @@ module.exports = { return { WithStatement(node) { - context.report(node, "Unexpected use of 'with' statement."); + context.report({ node, message: "Unexpected use of 'with' statement." }); } }; diff --git a/tools/eslint/lib/rules/object-curly-newline.js b/tools/eslint/lib/rules/object-curly-newline.js index 3ba786a6f1e2c2..88fc79463cb6ae 100644 --- a/tools/eslint/lib/rules/object-curly-newline.js +++ b/tools/eslint/lib/rules/object-curly-newline.js @@ -61,7 +61,7 @@ function normalizeOptionValue(value) { multiline = true; } - return {multiline, minProperties}; + return { multiline, minProperties }; } /** @@ -80,7 +80,7 @@ function normalizeOptions(options) { const value = normalizeOptionValue(options); - return {ObjectExpression: value, ObjectPattern: value}; + return { ObjectExpression: value, ObjectPattern: value }; } //------------------------------------------------------------------------------ diff --git a/tools/eslint/lib/rules/object-property-newline.js b/tools/eslint/lib/rules/object-property-newline.js index f06cb41843e534..a64420be93a910 100644 --- a/tools/eslint/lib/rules/object-property-newline.js +++ b/tools/eslint/lib/rules/object-property-newline.js @@ -27,7 +27,9 @@ module.exports = { }, additionalProperties: false } - ] + ], + + fixable: "whitespace" }, create(context) { @@ -61,7 +63,18 @@ module.exports = { context.report({ node, loc: firstTokenOfCurrentProperty.loc.start, - message: errorMessage + message: errorMessage, + fix(fixer) { + const comma = sourceCode.getTokenBefore(firstTokenOfCurrentProperty); + const rangeAfterComma = [comma.range[1], firstTokenOfCurrentProperty.range[0]]; + + // Don't perform a fix if there are any comments between the comma and the next property. + if (sourceCode.text.slice(rangeAfterComma[0], rangeAfterComma[1]).trim()) { + return null; + } + + return fixer.replaceTextRange(rangeAfterComma, "\n"); + } }); } } diff --git a/tools/eslint/lib/rules/object-shorthand.js b/tools/eslint/lib/rules/object-shorthand.js index 3ef782461a4018..43997f90692de5 100644 --- a/tools/eslint/lib/rules/object-shorthand.js +++ b/tools/eslint/lib/rules/object-shorthand.js @@ -77,6 +77,9 @@ module.exports = { }, avoidQuotes: { type: "boolean" + }, + avoidExplicitReturnArrows: { + type: "boolean" } }, additionalProperties: false @@ -100,6 +103,8 @@ module.exports = { const PARAMS = context.options[1] || {}; const IGNORE_CONSTRUCTORS = PARAMS.ignoreConstructors; const AVOID_QUOTES = PARAMS.avoidQuotes; + const AVOID_EXPLICIT_RETURN_ARROWS = !!PARAMS.avoidExplicitReturnArrows; + const sourceCode = context.getSourceCode(); //-------------------------------------------------------------------------- // Helpers @@ -188,7 +193,7 @@ module.exports = { // We have at least 1 shorthand property if (shorthandProperties.length > 0) { - context.report(node, "Unexpected mix of shorthand and non-shorthand properties."); + context.report({ node, message: "Unexpected mix of shorthand and non-shorthand properties." }); } else if (checkRedundancy) { // If all properties of the object contain a method or value with a name matching it's key, @@ -196,18 +201,143 @@ module.exports = { const canAlwaysUseShorthand = properties.every(isRedundant); if (canAlwaysUseShorthand) { - context.report(node, "Expected shorthand for all properties."); + context.report({ node, message: "Expected shorthand for all properties." }); } } } } } + /** + * Fixes a FunctionExpression node by making it into a shorthand property. + * @param {SourceCodeFixer} fixer The fixer object + * @param {ASTNode} node A `Property` node that has a `FunctionExpression` or `ArrowFunctionExpression` as its value + * @returns {Object} A fix for this node + */ + function makeFunctionShorthand(fixer, node) { + const firstKeyToken = node.computed ? sourceCode.getTokens(node).find(token => token.value === "[") : sourceCode.getFirstToken(node.key); + const lastKeyToken = node.computed ? sourceCode.getTokensBetween(node.key, node.value).find(token => token.value === "]") : sourceCode.getLastToken(node.key); + const keyText = sourceCode.text.slice(firstKeyToken.range[0], lastKeyToken.range[1]); + let keyPrefix = ""; + + if (node.value.generator) { + keyPrefix = "*"; + } else if (node.value.async) { + keyPrefix = "async "; + } + + if (node.value.type === "FunctionExpression") { + const functionToken = sourceCode.getTokens(node.value).find(token => token.type === "Keyword" && token.value === "function"); + const tokenBeforeParams = node.value.generator ? sourceCode.getTokenAfter(functionToken) : functionToken; + + return fixer.replaceTextRange([firstKeyToken.range[0], tokenBeforeParams.range[1]], keyPrefix + keyText); + } else { + const arrowToken = sourceCode.getTokens(node.value).find(token => token.value === "=>"); + const tokenBeforeArrow = sourceCode.getTokenBefore(arrowToken); + const hasParensAroundParameters = tokenBeforeArrow.type === "Punctuator" && tokenBeforeArrow.value === ")"; + const oldParamText = sourceCode.text.slice(sourceCode.getFirstToken(node.value, node.value.async ? 1 : 0).range[0], tokenBeforeArrow.range[1]); + const newParamText = hasParensAroundParameters ? oldParamText : `(${oldParamText})`; + + return fixer.replaceTextRange([firstKeyToken.range[0], arrowToken.range[1]], keyPrefix + keyText + newParamText); + } + } + + /** + * Fixes a FunctionExpression node by making it into a longform property. + * @param {SourceCodeFixer} fixer The fixer object + * @param {ASTNode} node A `Property` node that has a `FunctionExpression` as its value + * @returns {Object} A fix for this node + */ + function makeFunctionLongform(fixer, node) { + const firstKeyToken = node.computed ? sourceCode.getTokens(node).find(token => token.value === "[") : sourceCode.getFirstToken(node.key); + const lastKeyToken = node.computed ? sourceCode.getTokensBetween(node.key, node.value).find(token => token.value === "]") : sourceCode.getLastToken(node.key); + const keyText = sourceCode.text.slice(firstKeyToken.range[0], lastKeyToken.range[1]); + let functionHeader = "function"; + + if (node.value.generator) { + functionHeader = "function*"; + } else if (node.value.async) { + functionHeader = "async function"; + } + + return fixer.replaceTextRange([node.range[0], lastKeyToken.range[1]], `${keyText}: ${functionHeader}`); + } + + /* + * To determine whether a given arrow function has a lexical identifier (`this`, `arguments`, `super`, or `new.target`), + * create a stack of functions that define these identifiers (i.e. all functions except arrow functions) as the AST is + * traversed. Whenever a new function is encountered, create a new entry on the stack (corresponding to a different lexical + * scope of `this`), and whenever a function is exited, pop that entry off the stack. When an arrow function is entered, + * keep a reference to it on the current stack entry, and remove that reference when the arrow function is exited. + * When a lexical identifier is encountered, mark all the arrow functions on the current stack entry by adding them + * to an `arrowsWithLexicalIdentifiers` set. Any arrow function in that set will not be reported by this rule, + * because converting it into a method would change the value of one of the lexical identifiers. + */ + const lexicalScopeStack = []; + const arrowsWithLexicalIdentifiers = new WeakSet(); + const argumentsIdentifiers = new WeakSet(); + + /** + * Enters a function. This creates a new lexical identifier scope, so a new Set of arrow functions is pushed onto the stack. + * Also, this marks all `arguments` identifiers so that they can be detected later. + * @returns {void} + */ + function enterFunction() { + lexicalScopeStack.unshift(new Set()); + context.getScope().variables.filter(variable => variable.name === "arguments").forEach(variable => { + variable.references.map(ref => ref.identifier).forEach(identifier => argumentsIdentifiers.add(identifier)); + }); + } + + /** + * Exits a function. This pops the current set of arrow functions off the lexical scope stack. + * @returns {void} + */ + function exitFunction() { + lexicalScopeStack.shift(); + } + + /** + * Marks the current function as having a lexical keyword. This implies that all arrow functions + * in the current lexical scope contain a reference to this lexical keyword. + * @returns {void} + */ + function reportLexicalIdentifier() { + lexicalScopeStack[0].forEach(arrowFunction => arrowsWithLexicalIdentifiers.add(arrowFunction)); + } + //-------------------------------------------------------------------------- // Public //-------------------------------------------------------------------------- return { + Program: enterFunction, + FunctionDeclaration: enterFunction, + FunctionExpression: enterFunction, + "Program:exit": exitFunction, + "FunctionDeclaration:exit": exitFunction, + "FunctionExpression:exit": exitFunction, + + ArrowFunctionExpression(node) { + lexicalScopeStack[0].add(node); + }, + "ArrowFunctionExpression:exit"(node) { + lexicalScopeStack[0].delete(node); + }, + + ThisExpression: reportLexicalIdentifier, + Super: reportLexicalIdentifier, + MetaProperty(node) { + if (node.meta.name === "new" && node.property.name === "target") { + reportLexicalIdentifier(); + } + }, + Identifier(node) { + if (argumentsIdentifiers.has(node)) { + reportLexicalIdentifier(); + } + }, + ObjectExpression(node) { if (APPLY_CONSISTENT) { checkConsistency(node, false); @@ -216,7 +346,7 @@ module.exports = { } }, - Property(node) { + "Property:exit"(node) { const isConciseProperty = node.method || node.shorthand; // Ignore destructuring assignment @@ -230,59 +360,31 @@ module.exports = { } // only computed methods can fail the following checks - if (node.computed && node.value.type !== "FunctionExpression") { + if (node.computed && node.value.type !== "FunctionExpression" && node.value.type !== "ArrowFunctionExpression") { return; } //-------------------------------------------------------------- // Checks for property/method shorthand. if (isConciseProperty) { + if (node.method && (APPLY_NEVER || AVOID_QUOTES && isStringLiteral(node.key))) { - // if we're "never" and concise we should warn now - if (APPLY_NEVER) { - const type = node.method ? "method" : "property"; - + // { x() {} } should be written as { x: function() {} } context.report({ node, - message: "Expected longform {{type}} syntax.", - data: { - type - }, - fix(fixer) { - if (node.method) { - if (node.value.generator) { - return fixer.replaceTextRange([node.range[0], node.key.range[1]], `${node.key.name}: function*`); - } - - return fixer.insertTextAfter(node.key, ": function"); - } - - return fixer.insertTextAfter(node.key, `: ${node.key.name}`); - } + message: `Expected longform method syntax${APPLY_NEVER ? "" : " for string literal keys"}.`, + fix: fixer => makeFunctionLongform(fixer, node) }); - } + } else if (APPLY_NEVER) { - // {'xyz'() {}} should be written as {'xyz': function() {}} - if (AVOID_QUOTES && isStringLiteral(node.key)) { + // { x } should be written as { x: x } context.report({ node, - message: "Expected longform method syntax for string literal keys.", - fix(fixer) { - if (node.computed) { - return fixer.insertTextAfterRange([node.key.range[0], node.key.range[1] + 1], ": function"); - } - - return fixer.insertTextAfter(node.key, ": function"); - } + message: "Expected longform property syntax.", + fix: fixer => fixer.insertTextAfter(node.key, `: ${node.key.name}`) }); } - - return; - } - - //-------------------------------------------------------------- - // Checks for longform properties. - if (node.value.type === "FunctionExpression" && !node.value.id && APPLY_TO_METHODS) { + } else if (APPLY_TO_METHODS && !node.value.id && (node.value.type === "FunctionExpression" || node.value.type === "ArrowFunctionExpression")) { if (IGNORE_CONSTRUCTORS && isConstructor(node.key.name)) { return; } @@ -291,39 +393,18 @@ module.exports = { } // {[x]: function(){}} should be written as {[x]() {}} - if (node.computed) { + if (node.value.type === "FunctionExpression" || + node.value.type === "ArrowFunctionExpression" && + node.value.body.type === "BlockStatement" && + AVOID_EXPLICIT_RETURN_ARROWS && + !arrowsWithLexicalIdentifiers.has(node.value) + ) { context.report({ node, message: "Expected method shorthand.", - fix(fixer) { - if (node.value.generator) { - return fixer.replaceTextRange( - [node.key.range[0], node.value.range[0] + "function*".length], - `*[${node.key.name}]` - ); - } - - return fixer.removeRange([node.key.range[1] + 1, node.value.range[0] + "function".length]); - } + fix: fixer => makeFunctionShorthand(fixer, node) }); - return; } - - // {x: function(){}} should be written as {x() {}} - context.report({ - node, - message: "Expected method shorthand.", - fix(fixer) { - if (node.value.generator) { - return fixer.replaceTextRange( - [node.key.range[0], node.value.range[0] + "function*".length], - `*${node.key.name}` - ); - } - - return fixer.removeRange([node.key.range[1], node.value.range[0] + "function".length]); - } - }); } else if (node.value.type === "Identifier" && node.key.name === node.value.name && APPLY_TO_PROPS) { // {x: x} should be written as {x} diff --git a/tools/eslint/lib/rules/one-var-declaration-per-line.js b/tools/eslint/lib/rules/one-var-declaration-per-line.js index eb0d5c3bf1ad74..61b505c82d5d71 100644 --- a/tools/eslint/lib/rules/one-var-declaration-per-line.js +++ b/tools/eslint/lib/rules/one-var-declaration-per-line.js @@ -59,7 +59,7 @@ module.exports = { const declarations = node.declarations; let prev; - declarations.forEach(function(current) { + declarations.forEach(current => { if (prev && prev.loc.end.line === current.loc.start.line) { if (always || prev.init || current.init) { context.report({ diff --git a/tools/eslint/lib/rules/one-var.js b/tools/eslint/lib/rules/one-var.js index 27166559714065..9e40d4ea6f26c1 100644 --- a/tools/eslint/lib/rules/one-var.js +++ b/tools/eslint/lib/rules/one-var.js @@ -66,18 +66,18 @@ module.exports = { }; if (typeof mode === "string") { // simple options configuration with just a string - options.var = { uninitialized: mode, initialized: mode}; - options.let = { uninitialized: mode, initialized: mode}; - options.const = { uninitialized: mode, initialized: mode}; + options.var = { uninitialized: mode, initialized: mode }; + options.let = { uninitialized: mode, initialized: mode }; + options.const = { uninitialized: mode, initialized: mode }; } else if (typeof mode === "object") { // options configuration is an object if (mode.hasOwnProperty("var") && typeof mode.var === "string") { - options.var = { uninitialized: mode.var, initialized: mode.var}; + options.var = { uninitialized: mode.var, initialized: mode.var }; } if (mode.hasOwnProperty("let") && typeof mode.let === "string") { - options.let = { uninitialized: mode.let, initialized: mode.let}; + options.let = { uninitialized: mode.let, initialized: mode.let }; } if (mode.hasOwnProperty("const") && typeof mode.const === "string") { - options.const = { uninitialized: mode.const, initialized: mode.const}; + options.const = { uninitialized: mode.const, initialized: mode.const }; } if (mode.hasOwnProperty("uninitialized")) { if (!options.var) { @@ -123,8 +123,8 @@ module.exports = { */ function startBlock() { blockStack.push({ - let: {initialized: false, uninitialized: false}, - const: {initialized: false, uninitialized: false} + let: { initialized: false, uninitialized: false }, + const: { initialized: false, uninitialized: false } }); } @@ -134,7 +134,7 @@ module.exports = { * @private */ function startFunction() { - functionStack.push({initialized: false, uninitialized: false}); + functionStack.push({ initialized: false, uninitialized: false }); startBlock(); } diff --git a/tools/eslint/lib/rules/operator-assignment.js b/tools/eslint/lib/rules/operator-assignment.js index 5e1dd97b996bc7..e003478c7bc427 100644 --- a/tools/eslint/lib/rules/operator-assignment.js +++ b/tools/eslint/lib/rules/operator-assignment.js @@ -70,6 +70,17 @@ function same(a, b) { } } +/** +* Determines if the left side of a node can be safely fixed (i.e. if it activates the same getters/setters and) +* toString calls regardless of whether assignment shorthand is used) +* @param {ASTNode} node The node on the left side of the expression +* @returns {boolean} `true` if the node can be fixed +*/ +function canBeFixed(node) { + return node.type === "Identifier" || + node.type === "MemberExpression" && node.object.type === "Identifier" && (!node.computed || node.property.type === "Literal"); +} + module.exports = { meta: { docs: { @@ -82,11 +93,24 @@ module.exports = { { enum: ["always", "never"] } - ] + ], + + fixable: "code" }, create(context) { + const sourceCode = context.getSourceCode(); + + /** + * Returns the operator token of an AssignmentExpression or BinaryExpression + * @param {ASTNode} node An AssignmentExpression or BinaryExpression node + * @returns {Token} The operator token in the node + */ + function getOperatorToken(node) { + return sourceCode.getTokensBetween(node.left, node.right).find(token => token.value === node.operator); + } + /** * Ensures that an assignment uses the shorthand form where possible. * @param {ASTNode} node An AssignmentExpression node. @@ -101,13 +125,34 @@ module.exports = { const expr = node.right; const operator = expr.operator; - if (isCommutativeOperatorWithShorthand(operator)) { - if (same(left, expr.left) || same(left, expr.right)) { - context.report(node, "Assignment can be replaced with operator assignment."); - } - } else if (isNonCommutativeOperatorWithShorthand(operator)) { + if (isCommutativeOperatorWithShorthand(operator) || isNonCommutativeOperatorWithShorthand(operator)) { if (same(left, expr.left)) { - context.report(node, "Assignment can be replaced with operator assignment."); + context.report({ + node, + message: "Assignment can be replaced with operator assignment.", + fix(fixer) { + if (canBeFixed(left)) { + const equalsToken = getOperatorToken(node); + const operatorToken = getOperatorToken(expr); + const leftText = sourceCode.getText().slice(node.range[0], equalsToken.range[0]); + const rightText = sourceCode.getText().slice(operatorToken.range[1], node.range[1]); + + return fixer.replaceText(node, `${leftText}${expr.operator}=${rightText}`); + } + return null; + } + }); + } else if (same(left, expr.right) && isCommutativeOperatorWithShorthand(operator)) { + + /* + * This case can't be fixed safely. + * If `a` and `b` both have custom valueOf() behavior, then fixing `a = b * a` to `a *= b` would + * change the execution order of the valueOf() functions. + */ + context.report({ + node, + message: "Assignment can be replaced with operator assignment." + }); } } } @@ -119,7 +164,20 @@ module.exports = { */ function prohibit(node) { if (node.operator !== "=") { - context.report(node, "Unexpected operator assignment shorthand."); + context.report({ + node, + message: "Unexpected operator assignment shorthand.", + fix(fixer) { + if (canBeFixed(node.left)) { + const operatorToken = getOperatorToken(node); + const leftText = sourceCode.getText().slice(node.range[0], operatorToken.range[0]); + const rightText = sourceCode.getText().slice(operatorToken.range[1], node.range[1]); + + return fixer.replaceText(node, `${leftText}= ${leftText}${node.operator.slice(0, -1)}${rightText}`); + } + return null; + } + }); } } diff --git a/tools/eslint/lib/rules/operator-linebreak.js b/tools/eslint/lib/rules/operator-linebreak.js index ce222526e1d410..c8f2b2818e23b2 100644 --- a/tools/eslint/lib/rules/operator-linebreak.js +++ b/tools/eslint/lib/rules/operator-linebreak.js @@ -11,6 +11,8 @@ const astUtils = require("../ast-utils"); // Rule Definition //------------------------------------------------------------------------------ +const LINEBREAK_REGEX = /\r\n|\r|\n|\u2028|\u2029/g; + module.exports = { meta: { docs: { @@ -38,7 +40,9 @@ module.exports = { }, additionalProperties: false } - ] + ], + + fixable: "code" }, create(context) { @@ -62,6 +66,61 @@ module.exports = { // Helpers //-------------------------------------------------------------------------- + /** + * Gets a fixer function to fix rule issues + * @param {Token} operatorToken The operator token of an expression + * @param {string} desiredStyle The style for the rule. One of 'before', 'after', 'none' + * @returns {Function} A fixer function + */ + function getFixer(operatorToken, desiredStyle) { + return fixer => { + const tokenBefore = sourceCode.getTokenBefore(operatorToken); + const tokenAfter = sourceCode.getTokenAfter(operatorToken); + const textBefore = sourceCode.text.slice(tokenBefore.range[1], operatorToken.range[0]); + const textAfter = sourceCode.text.slice(operatorToken.range[1], tokenAfter.range[0]); + const hasLinebreakBefore = !astUtils.isTokenOnSameLine(tokenBefore, operatorToken); + const hasLinebreakAfter = !astUtils.isTokenOnSameLine(operatorToken, tokenAfter); + let newTextBefore, newTextAfter; + + if (hasLinebreakBefore !== hasLinebreakAfter && desiredStyle !== "none") { + + // If there is a comment before and after the operator, don't do a fix. + if (sourceCode.getTokenOrCommentBefore(operatorToken) !== tokenBefore && sourceCode.getTokenOrCommentAfter(operatorToken) !== tokenAfter) { + return null; + } + + /* + * If there is only one linebreak and it's on the wrong side of the operator, swap the text before and after the operator. + * foo && + * bar + * would get fixed to + * foo + * && bar + */ + newTextBefore = textAfter; + newTextAfter = textBefore; + } else { + + // Otherwise, if no linebreak is desired and no comments interfere, replace the linebreaks with empty strings. + newTextBefore = desiredStyle === "before" || textBefore.trim() ? textBefore : textBefore.replace(LINEBREAK_REGEX, ""); + newTextAfter = desiredStyle === "after" || textAfter.trim() ? textAfter : textAfter.replace(LINEBREAK_REGEX, ""); + + // If there was no change (due to interfering comments), don't output a fix. + if (newTextBefore === textBefore && newTextAfter === textAfter) { + return null; + } + } + + if (newTextAfter === "" && tokenAfter.type === "Punctuator" && "+-".includes(operatorToken.value) && tokenAfter.value === operatorToken.value) { + + // To avoid accidentally creating a ++ or -- operator, insert a space if the operator is a +/- and the following token is a unary +/-. + newTextAfter += " "; + } + + return fixer.replaceTextRange([tokenBefore.range[1], tokenAfter.range[0]], newTextBefore + operatorToken.value + newTextAfter); + }; + } + /** * Checks the operator placement * @param {ASTNode} node The node to check @@ -87,12 +146,13 @@ module.exports = { const operator = operatorToken.value; const operatorStyleOverride = styleOverrides[operator]; const style = operatorStyleOverride || globalStyle; + const fix = getFixer(operatorToken, style); // if single line if (astUtils.isTokenOnSameLine(leftToken, operatorToken) && astUtils.isTokenOnSameLine(operatorToken, rightToken)) { - return; + // do nothing. } else if (operatorStyleOverride !== "ignore" && !astUtils.isTokenOnSameLine(leftToken, operatorToken) && !astUtils.isTokenOnSameLine(operatorToken, rightToken)) { @@ -107,7 +167,8 @@ module.exports = { message: "Bad line breaking before and after '{{operator}}'.", data: { operator - } + }, + fix }); } else if (style === "before" && astUtils.isTokenOnSameLine(leftToken, operatorToken)) { @@ -121,7 +182,8 @@ module.exports = { message: "'{{operator}}' should be placed at the beginning of the line.", data: { operator - } + }, + fix }); } else if (style === "after" && astUtils.isTokenOnSameLine(operatorToken, rightToken)) { @@ -135,7 +197,8 @@ module.exports = { message: "'{{operator}}' should be placed at the end of the line.", data: { operator - } + }, + fix }); } else if (style === "none") { @@ -149,7 +212,8 @@ module.exports = { message: "There should be no line break before or after '{{operator}}'.", data: { operator - } + }, + fix }); } diff --git a/tools/eslint/lib/rules/padded-blocks.js b/tools/eslint/lib/rules/padded-blocks.js index a24d421b0f4f23..2b4da39b360214 100644 --- a/tools/eslint/lib/rules/padded-blocks.js +++ b/tools/eslint/lib/rules/padded-blocks.js @@ -173,7 +173,7 @@ module.exports = { if (!blockHasBottomPadding) { context.report({ node, - loc: {line: closeBrace.loc.end.line, column: closeBrace.loc.end.column - 1 }, + loc: { line: closeBrace.loc.end.line, column: closeBrace.loc.end.column - 1 }, fix(fixer) { return fixer.insertTextBefore(closeBrace, "\n"); }, @@ -199,7 +199,7 @@ module.exports = { context.report({ node, - loc: {line: closeBrace.loc.end.line, column: closeBrace.loc.end.column - 1 }, + loc: { line: closeBrace.loc.end.line, column: closeBrace.loc.end.column - 1 }, message: NEVER_MESSAGE, fix(fixer) { return fixer.replaceTextRange([previousToken.end, closeBrace.start - closeBrace.loc.start.column], "\n"); diff --git a/tools/eslint/lib/rules/prefer-arrow-callback.js b/tools/eslint/lib/rules/prefer-arrow-callback.js index 034112093bd405..ee385042f1309e 100644 --- a/tools/eslint/lib/rules/prefer-arrow-callback.js +++ b/tools/eslint/lib/rules/prefer-arrow-callback.js @@ -63,7 +63,7 @@ function getVariableOfArguments(scope) { * {boolean} retv.isLexicalThis - `true` if the node is with `.bind(this)`. */ function getCallbackInfo(node) { - const retv = {isCallback: false, isLexicalThis: false}; + const retv = { isCallback: false, isLexicalThis: false }; let parent = node.parent; while (node) { @@ -176,7 +176,7 @@ module.exports = { * @returns {void} */ function enterScope() { - stack.push({this: false, super: false, meta: false}); + stack.push({ this: false, super: false, meta: false }); } /** diff --git a/tools/eslint/lib/rules/prefer-const.js b/tools/eslint/lib/rules/prefer-const.js index 5255f2745c9384..07d8da82a105c4 100644 --- a/tools/eslint/lib/rules/prefer-const.js +++ b/tools/eslint/lib/rules/prefer-const.js @@ -5,12 +5,6 @@ "use strict"; -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const lodash = require("lodash"); - //------------------------------------------------------------------------------ // Helpers //------------------------------------------------------------------------------ @@ -91,6 +85,17 @@ function getIdentifierIfShouldBeConst(variable, ignoreReadBeforeAssign) { return null; } + /* + * Due to a bug in acorn, code such as `let foo = 1; let foo = 2;` will not throw a syntax error. As a sanity + * check, make sure that the variable only has one declaration. After the parsing bug is fixed, this check + * will no longer be necessary, because variables declared with `let` or `const` should always have exactly one + * declaration. + * https://github.com/ternjs/acorn/issues/487 + */ + if (variable.defs.length > 1) { + return null; + } + // Finds the unique WriteReference. let writer = null; let isReadBeforeInit = false; @@ -244,8 +249,8 @@ module.exports = { { type: "object", properties: { - destructuring: {enum: ["any", "all"]}, - ignoreReadBeforeAssign: {type: "boolean"} + destructuring: { enum: ["any", "all"] }, + ignoreReadBeforeAssign: { type: "boolean" } }, additionalProperties: false } @@ -254,80 +259,10 @@ module.exports = { create(context) { const options = context.options[0] || {}; + const sourceCode = context.getSourceCode(); const checkingMixedDestructuring = options.destructuring !== "all"; const ignoreReadBeforeAssign = options.ignoreReadBeforeAssign === true; - let variables = null; - - /** - * Reports a given Identifier node. - * - * @param {ASTNode} node - An Identifier node to report. - * @returns {void} - */ - function report(node) { - const reportArgs = { - node, - message: "'{{name}}' is never reassigned. Use 'const' instead.", - data: node - }, - varDeclParent = findUp(node, "VariableDeclaration", function(parentNode) { - return lodash.endsWith(parentNode.type, "Statement"); - }), - isNormalVarDecl = (node.parent.parent.parent.type === "ForInStatement" || - node.parent.parent.parent.type === "ForOfStatement" || - node.parent.init), - - isDestructuringVarDecl = - - // {let {a} = obj} should be written as {const {a} = obj} - (node.parent.parent.type === "ObjectPattern" && - - // If options.destucturing is "all", then this warning will not occur unless - // every assignment in the destructuring should be const. In that case, it's safe - // to apply the fix. Otherwise, it's safe to apply the fix if there's only one - // assignment occurring. If there is more than one assignment and options.destructuring - // is not "all", then it's not clear how the developer would want to resolve the issue, - // so we should not attempt to do it programmatically. - (options.destructuring === "all" || node.parent.parent.properties.length === 1)) || - - // {let [a] = [1]} should be written as {const [a] = [1]} - (node.parent.type === "ArrayPattern" && - - // See note above about fixing multiple warnings at once. - (options.destructuring === "all" || node.parent.elements.length === 1)); - - if (varDeclParent && - (isNormalVarDecl || isDestructuringVarDecl) && - - // If there are multiple variable declarations, like {let a = 1, b = 2}, then - // do not attempt to fix if one of the declarations should be `const`. It's - // too hard to know how the developer would want to automatically resolve the issue. - varDeclParent.declarations.length === 1) { - - reportArgs.fix = function(fixer) { - return fixer.replaceTextRange( - [varDeclParent.start, varDeclParent.start + "let".length], - "const" - ); - }; - } - - context.report(reportArgs); - } - - /** - * Reports a given variable if the variable should be declared as const. - * - * @param {escope.Variable} variable - A variable to report. - * @returns {void} - */ - function checkVariable(variable) { - const node = getIdentifierIfShouldBeConst(variable, ignoreReadBeforeAssign); - - if (node) { - report(node); - } - } + const variables = []; /** * Reports given identifier nodes if all of the nodes should be declared @@ -344,25 +279,39 @@ module.exports = { * @returns {void} */ function checkGroup(nodes) { - if (nodes.every(Boolean)) { - nodes.forEach(report); + const nodesToReport = nodes.filter(Boolean); + + if (nodes.length && (checkingMixedDestructuring || nodesToReport.length === nodes.length)) { + const varDeclParent = findUp(nodes[0], "VariableDeclaration", parentNode => parentNode.type.endsWith("Statement")); + const shouldFix = varDeclParent && + + // If there are multiple variable declarations, like {let a = 1, b = 2}, then + // do not attempt to fix if one of the declarations should be `const`. It's + // too hard to know how the developer would want to automatically resolve the issue. + varDeclParent.declarations.length === 1 && + + // Don't do a fix unless the variable is initialized (or it's in a for-in or for-of loop) + (varDeclParent.parent.type === "ForInStatement" || varDeclParent.parent.type === "ForOfStatement" || varDeclParent.declarations[0].init) && + + // If options.destucturing is "all", then this warning will not occur unless + // every assignment in the destructuring should be const. In that case, it's safe + // to apply the fix. + nodesToReport.length === nodes.length; + + nodesToReport.forEach(node => { + context.report({ + node, + message: "'{{name}}' is never reassigned. Use 'const' instead.", + data: node, + fix: shouldFix ? fixer => fixer.replaceText(sourceCode.getFirstToken(varDeclParent), "const") : null + }); + }); } } return { - Program() { - variables = []; - }, - "Program:exit"() { - if (checkingMixedDestructuring) { - variables.forEach(checkVariable); - } else { - groupByDestructuring(variables, ignoreReadBeforeAssign) - .forEach(checkGroup); - } - - variables = null; + groupByDestructuring(variables, ignoreReadBeforeAssign).forEach(checkGroup); }, VariableDeclaration(node) { diff --git a/tools/eslint/lib/rules/prefer-destructuring.js b/tools/eslint/lib/rules/prefer-destructuring.js new file mode 100644 index 00000000000000..c3fbcaa6310fc8 --- /dev/null +++ b/tools/eslint/lib/rules/prefer-destructuring.js @@ -0,0 +1,173 @@ +/** + * @fileoverview Prefer destructuring from arrays and objects + * @author Alex LaFroscia + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = { + meta: { + docs: { + description: "require destructuring from arrays and/or objects", + category: "ECMAScript 6", + recommended: false + }, + + schema: [ + { + type: "object", + properties: { + array: { + type: "boolean" + }, + object: { + type: "boolean" + } + }, + additionalProperties: false + }, + { + type: "object", + properties: { + enforceForRenamedProperties: { + type: "boolean" + } + }, + additionalProperties: false + } + ] + }, + create(context) { + + let checkArrays = true; + let checkObjects = true; + let enforceForRenamedProperties = false; + const enabledTypes = context.options[0]; + const additionalOptions = context.options[1]; + + if (enabledTypes) { + if (typeof enabledTypes.array !== "undefined") { + checkArrays = enabledTypes.array; + } + + if (typeof enabledTypes.object !== "undefined") { + checkObjects = enabledTypes.object; + } + } + + if (additionalOptions) { + if (typeof additionalOptions.enforceForRenamedProperties !== "undefined") { + enforceForRenamedProperties = additionalOptions.enforceForRenamedProperties; + } + } + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Determines if the given node node is accessing an array index + * + * This is used to differentiate array index access from object property + * access. + * + * @param {ASTNode} node the node to evaluate + * @returns {boolean} whether or not the node is an integer + */ + function isArrayIndexAccess(node) { + return Number.isInteger(node.property.value); + } + + /** + * Report that the given node should use destructuring + * + * @param {ASTNode} reportNode the node to report + * @param {string} type the type of destructuring that should have been done + * @returns {void} + */ + function report(reportNode, type) { + context.report({ node: reportNode, message: `Use ${type} destructuring` }); + } + + /** + * Check that the `prefer-destructuring` rules are followed based on the + * given left- and right-hand side of the assignment. + * + * Pulled out into a separate method so that VariableDeclarators and + * AssignmentExpressions can share the same verification logic. + * + * @param {ASTNode} leftNode the left-hand side of the assignment + * @param {ASTNode} rightNode the right-hand side of the assignment + * @param {ASTNode} reportNode the node to report the error on + * @returns {void} + */ + function performCheck(leftNode, rightNode, reportNode) { + if (rightNode.type !== "MemberExpression") { + return; + } + + if (checkArrays && isArrayIndexAccess(rightNode)) { + report(reportNode, "array"); + return; + } + + if (checkObjects && enforceForRenamedProperties) { + report(reportNode, "object"); + return; + } + + if (checkObjects) { + const property = rightNode.property; + + if ((property.type === "Literal" && leftNode.name === property.value) || + (property.type === "Identifier" && leftNode.name === property.name)) { + report(reportNode, "object"); + } + } + } + + /** + * Check if a given variable declarator is coming from an property access + * that should be using destructuring instead + * + * @param {ASTNode} node the variable declarator to check + * @returns {void} + */ + function checkVariableDeclarator(node) { + + // Skip if variable is declared without assignment + if (!node.init) { + return; + } + + // We only care about member expressions past this point + if (node.init.type !== "MemberExpression") { + return; + } + + performCheck(node.id, node.init, node); + } + + /** + * Run the `prefer-destructuring` check on an AssignmentExpression + * + * @param {ASTNode} node the AssignmentExpression node + * @returns {void} + */ + function checkAssigmentExpression(node) { + performCheck(node.left, node.right, node); + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + VariableDeclarator: checkVariableDeclarator, + AssignmentExpression: checkAssigmentExpression + }; + } +}; diff --git a/tools/eslint/lib/rules/prefer-reflect.js b/tools/eslint/lib/rules/prefer-reflect.js index 64db836d04dd89..49e20989ecb00d 100644 --- a/tools/eslint/lib/rules/prefer-reflect.js +++ b/tools/eslint/lib/rules/prefer-reflect.js @@ -1,6 +1,7 @@ /** * @fileoverview Rule to suggest using "Reflect" api over Function/Object methods * @author Keith Cirkel + * @deprecated in ESLint v3.9.0 */ "use strict"; @@ -13,9 +14,12 @@ module.exports = { docs: { description: "require `Reflect` methods where applicable", category: "ECMAScript 6", - recommended: false + recommended: false, + replacedBy: [] }, + deprecated: true, + schema: [ { type: "object", @@ -79,10 +83,10 @@ module.exports = { * @returns {void} */ function report(node, existing, substitute) { - context.report(node, "Avoid using {{existing}}, instead use {{substitute}}.", { + context.report({ node, message: "Avoid using {{existing}}, instead use {{substitute}}.", data: { existing, substitute - }); + } }); } return { diff --git a/tools/eslint/lib/rules/quote-props.js b/tools/eslint/lib/rules/quote-props.js index 2129ce6aa99b87..1dcdd461b598fc 100644 --- a/tools/eslint/lib/rules/quote-props.js +++ b/tools/eslint/lib/rules/quote-props.js @@ -162,7 +162,7 @@ module.exports = { context.report({ node, message: MESSAGE_UNNECESSARY, - data: {property: key.value}, + data: { property: key.value }, fix: fixer => fixer.replaceText(key, getUnquotedKey(key)) }); } @@ -170,14 +170,14 @@ module.exports = { context.report({ node, message: MESSAGE_RESERVED, - data: {property: key.name}, + data: { property: key.name }, fix: fixer => fixer.replaceText(key, getQuotedKey(key)) }); } else if (NUMBERS && key.type === "Literal" && typeof key.value === "number") { context.report({ node, message: MESSAGE_NUMERIC, - data: {property: key.value}, + data: { property: key.value }, fix: fixer => fixer.replaceText(key, getQuotedKey(key)) }); } @@ -195,7 +195,7 @@ module.exports = { context.report({ node, message: MESSAGE_UNQUOTED, - data: {property: key.name || key.value}, + data: { property: key.name || key.value }, fix: fixer => fixer.replaceText(key, getQuotedKey(key)) }); } @@ -213,7 +213,7 @@ module.exports = { let keywordKeyName = null, necessaryQuotes = false; - node.properties.forEach(function(property) { + node.properties.forEach(property => { const key = property.key; let tokens; @@ -257,7 +257,7 @@ module.exports = { context.report({ node: property, message: "Properties should be quoted as '{{property}}' is a reserved word.", - data: {property: keywordKeyName}, + data: { property: keywordKeyName }, fix: fixer => fixer.replaceText(property.key, getQuotedKey(property.key)) }); }); @@ -266,7 +266,7 @@ module.exports = { context.report({ node: property, message: "Inconsistently quoted property '{{key}}' found.", - data: {key: property.key.name || property.key.value}, + data: { key: property.key.name || property.key.value }, fix: fixer => fixer.replaceText(property.key, getQuotedKey(property.key)) }); }); diff --git a/tools/eslint/lib/rules/quotes.js b/tools/eslint/lib/rules/quotes.js index 90e68289e05662..5c53c76908c3df 100644 --- a/tools/eslint/lib/rules/quotes.js +++ b/tools/eslint/lib/rules/quotes.js @@ -51,7 +51,7 @@ QUOTE_SETTINGS.backtick.convert = function(str) { if (newQuote === oldQuote) { return str; } - return newQuote + str.slice(1, -1).replace(/\\(\${|\r\n?|\n|.)|["'`]|\${|(\r\n?|\n)/g, function(match, escaped, newline) { + return newQuote + str.slice(1, -1).replace(/\\(\${|\r\n?|\n|.)|["'`]|\${|(\r\n?|\n)/g, (match, escaped, newline) => { if (escaped === oldQuote || oldQuote === "`" && escaped === "${") { return escaped; // unescape } @@ -258,7 +258,11 @@ module.exports = { return; } - const shouldWarn = node.quasis.length === 1 && (node.quasis[0].value.cooked.indexOf("\n") === -1); + /* + * A warning should be produced if the template literal only has one TemplateElement, and has no unescaped newlines. + * An unescaped newline is a newline preceded by an even number of backslashes. + */ + const shouldWarn = node.quasis.length === 1 && !/(^|[^\\])(\\\\)*[\r\n\u2028\u2029]/.test(node.quasis[0].value.raw); if (shouldWarn) { context.report({ @@ -268,6 +272,15 @@ module.exports = { description: settings.description, }, fix(fixer) { + if (isPartOfDirectivePrologue(node)) { + + /* + * TemplateLiterals in a directive prologue aren't actually directives, but if they're + * in the directive prologue, then fixing them might turn them into directives and change + * the behavior of the code. + */ + return null; + } return fixer.replaceText(node, settings.convert(sourceCode.getText(node))); } }); diff --git a/tools/eslint/lib/rules/radix.js b/tools/eslint/lib/rules/radix.js index f36e27d3634b9e..0dfa081b6a3e35 100644 --- a/tools/eslint/lib/rules/radix.js +++ b/tools/eslint/lib/rules/radix.js @@ -145,7 +145,7 @@ module.exports = { // Check `parseInt()` variable = astUtils.getVariableByName(scope, "parseInt"); if (!isShadowed(variable)) { - variable.references.forEach(function(reference) { + variable.references.forEach(reference => { const node = reference.identifier; if (astUtils.isCallee(node)) { @@ -157,7 +157,7 @@ module.exports = { // Check `Number.parseInt()` variable = astUtils.getVariableByName(scope, "Number"); if (!isShadowed(variable)) { - variable.references.forEach(function(reference) { + variable.references.forEach(reference => { const node = reference.identifier.parent; if (isParseIntMethod(node) && astUtils.isCallee(node)) { diff --git a/tools/eslint/lib/rules/require-await.js b/tools/eslint/lib/rules/require-await.js new file mode 100644 index 00000000000000..89b24f75b0f951 --- /dev/null +++ b/tools/eslint/lib/rules/require-await.js @@ -0,0 +1,95 @@ +/** + * @fileoverview Rule to disallow async functions which have no `await` expression. + * @author Toru Nagashima + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("../ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Capitalize the 1st letter of the given text. + * + * @param {string} text - The text to capitalize. + * @returns {string} The text that the 1st letter was capitalized. + */ +function capitalizeFirstLetter(text) { + return text[0].toUpperCase() + text.slice(1); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = { + meta: { + docs: { + description: "disallow async functions which have no `await` expression", + category: "Best Practices", + recommended: false + }, + schema: [] + }, + + create(context) { + const sourceCode = context.getSourceCode(); + let scopeInfo = null; + + /** + * Push the scope info object to the stack. + * + * @returns {void} + */ + function enterFunction() { + scopeInfo = { + upper: scopeInfo, + hasAwait: false, + }; + } + + /** + * Pop the top scope info object from the stack. + * Also, it reports the function if needed. + * + * @param {ASTNode} node - The node to report. + * @returns {void} + */ + function exitFunction(node) { + if (node.async && !scopeInfo.hasAwait && !astUtils.isEmptyFunction(node)) { + context.report({ + node, + loc: astUtils.getFunctionHeadLoc(node, sourceCode), + message: "{{name}} has no 'await' expression.", + data: { + name: capitalizeFirstLetter( + astUtils.getFunctionNameWithKind(node) + ) + } + }); + } + + scopeInfo = scopeInfo.upper; + } + + return { + FunctionDeclaration: enterFunction, + FunctionExpression: enterFunction, + ArrowFunctionExpression: enterFunction, + "FunctionDeclaration:exit": exitFunction, + "FunctionExpression:exit": exitFunction, + "ArrowFunctionExpression:exit": exitFunction, + + AwaitExpression() { + scopeInfo.hasAwait = true; + } + }; + } +}; diff --git a/tools/eslint/lib/rules/require-jsdoc.js b/tools/eslint/lib/rules/require-jsdoc.js index 9300fce1baa42b..f1ecde81f959ec 100644 --- a/tools/eslint/lib/rules/require-jsdoc.js +++ b/tools/eslint/lib/rules/require-jsdoc.js @@ -27,6 +27,9 @@ module.exports = { }, FunctionDeclaration: { type: "boolean" + }, + ArrowFunctionExpression: { + type: "boolean" } }, additionalProperties: false @@ -52,7 +55,7 @@ module.exports = { * @returns {void} */ function report(node) { - context.report(node, "Missing JSDoc comment."); + context.report({ node, message: "Missing JSDoc comment." }); } /** @@ -98,6 +101,11 @@ module.exports = { if (options.ClassDeclaration) { checkJsDoc(node); } + }, + ArrowFunctionExpression(node) { + if (options.ArrowFunctionExpression && node.parent.type === "VariableDeclarator") { + checkJsDoc(node); + } } }; } diff --git a/tools/eslint/lib/rules/require-yield.js b/tools/eslint/lib/rules/require-yield.js index 36b4ea11a585aa..5cc2944bc692d6 100644 --- a/tools/eslint/lib/rules/require-yield.js +++ b/tools/eslint/lib/rules/require-yield.js @@ -48,9 +48,7 @@ module.exports = { const countYield = stack.pop(); if (countYield === 0 && node.body.body.length > 0) { - context.report( - node, - "This generator function does not have 'yield'."); + context.report({ node, message: "This generator function does not have 'yield'." }); } } diff --git a/tools/eslint/lib/rules/semi.js b/tools/eslint/lib/rules/semi.js index 2f28f1614d1a42..ee37ab018c82fd 100644 --- a/tools/eslint/lib/rules/semi.js +++ b/tools/eslint/lib/rules/semi.js @@ -39,7 +39,7 @@ module.exports = { { type: "object", properties: { - omitLastInOneLineBlock: {type: "boolean"} + omitLastInOneLineBlock: { type: "boolean" } }, additionalProperties: false } @@ -53,7 +53,7 @@ module.exports = { create(context) { - const OPT_OUT_PATTERN = /^[-[(\/+]$/; // One of [(/+-, but not ++ or -- + const OPT_OUT_PATTERN = /^[-[(/+`]/; // One of [(/+-` const options = context.options[1]; const never = context.options[0] === "never", exceptOneLine = options && options.omitLastInOneLineBlock === true, @@ -127,7 +127,7 @@ module.exports = { const lastTokenLine = lastToken.loc.end.line; const nextTokenLine = nextToken.loc.start.line; - const isOptOutToken = OPT_OUT_PATTERN.test(nextToken.value); + const isOptOutToken = OPT_OUT_PATTERN.test(nextToken.value) && nextToken.value !== "++" && nextToken.value !== "--"; const isDivider = (nextToken.value === "}" || nextToken.value === ";"); return (lastTokenLine !== nextTokenLine && !isOptOutToken) || isDivider; diff --git a/tools/eslint/lib/rules/sort-imports.js b/tools/eslint/lib/rules/sort-imports.js index ae3333c2ac16d7..83f500990239b2 100644 --- a/tools/eslint/lib/rules/sort-imports.js +++ b/tools/eslint/lib/rules/sort-imports.js @@ -39,7 +39,9 @@ module.exports = { }, additionalProperties: false } - ] + ], + + fixable: "code" }, create(context) { @@ -47,7 +49,8 @@ module.exports = { const configuration = context.options[0] || {}, ignoreCase = configuration.ignoreCase || false, ignoreMemberSort = configuration.ignoreMemberSort || false, - memberSyntaxSortOrder = configuration.memberSyntaxSortOrder || ["none", "all", "multiple", "single"]; + memberSyntaxSortOrder = configuration.memberSyntaxSortOrder || ["none", "all", "multiple", "single"], + sourceCode = context.getSourceCode(); let previousDeclaration = null; /** @@ -135,36 +138,49 @@ module.exports = { } } - // Multiple members of an import declaration should also be sorted alphabetically. - if (!ignoreMemberSort && node.specifiers.length > 1) { - let previousSpecifier = null; - let previousSpecifierName = null; + if (!ignoreMemberSort) { + const importSpecifiers = node.specifiers.filter(specifier => specifier.type === "ImportSpecifier"); + const getSortableName = ignoreCase ? specifier => specifier.local.name.toLowerCase() : specifier => specifier.local.name; + const firstUnsortedIndex = importSpecifiers.map(getSortableName).findIndex((name, index, array) => array[index - 1] > name); + + if (firstUnsortedIndex !== -1) { + context.report({ + node: importSpecifiers[firstUnsortedIndex], + message: "Member '{{memberName}}' of the import declaration should be sorted alphabetically.", + data: { memberName: importSpecifiers[firstUnsortedIndex].local.name }, + fix(fixer) { + if (importSpecifiers.some(specifier => sourceCode.getComments(specifier).leading.length || sourceCode.getComments(specifier).trailing.length)) { + + // If there are comments in the ImportSpecifier list, don't rearrange the specifiers. + return null; + } - for (let i = 0; i < node.specifiers.length; ++i) { - const currentSpecifier = node.specifiers[i]; + return fixer.replaceTextRange( + [importSpecifiers[0].range[0], importSpecifiers[importSpecifiers.length - 1].range[1]], + importSpecifiers - if (currentSpecifier.type !== "ImportSpecifier") { - continue; - } + // Clone the importSpecifiers array to avoid mutating it + .slice() - let currentSpecifierName = currentSpecifier.local.name; + // Sort the array into the desired order + .sort((specifierA, specifierB) => { + const aName = getSortableName(specifierA); + const bName = getSortableName(specifierB); - if (ignoreCase) { - currentSpecifierName = currentSpecifierName.toLowerCase(); - } + return aName > bName ? 1 : -1; + }) - if (previousSpecifier && currentSpecifierName < previousSpecifierName) { - context.report({ - node: currentSpecifier, - message: "Member '{{memberName}}' of the import declaration should be sorted alphabetically.", - data: { - memberName: currentSpecifier.local.name - } - }); - } + // Build a string out of the sorted list of import specifiers and the text between the originals + .reduce((sourceText, specifier, index) => { + const textAfterSpecifier = index === importSpecifiers.length - 1 + ? "" + : sourceCode.getText().slice(importSpecifiers[index].range[1], importSpecifiers[index + 1].range[0]); - previousSpecifier = currentSpecifier; - previousSpecifierName = currentSpecifierName; + return sourceText + sourceCode.getText(specifier) + textAfterSpecifier; + }, "") + ); + } + }); } } diff --git a/tools/eslint/lib/rules/sort-vars.js b/tools/eslint/lib/rules/sort-vars.js index 1e1cf3c959e663..e18cc320ef0553 100644 --- a/tools/eslint/lib/rules/sort-vars.js +++ b/tools/eslint/lib/rules/sort-vars.js @@ -37,7 +37,7 @@ module.exports = { return { VariableDeclaration(node) { - node.declarations.reduce(function(memo, decl) { + node.declarations.reduce((memo, decl) => { if (decl.id.type === "ObjectPattern" || decl.id.type === "ArrayPattern") { return memo; } @@ -51,7 +51,7 @@ module.exports = { } if (currenVariableName < lastVariableName) { - context.report(decl, "Variables within the same declaration block should be sorted alphabetically."); + context.report({ node: decl, message: "Variables within the same declaration block should be sorted alphabetically." }); return memo; } else { return decl; diff --git a/tools/eslint/lib/rules/space-in-parens.js b/tools/eslint/lib/rules/space-in-parens.js index c01170b2bc13b4..af838dfa9e8376 100644 --- a/tools/eslint/lib/rules/space-in-parens.js +++ b/tools/eslint/lib/rules/space-in-parens.js @@ -220,7 +220,7 @@ module.exports = { exceptions = getExceptions(); const tokens = sourceCode.tokensAndComments; - tokens.forEach(function(token, i) { + tokens.forEach((token, i) => { const prevToken = tokens[i - 1]; const nextToken = tokens[i + 1]; diff --git a/tools/eslint/lib/rules/space-infix-ops.js b/tools/eslint/lib/rules/space-infix-ops.js index 9831e8e2af6085..d919a1225a2bf5 100644 --- a/tools/eslint/lib/rules/space-infix-ops.js +++ b/tools/eslint/lib/rules/space-infix-ops.js @@ -57,7 +57,7 @@ module.exports = { const op = tokens[i]; if ( - op.type === "Punctuator" && + (op.type === "Punctuator" || op.type === "Keyword") && OPERATORS.indexOf(op.value) >= 0 && (tokens[i - 1].range[1] >= op.range[0] || op.range[1] >= tokens[i + 1].range[0]) ) { diff --git a/tools/eslint/lib/rules/spaced-comment.js b/tools/eslint/lib/rules/spaced-comment.js index a3dce4fa4e3d30..85abd7360e622a 100644 --- a/tools/eslint/lib/rules/spaced-comment.js +++ b/tools/eslint/lib/rules/spaced-comment.js @@ -240,7 +240,7 @@ module.exports = { const config = context.options[1] || {}; const balanced = config.block && config.block.balanced; - const styleRules = ["block", "line"].reduce(function(rule, type) { + const styleRules = ["block", "line"].reduce((rule, type) => { const markers = parseMarkersOption(config[type] && config[type].markers || config.markers); const exceptions = config[type] && config[type].exceptions || config.exceptions || []; const endNeverPattern = "[ \t]+$"; diff --git a/tools/eslint/lib/rules/strict.js b/tools/eslint/lib/rules/strict.js index 1591bd871465d4..34ed443d92c816 100644 --- a/tools/eslint/lib/rules/strict.js +++ b/tools/eslint/lib/rules/strict.js @@ -135,7 +135,7 @@ module.exports = { */ function reportSlice(nodes, start, end, message, fix) { nodes.slice(start, end).forEach(node => { - context.report({node, message, fix: fix ? getFixFunction(node) : null}); + context.report({ node, message, fix: fix ? getFixFunction(node) : null }); }); } @@ -176,19 +176,19 @@ module.exports = { if (isStrict) { if (!isSimpleParameterList(node.params)) { - context.report(useStrictDirectives[0], messages.nonSimpleParameterList); + context.report({ node: useStrictDirectives[0], message: messages.nonSimpleParameterList }); } else if (isParentStrict) { - context.report({node: useStrictDirectives[0], message: messages.unnecessary, fix: getFixFunction(useStrictDirectives[0])}); + context.report({ node: useStrictDirectives[0], message: messages.unnecessary, fix: getFixFunction(useStrictDirectives[0]) }); } else if (isInClass) { - context.report({node: useStrictDirectives[0], message: messages.unnecessaryInClasses, fix: getFixFunction(useStrictDirectives[0])}); + context.report({ node: useStrictDirectives[0], message: messages.unnecessaryInClasses, fix: getFixFunction(useStrictDirectives[0]) }); } reportAllExceptFirst(useStrictDirectives, messages.multiple, true); } else if (isParentGlobal) { if (isSimpleParameterList(node.params)) { - context.report(node, messages.function); + context.report({ node, message: messages.function }); } else { - context.report(node, messages.wrap); + context.report({ node, message: messages.wrap }); } } @@ -221,7 +221,7 @@ module.exports = { if (isSimpleParameterList(node.params)) { reportAll(useStrictDirectives, messages[mode], shouldFix(mode)); } else { - context.report(useStrictDirectives[0], messages.nonSimpleParameterList); + context.report({ node: useStrictDirectives[0], message: messages.nonSimpleParameterList }); reportAllExceptFirst(useStrictDirectives, messages.multiple, true); } } @@ -237,7 +237,7 @@ module.exports = { if (mode === "global") { if (node.body.length > 0 && useStrictDirectives.length === 0) { - context.report(node, messages.global); + context.report({ node, message: messages.global }); } reportAllExceptFirst(useStrictDirectives, messages.multiple, true); } else { diff --git a/tools/eslint/lib/rules/symbol-description.js b/tools/eslint/lib/rules/symbol-description.js index 37ac8be7276656..3f5ffd7463cd5a 100644 --- a/tools/eslint/lib/rules/symbol-description.js +++ b/tools/eslint/lib/rules/symbol-description.js @@ -51,7 +51,7 @@ module.exports = { const variable = astUtils.getVariableByName(scope, "Symbol"); if (variable && variable.defs.length === 0) { - variable.references.forEach(function(reference) { + variable.references.forEach(reference => { const node = reference.identifier; if (astUtils.isCallee(node)) { diff --git a/tools/eslint/lib/rules/template-curly-spacing.js b/tools/eslint/lib/rules/template-curly-spacing.js index 1ac3262fce2597..1d491a24c9c1e2 100644 --- a/tools/eslint/lib/rules/template-curly-spacing.js +++ b/tools/eslint/lib/rules/template-curly-spacing.js @@ -33,7 +33,7 @@ module.exports = { fixable: "whitespace", schema: [ - {enum: ["always", "never"]} + { enum: ["always", "never"] } ] }, diff --git a/tools/eslint/lib/rules/unicode-bom.js b/tools/eslint/lib/rules/unicode-bom.js index 82692894d4a852..2f16a258509e8b 100644 --- a/tools/eslint/lib/rules/unicode-bom.js +++ b/tools/eslint/lib/rules/unicode-bom.js @@ -36,7 +36,7 @@ module.exports = { Program: function checkUnicodeBOM(node) { const sourceCode = context.getSourceCode(), - location = {column: 0, line: 1}, + location = { column: 0, line: 1 }, requireBOM = context.options[0] || "never"; if (!sourceCode.hasBOM && (requireBOM === "always")) { diff --git a/tools/eslint/lib/rules/use-isnan.js b/tools/eslint/lib/rules/use-isnan.js index b4a978b5efe21b..5ec48a0386e1b5 100644 --- a/tools/eslint/lib/rules/use-isnan.js +++ b/tools/eslint/lib/rules/use-isnan.js @@ -25,7 +25,7 @@ module.exports = { return { BinaryExpression(node) { if (/^(?:[<>]|[!=]=)=?$/.test(node.operator) && (node.left.name === "NaN" || node.right.name === "NaN")) { - context.report(node, "Use the isNaN function to compare with NaN."); + context.report({ node, message: "Use the isNaN function to compare with NaN." }); } } }; diff --git a/tools/eslint/lib/rules/valid-jsdoc.js b/tools/eslint/lib/rules/valid-jsdoc.js index 09fc684719a4af..66ad1f8d45de1f 100644 --- a/tools/eslint/lib/rules/valid-jsdoc.js +++ b/tools/eslint/lib/rules/valid-jsdoc.js @@ -202,7 +202,7 @@ module.exports = { elements.forEach(validateType.bind(null, jsdocNode)); - typesToCheck.forEach(function(typeToCheck) { + typesToCheck.forEach(typeToCheck => { if (typeToCheck.expectedType && typeToCheck.expectedType !== typeToCheck.currentType) { context.report({ @@ -246,15 +246,15 @@ module.exports = { } catch (ex) { if (/braces/i.test(ex.message)) { - context.report(jsdocNode, "JSDoc type missing brace."); + context.report({ node: jsdocNode, message: "JSDoc type missing brace." }); } else { - context.report(jsdocNode, "JSDoc syntax error."); + context.report({ node: jsdocNode, message: "JSDoc syntax error." }); } return; } - jsdoc.tags.forEach(function(tag) { + jsdoc.tags.forEach(tag => { switch (tag.title.toLowerCase()) { @@ -262,15 +262,15 @@ module.exports = { case "arg": case "argument": if (!tag.type) { - context.report(jsdocNode, "Missing JSDoc parameter type for '{{name}}'.", { name: tag.name }); + context.report({ node: jsdocNode, message: "Missing JSDoc parameter type for '{{name}}'.", data: { name: tag.name } }); } if (!tag.description && requireParamDescription) { - context.report(jsdocNode, "Missing JSDoc parameter description for '{{name}}'.", { name: tag.name }); + context.report({ node: jsdocNode, message: "Missing JSDoc parameter description for '{{name}}'.", data: { name: tag.name } }); } if (params[tag.name]) { - context.report(jsdocNode, "Duplicate JSDoc parameter '{{name}}'.", { name: tag.name }); + context.report({ node: jsdocNode, message: "Duplicate JSDoc parameter '{{name}}'.", data: { name: tag.name } }); } else if (tag.name.indexOf(".") === -1) { params[tag.name] = 1; } @@ -290,11 +290,11 @@ module.exports = { }); } else { if (requireReturnType && !tag.type) { - context.report(jsdocNode, "Missing JSDoc return type."); + context.report({ node: jsdocNode, message: "Missing JSDoc return type." }); } if (!isValidReturnType(tag) && !tag.description && requireReturnDescription) { - context.report(jsdocNode, "Missing JSDoc return description."); + context.report({ node: jsdocNode, message: "Missing JSDoc return description." }); } } @@ -324,7 +324,7 @@ module.exports = { // check tag preferences if (prefer.hasOwnProperty(tag.title) && tag.title !== prefer[tag.title]) { - context.report(jsdocNode, "Use @{{name}} instead.", { name: prefer[tag.title] }); + context.report({ node: jsdocNode, message: "Use @{{name}} instead.", data: { name: prefer[tag.title] } }); } // validate the types @@ -352,7 +352,7 @@ module.exports = { const jsdocParams = Object.keys(params); if (node.params) { - node.params.forEach(function(param, i) { + node.params.forEach((param, i) => { if (param.type === "AssignmentPattern") { param = param.left; } @@ -362,14 +362,14 @@ module.exports = { // TODO(nzakas): Figure out logical things to do with destructured, default, rest params if (param.type === "Identifier") { if (jsdocParams[i] && (name !== jsdocParams[i])) { - context.report(jsdocNode, "Expected JSDoc for '{{name}}' but found '{{jsdocName}}'.", { + context.report({ node: jsdocNode, message: "Expected JSDoc for '{{name}}' but found '{{jsdocName}}'.", data: { name, jsdocName: jsdocParams[i] - }); + } }); } else if (!params[name] && !isOverride) { - context.report(jsdocNode, "Missing JSDoc for parameter '{{name}}'.", { + context.report({ node: jsdocNode, message: "Missing JSDoc for parameter '{{name}}'.", data: { name - }); + } }); } } }); @@ -379,7 +379,7 @@ module.exports = { const regex = new RegExp(options.matchDescription); if (!regex.test(jsdoc.description)) { - context.report(jsdocNode, "JSDoc description does not satisfy the regex pattern."); + context.report({ node: jsdocNode, message: "JSDoc description does not satisfy the regex pattern." }); } } diff --git a/tools/eslint/lib/rules/valid-typeof.js b/tools/eslint/lib/rules/valid-typeof.js index ed0a7c017955f2..94b407b600a43c 100644 --- a/tools/eslint/lib/rules/valid-typeof.js +++ b/tools/eslint/lib/rules/valid-typeof.js @@ -62,10 +62,10 @@ module.exports = { const value = sibling.type === "Literal" ? sibling.value : sibling.quasis[0].value.cooked; if (VALID_TYPES.indexOf(value) === -1) { - context.report(sibling, "Invalid typeof comparison value."); + context.report({ node: sibling, message: "Invalid typeof comparison value." }); } } else if (requireStringLiterals && !isTypeofExpression(sibling)) { - context.report(sibling, "Typeof comparisons should be to string literals."); + context.report({ node: sibling, message: "Typeof comparisons should be to string literals." }); } } } diff --git a/tools/eslint/lib/rules/vars-on-top.js b/tools/eslint/lib/rules/vars-on-top.js index 92ed08e2d4b5de..f74db905b1908d 100644 --- a/tools/eslint/lib/rules/vars-on-top.js +++ b/tools/eslint/lib/rules/vars-on-top.js @@ -100,7 +100,7 @@ module.exports = { */ function globalVarCheck(node, parent) { if (!isVarOnTop(node, parent.body)) { - context.report(node, errorMessage); + context.report({ node, message: errorMessage }); } } @@ -115,7 +115,7 @@ module.exports = { if (!(/Function/.test(grandParent.type) && parent.type === "BlockStatement" && isVarOnTop(node, parent.body))) { - context.report(node, errorMessage); + context.report({ node, message: errorMessage }); } } diff --git a/tools/eslint/lib/rules/yield-star-spacing.js b/tools/eslint/lib/rules/yield-star-spacing.js index ecd33c5b38fafb..eb20fc01b0b9a9 100644 --- a/tools/eslint/lib/rules/yield-star-spacing.js +++ b/tools/eslint/lib/rules/yield-star-spacing.js @@ -28,8 +28,8 @@ module.exports = { { type: "object", properties: { - before: {type: "boolean"}, - after: {type: "boolean"} + before: { type: "boolean" }, + after: { type: "boolean" } }, additionalProperties: false } diff --git a/tools/eslint/lib/rules/yoda.js b/tools/eslint/lib/rules/yoda.js index e463a476ab6be4..ba711c63c2f1ae 100644 --- a/tools/eslint/lib/rules/yoda.js +++ b/tools/eslint/lib/rules/yoda.js @@ -4,6 +4,12 @@ */ "use strict"; +//-------------------------------------------------------------------------- +// Requirements +//-------------------------------------------------------------------------- + +const astUtils = require("../ast-utils"); + //-------------------------------------------------------------------------- // Helpers //-------------------------------------------------------------------------- @@ -54,13 +60,16 @@ function looksLikeLiteral(node) { /** * Attempts to derive a Literal node from nodes that are treated like literals. * @param {ASTNode} node Node to normalize. - * @returns {ASTNode} The original node if the node is already a Literal, or a - * normalized Literal node with the negative number as the - * value if the node represents a negative number literal, - * otherwise null if the node cannot be converted to a - * normalized literal. + * @param {number} [defaultValue] The default value to be returned if the node + * is not a Literal. + * @returns {ASTNode} One of the following options. + * 1. The original node if the node is already a Literal + * 2. A normalized Literal node with the negative number as the value if the + * node represents a negative number literal. + * 3. The Literal node which has the `defaultValue` argument if it exists. + * 4. Otherwise `null`. */ -function getNormalizedLiteral(node) { +function getNormalizedLiteral(node, defaultValue) { if (node.type === "Literal") { return node; } @@ -73,6 +82,14 @@ function getNormalizedLiteral(node) { }; } + if (defaultValue) { + return { + type: "Literal", + value: defaultValue, + raw: String(defaultValue) + }; + } + return null; } @@ -98,12 +115,26 @@ function same(a, b) { case "Literal": return a.value === b.value; - case "MemberExpression": + case "MemberExpression": { + const nameA = astUtils.getStaticPropertyName(a); + + // x.y = x["y"] + if (nameA) { + return ( + same(a.object, b.object) && + nameA === astUtils.getStaticPropertyName(b) + ); + } // x[0] = x[0] // x[y] = x[y] // x.y = x.y - return same(a.object, b.object) && same(a.property, b.property); + return ( + a.computed === b.computed && + same(a.object, b.object) && + same(a.property, b.property) + ); + } case "ThisExpression": return true; @@ -178,7 +209,7 @@ module.exports = { return (node.operator === "&&" && (leftLiteral = getNormalizedLiteral(left.left)) && - (rightLiteral = getNormalizedLiteral(right.right)) && + (rightLiteral = getNormalizedLiteral(right.right, Number.POSITIVE_INFINITY)) && leftLiteral.value <= rightLiteral.value && same(left.right, right.left)); } @@ -191,7 +222,7 @@ module.exports = { let leftLiteral, rightLiteral; return (node.operator === "||" && - (leftLiteral = getNormalizedLiteral(left.right)) && + (leftLiteral = getNormalizedLiteral(left.right, Number.NEGATIVE_INFINITY)) && (rightLiteral = getNormalizedLiteral(right.left)) && leftLiteral.value <= rightLiteral.value && same(left.left, right.right)); diff --git a/tools/eslint/lib/testers/event-generator-tester.js b/tools/eslint/lib/testers/event-generator-tester.js index d85238e9db0471..89693fe94819df 100644 --- a/tools/eslint/lib/testers/event-generator-tester.js +++ b/tools/eslint/lib/testers/event-generator-tester.js @@ -44,19 +44,19 @@ module.exports = { * @returns {void} */ testEventGeneratorInterface(instance) { - this.describe("should implement EventGenerator interface", function() { - this.it("should have `emitter` property.", function() { + this.describe("should implement EventGenerator interface", () => { + this.it("should have `emitter` property.", () => { assert.equal(typeof instance.emitter, "object"); assert.equal(typeof instance.emitter.emit, "function"); }); - this.it("should have `enterNode` property.", function() { + this.it("should have `enterNode` property.", () => { assert.equal(typeof instance.enterNode, "function"); }); - this.it("should have `leaveNode` property.", function() { + this.it("should have `leaveNode` property.", () => { assert.equal(typeof instance.leaveNode, "function"); }); - }.bind(this)); + }); } }; diff --git a/tools/eslint/lib/testers/rule-tester.js b/tools/eslint/lib/testers/rule-tester.js index 25b86993593c4a..5d327ad28b9360 100644 --- a/tools/eslint/lib/testers/rule-tester.js +++ b/tools/eslint/lib/testers/rule-tester.js @@ -252,8 +252,26 @@ RuleTester.prototype = { run(ruleName, rule, test) { const testerConfig = this.testerConfig, + requiredScenarios = ["valid", "invalid"], + scenarioErrors = [], result = {}; + if (lodash.isNil(test) || typeof test !== "object") { + throw new Error(`Test Scenarios for rule ${ruleName} : Could not find test scenario object`); + } + + requiredScenarios.forEach(scenarioType => { + if (lodash.isNil(test[scenarioType])) { + scenarioErrors.push(`Could not find any ${scenarioType} test scenarios`); + } + }); + + if (scenarioErrors.length > 0) { + throw new Error([ + `Test Scenarios for rule ${ruleName} is invalid:` + ].concat(scenarioErrors).join("\n")); + } + /* eslint-disable no-shadow */ /** @@ -307,9 +325,7 @@ RuleTester.prototype = { if (validateSchema.errors) { throw new Error([ `Schema for rule ${ruleName} is invalid:` - ].concat(validateSchema.errors.map(function(error) { - return `\t${error.field}: ${error.message}`; - })).join("\n")); + ].concat(validateSchema.errors.map(error => `\t${error.field}: ${error.message}`)).join("\n")); } } @@ -321,10 +337,10 @@ RuleTester.prototype = { * running the rule under test. */ eslint.reset(); - eslint.on("Program", function(node) { + eslint.on("Program", node => { beforeAST = cloneDeeplyExcludesParent(node); - eslint.on("Program:exit", function(node) { + eslint.on("Program:exit", node => { afterAST = cloneDeeplyExcludesParent(node); }); }); @@ -448,7 +464,7 @@ RuleTester.prototype = { } if (item.errors[i].type) { - assert.equal(messages[i].nodeType, item.errors[i].type, `Error type should be ${item.errors[i].type}`); + assert.equal(messages[i].nodeType, item.errors[i].type, `Error type should be ${item.errors[i].type}, found ${messages[i].nodeType}`); } if (item.errors[i].hasOwnProperty("line")) { @@ -488,18 +504,18 @@ RuleTester.prototype = { * This creates a mocha test suite and pipes all supplied info through * one of the templates above. */ - RuleTester.describe(ruleName, function() { - RuleTester.describe("valid", function() { - test.valid.forEach(function(valid) { - RuleTester.it(valid.code || valid, function() { + RuleTester.describe(ruleName, () => { + RuleTester.describe("valid", () => { + test.valid.forEach(valid => { + RuleTester.it(valid.code || valid, () => { testValidTemplate(ruleName, valid); }); }); }); - RuleTester.describe("invalid", function() { - test.invalid.forEach(function(invalid) { - RuleTester.it(invalid.code, function() { + RuleTester.describe("invalid", () => { + test.invalid.forEach(invalid => { + RuleTester.it(invalid.code, () => { testInvalidTemplate(ruleName, invalid); }); }); diff --git a/tools/eslint/lib/timing.js b/tools/eslint/lib/timing.js index 627aa5f82f8118..20456628640bf6 100644 --- a/tools/eslint/lib/timing.js +++ b/tools/eslint/lib/timing.js @@ -54,18 +54,16 @@ const ALIGN = [alignLeft, alignRight, alignRight]; function display(data) { let total = 0; const rows = Object.keys(data) - .map(function(key) { + .map(key => { const time = data[key]; total += time; return [key, time]; }) - .sort(function(a, b) { - return b[1] - a[1]; - }) + .sort((a, b) => b[1] - a[1]) .slice(0, 10); - rows.forEach(function(row) { + rows.forEach(row => { row.push(`${(row[1] * 100 / total).toFixed(1)}%`); row[1] = row[1].toFixed(3); }); @@ -74,7 +72,7 @@ function display(data) { const widths = []; - rows.forEach(function(row) { + rows.forEach(row => { const len = row.length; for (let i = 0; i < len; i++) { @@ -86,13 +84,13 @@ function display(data) { } }); - const table = rows.map(function(row) { - return row.map(function(cell, index) { - return ALIGN[index](cell, widths[index]); - }).join(" | "); - }); + const table = rows.map(row => + row + .map((cell, index) => ALIGN[index](cell, widths[index])) + .join(" | ") + ); - table.splice(1, 0, widths.map(function(w, index) { + table.splice(1, 0, widths.map((w, index) => { if (index !== 0 && index !== widths.length - 1) { w++; } @@ -130,7 +128,7 @@ module.exports = (function() { } if (enabled) { - process.on("exit", function() { + process.on("exit", () => { display(data); }); } diff --git a/tools/eslint/lib/util/comment-event-generator.js b/tools/eslint/lib/util/comment-event-generator.js index 47cc68f296f87e..dfa7132ff850ef 100644 --- a/tools/eslint/lib/util/comment-event-generator.js +++ b/tools/eslint/lib/util/comment-event-generator.js @@ -20,7 +20,7 @@ */ function emitComments(comments, emitter, locs, eventName) { if (comments.length > 0) { - comments.forEach(function(node) { + comments.forEach(node => { const index = locs.indexOf(node.loc); if (index >= 0) { diff --git a/tools/eslint/lib/util/glob-util.js b/tools/eslint/lib/util/glob-util.js index cba2e694ad5238..198e069e9f0850 100644 --- a/tools/eslint/lib/util/glob-util.js +++ b/tools/eslint/lib/util/glob-util.js @@ -43,9 +43,7 @@ function processPath(options) { const cwd = (options && options.cwd) || process.cwd(); let extensions = (options && options.extensions) || [".js"]; - extensions = extensions.map(function(ext) { - return ext.charAt(0) === "." ? ext.substr(1) : ext; - }); + extensions = extensions.map(ext => ext.replace(/^\./, "")); let suffix = "/**"; @@ -67,7 +65,7 @@ function processPath(options) { const resolvedPath = path.resolve(cwd, pathname); if (shell.test("-d", resolvedPath)) { - newPath = pathname.replace(/[\/\\]$/, "") + suffix; + newPath = pathname.replace(/[/\\]$/, "") + suffix; } return pathUtil.convertPathToPosix(newPath); @@ -145,12 +143,12 @@ function listFilesToProcess(globPatterns, options) { if (added[filename]) { return; } - files.push({filename, ignored}); + files.push({ filename, ignored }); added[filename] = true; } debug("Creating list of files to process."); - globPatterns.forEach(function(pattern) { + globPatterns.forEach(pattern => { const file = path.resolve(cwd, pattern); if (shell.test("-f", file)) { @@ -160,9 +158,9 @@ function listFilesToProcess(globPatterns, options) { } else { // regex to find .hidden or /.hidden patterns, but not ./relative or ../relative - const globIncludesDotfiles = /(?:(?:^\.)|(?:[\/\\]\.))[^\/\\\.].*/.test(pattern); + const globIncludesDotfiles = /(?:(?:^\.)|(?:[/\\]\.))[^/\\.].*/.test(pattern); - const ignoredPaths = new IgnoredPaths(Object.assign({}, options, {dotfiles: options.dotfiles || globIncludesDotfiles})); + const ignoredPaths = new IgnoredPaths(Object.assign({}, options, { dotfiles: options.dotfiles || globIncludesDotfiles })); const shouldIgnore = ignoredPaths.getIgnoredFoldersGlobChecker(); const globOptions = { nodir: true, @@ -170,7 +168,7 @@ function listFilesToProcess(globPatterns, options) { cwd, }; - new GlobSync(pattern, globOptions, shouldIgnore).found.forEach(function(globMatch) { + new GlobSync(pattern, globOptions, shouldIgnore).found.forEach(globMatch => { addFile(path.resolve(cwd, globMatch), false, ignoredPaths); }); } diff --git a/tools/eslint/lib/util/module-resolver.js b/tools/eslint/lib/util/module-resolver.js index 40c107a70e82bd..505c572822699b 100644 --- a/tools/eslint/lib/util/module-resolver.js +++ b/tools/eslint/lib/util/module-resolver.js @@ -30,18 +30,18 @@ const DEFAULT_OPTIONS = { /** * Resolves modules based on a set of options. - * @param {Object} options The options for resolving modules. - * @param {string[]} options.lookupPaths An array of paths to include in the - * lookup with the highest priority paths coming first. - * @constructor */ -function ModuleResolver(options) { - options = options || {}; +class ModuleResolver { - this.options = Object.assign({}, DEFAULT_OPTIONS, options); -} - -ModuleResolver.prototype = { + /** + * Resolves modules based on a set of options. + * @param {Object} options The options for resolving modules. + * @param {string[]} options.lookupPaths An array of paths to include in the + * lookup with the highest priority paths coming first. + */ + constructor(options) { + this.options = Object.assign({}, DEFAULT_OPTIONS, options || {}); + } /** * Resolves the file location of a given module relative to the configured @@ -75,10 +75,8 @@ ModuleResolver.prototype = { } return result; - } - -}; +} //------------------------------------------------------------------------------ // Public API diff --git a/tools/eslint/lib/util/node-event-generator.js b/tools/eslint/lib/util/node-event-generator.js index 95d9132dd2f3b3..1666ae93f53406 100644 --- a/tools/eslint/lib/util/node-event-generator.js +++ b/tools/eslint/lib/util/node-event-generator.js @@ -20,34 +20,33 @@ * leaveNode(node: ASTNode): void; * } * ``` - * - * @param {EventEmitter} emitter - An event emitter which is the destination of events. - * @returns {NodeEventGenerator} new instance. */ -function NodeEventGenerator(emitter) { - this.emitter = emitter; -} +class NodeEventGenerator { -NodeEventGenerator.prototype = { - constructor: NodeEventGenerator, + /** + * @param {EventEmitter} emitter - An event emitter which is the destination of events. + */ + constructor(emitter) { + this.emitter = emitter; + } /** * Emits an event of entering AST node. * @param {ASTNode} node - A node which was entered. * @returns {void} */ - enterNode: function enterNode(node) { + enterNode(node) { this.emitter.emit(node.type, node); - }, + } /** * Emits an event of leaving AST node. * @param {ASTNode} node - A node which was left. * @returns {void} */ - leaveNode: function leaveNode(node) { + leaveNode(node) { this.emitter.emit(`${node.type}:exit`, node); } -}; +} module.exports = NodeEventGenerator; diff --git a/tools/eslint/lib/util/npm-util.js b/tools/eslint/lib/util/npm-util.js index e9131595e7e822..ef1c0c62936347 100644 --- a/tools/eslint/lib/util/npm-util.js +++ b/tools/eslint/lib/util/npm-util.js @@ -53,7 +53,7 @@ function installSyncSaveDev(packages) { if (Array.isArray(packages)) { packages = packages.join(" "); } - shell.exec(`npm i --save-dev ${packages}`, {stdio: "inherit"}); + shell.exec(`npm i --save-dev ${packages}`, { stdio: "inherit" }); } /** @@ -89,7 +89,7 @@ function check(packages, opt) { if (opt.dependencies && typeof fileJson.dependencies === "object") { deps = deps.concat(Object.keys(fileJson.dependencies)); } - return packages.reduce(function(status, pkg) { + return packages.reduce((status, pkg) => { status[pkg] = deps.indexOf(pkg) !== -1; return status; }, {}); @@ -107,7 +107,7 @@ function check(packages, opt) { * and values are booleans indicating installation. */ function checkDeps(packages, rootDir) { - return check(packages, {dependencies: true, startDir: rootDir}); + return check(packages, { dependencies: true, startDir: rootDir }); } /** @@ -121,7 +121,7 @@ function checkDeps(packages, rootDir) { * and values are booleans indicating installation. */ function checkDevDeps(packages) { - return check(packages, {devDependencies: true}); + return check(packages, { devDependencies: true }); } /** diff --git a/tools/eslint/lib/util/patterns/letters.js b/tools/eslint/lib/util/patterns/letters.js new file mode 100644 index 00000000000000..b212cfc9ebd34a --- /dev/null +++ b/tools/eslint/lib/util/patterns/letters.js @@ -0,0 +1,37 @@ +/** + * @fileoverview Pattern for detecting any letter (even letters outside of ASCII). + * NOTE: This file was generated using this script in JSCS based on the Unicode 7.0.0 standard: https://github.com/jscs-dev/node-jscs/blob/f5ed14427deb7e7aac84f3056a5aab2d9f3e563e/publish/helpers/generate-patterns.js + * Do not edit this file by hand-- please use https://github.com/mathiasbynens/regenerate to regenerate the regular expression exported from this file. + * @author Kevin Partington + * @license MIT License (from JSCS). See below. + */ + +/* + * The MIT License (MIT) + * + * Copyright 2013-2016 Dulin Marat and other contributors + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +"use strict"; + +module.exports = /[A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B2\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16F1-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF40\uDF42-\uDF49\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF]|\uD801[\uDC00-\uDC9D\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDE00-\uDE11\uDE13-\uDE2B\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDE00-\uDE2F\uDE44\uDE80-\uDEAA]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF98]|[\uD80C\uD840-\uD868\uD86A-\uD86C][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D]|\uD87E[\uDC00-\uDE1D]/; + diff --git a/tools/eslint/lib/util/source-code-fixer.js b/tools/eslint/lib/util/source-code-fixer.js index 064a0a1f902443..3b702e509e77a4 100644 --- a/tools/eslint/lib/util/source-code-fixer.js +++ b/tools/eslint/lib/util/source-code-fixer.js @@ -72,7 +72,7 @@ SourceCodeFixer.applyFixes = function(sourceCode, messages) { let lastFixPos = text.length + 1, prefix = (sourceCode.hasBOM ? BOM : ""); - messages.forEach(function(problem) { + messages.forEach(problem => { if (problem.hasOwnProperty("fix")) { fixes.push(problem); } else { @@ -84,14 +84,12 @@ SourceCodeFixer.applyFixes = function(sourceCode, messages) { debug("Found fixes to apply"); // sort in reverse order of occurrence - fixes.sort(function(a, b) { - return b.fix.range[1] - a.fix.range[1] || b.fix.range[0] - a.fix.range[0]; - }); + fixes.sort((a, b) => b.fix.range[1] - a.fix.range[1] || b.fix.range[0] - a.fix.range[0]); // split into array of characters for easier manipulation const chars = text.split(""); - fixes.forEach(function(problem) { + fixes.forEach(problem => { const fix = problem.fix; let start = fix.range[0]; const end = fix.range[1]; diff --git a/tools/eslint/lib/util/source-code-util.js b/tools/eslint/lib/util/source-code-util.js index 8e660e0961d330..892c32d22a00e8 100644 --- a/tools/eslint/lib/util/source-code-util.js +++ b/tools/eslint/lib/util/source-code-util.js @@ -29,7 +29,7 @@ const debug = require("debug")("eslint:source-code-util"); */ function getSourceCodeOfFile(filename, options) { debug("getting sourceCode of", filename); - const opts = Object.assign({}, options, { rules: {}}); + const opts = Object.assign({}, options, { rules: {} }); const cli = new CLIEngine(opts); const results = cli.executeOnFiles([filename]); @@ -71,7 +71,7 @@ function getSourceCodeOfFiles(patterns, options, cb) { patterns = [patterns]; } - const defaultOptions = Object.assign({}, baseDefaultOptions, {cwd: process.cwd()}); + const defaultOptions = Object.assign({}, baseDefaultOptions, { cwd: process.cwd() }); if (typeof options === "undefined") { opts = defaultOptions; @@ -84,14 +84,14 @@ function getSourceCodeOfFiles(patterns, options, cb) { debug("constructed options:", opts); patterns = globUtil.resolveFileGlobPatterns(patterns, opts); - const filenames = globUtil.listFilesToProcess(patterns, opts).reduce(function(files, fileInfo) { - return !fileInfo.ignored ? files.concat(fileInfo.filename) : files; - }, []); + const filenames = globUtil.listFilesToProcess(patterns, opts) + .filter(fileInfo => !fileInfo.ignored) + .reduce((files, fileInfo) => files.concat(fileInfo.filename), []); if (filenames.length === 0) { debug(`Did not find any files matching pattern(s): ${patterns}`); } - filenames.forEach(function(filename) { + filenames.forEach(filename => { const sourceCode = getSourceCodeOfFile(filename, opts); if (sourceCode) { diff --git a/tools/eslint/lib/util/source-code.js b/tools/eslint/lib/util/source-code.js index 378bdd328fa50a..5d073039d81cd7 100644 --- a/tools/eslint/lib/util/source-code.js +++ b/tools/eslint/lib/util/source-code.js @@ -117,16 +117,16 @@ function SourceCode(text, ast) { */ this.lines = SourceCode.splitLines(this.text); - this.tokensAndComments = ast.tokens.concat(ast.comments).sort(function(left, right) { - return left.range[0] - right.range[0]; - }); + this.tokensAndComments = ast.tokens + .concat(ast.comments) + .sort((left, right) => left.range[0] - right.range[0]); // create token store methods const tokenStore = createTokenStore(ast.tokens); - Object.keys(tokenStore).forEach(function(methodName) { + Object.keys(tokenStore).forEach(methodName => { this[methodName] = tokenStore[methodName]; - }, this); + }); const tokensAndCommentsStore = createTokenStore(this.tokensAndComments); @@ -280,7 +280,7 @@ SourceCode.prototype = { } }); - return result ? Object.assign({parent: resultParent}, result) : null; + return result ? Object.assign({ parent: resultParent }, result) : null; }, /** diff --git a/tools/eslint/lib/util/traverser.js b/tools/eslint/lib/util/traverser.js index 50d18b045eb6ff..d5710bb8ac7b2d 100644 --- a/tools/eslint/lib/util/traverser.js +++ b/tools/eslint/lib/util/traverser.js @@ -46,9 +46,7 @@ function Traverser() { * @private */ Traverser.getKeys = function(node) { - return Object.keys(node).filter(function(key) { - return KEY_BLACKLIST.indexOf(key) === -1; - }); + return Object.keys(node).filter(key => KEY_BLACKLIST.indexOf(key) === -1); }; module.exports = Traverser; diff --git a/tools/eslint/lib/util/xml-escape.js b/tools/eslint/lib/util/xml-escape.js index 698abaf38eaecf..9f43c99c46a23c 100644 --- a/tools/eslint/lib/util/xml-escape.js +++ b/tools/eslint/lib/util/xml-escape.js @@ -15,7 +15,7 @@ * @private */ module.exports = function(s) { - return (`${s}`).replace(/[<>&"'\x00-\x1F\x7F\u0080-\uFFFF]/g, function(c) { // eslint-disable-line no-control-regex + return (`${s}`).replace(/[<>&"'\x00-\x1F\x7F\u0080-\uFFFF]/g, c => { // eslint-disable-line no-control-regex switch (c) { case "<": return "<"; diff --git a/tools/eslint/node_modules/.bin/eslint b/tools/eslint/node_modules/.bin/eslint new file mode 120000 index 00000000000000..810e4bcb32af34 --- /dev/null +++ b/tools/eslint/node_modules/.bin/eslint @@ -0,0 +1 @@ +../eslint/bin/eslint.js \ No newline at end of file diff --git a/tools/eslint/node_modules/.bin/strip-json-comments b/tools/eslint/node_modules/.bin/strip-json-comments deleted file mode 120000 index 63d549f96f3b2f..00000000000000 --- a/tools/eslint/node_modules/.bin/strip-json-comments +++ /dev/null @@ -1 +0,0 @@ -../strip-json-comments/cli.js \ No newline at end of file diff --git a/tools/eslint/node_modules/acorn/.tern-project b/tools/eslint/node_modules/acorn/.tern-project deleted file mode 100644 index 6718ce07e1c8a0..00000000000000 --- a/tools/eslint/node_modules/acorn/.tern-project +++ /dev/null @@ -1,6 +0,0 @@ -{ - "plugins": { - "node": true, - "es_modules": true - } -} \ No newline at end of file diff --git a/tools/eslint/node_modules/acorn/AUTHORS b/tools/eslint/node_modules/acorn/AUTHORS index 314d7086cf5bf2..306404542a3b07 100644 --- a/tools/eslint/node_modules/acorn/AUTHORS +++ b/tools/eslint/node_modules/acorn/AUTHORS @@ -25,6 +25,7 @@ Joel Kemp Johannes Herr Jordan Klassen Jürg Lehni +Kai Cataldo keeyipchan Keheliya Gallaba Kevin Irish @@ -32,6 +33,7 @@ Kevin Kwok krator Marijn Haverbeke Martin Carlberg +Mat Garcia Mathias Bynens Mathieu 'p01' Henri Matthew Bastien diff --git a/tools/eslint/node_modules/acorn/bin/generate-identifier-regex.js b/tools/eslint/node_modules/acorn/bin/generate-identifier-regex.js deleted file mode 100644 index 100e8cf280fc56..00000000000000 --- a/tools/eslint/node_modules/acorn/bin/generate-identifier-regex.js +++ /dev/null @@ -1,55 +0,0 @@ -'use strict'; - -// Which Unicode version should be used? -var version = '9.0.0'; - -var start = require('unicode-' + version + '/Binary_Property/ID_Start/code-points.js') - .filter(function(ch) { return ch > 0x7f; }); -var last = -1; -var cont = [0x200c, 0x200d].concat(require('unicode-' + version + '/Binary_Property/ID_Continue/code-points.js') - .filter(function(ch) { return ch > 0x7f && search(start, ch, last + 1) == -1; })); - -function search(arr, ch, starting) { - for (var i = starting; arr[i] <= ch && i < arr.length; last = i++) - if (arr[i] === ch) - return i; - return -1; -} - -function pad(str, width) { - while (str.length < width) str = "0" + str; - return str; -} - -function esc(code) { - var hex = code.toString(16); - if (hex.length <= 2) return "\\x" + pad(hex, 2); - else return "\\u" + pad(hex, 4); -} - -function generate(chars) { - var astral = [], re = ""; - for (var i = 0, at = 0x10000; i < chars.length; i++) { - var from = chars[i], to = from; - while (i < chars.length - 1 && chars[i + 1] == to + 1) { - i++; - to++; - } - if (to <= 0xffff) { - if (from == to) re += esc(from); - else if (from + 1 == to) re += esc(from) + esc(to); - else re += esc(from) + "-" + esc(to); - } else { - astral.push(from - at, to - from); - at = to; - } - } - return {nonASCII: re, astral: astral}; -} - -var startData = generate(start), contData = generate(cont); - -console.log("let nonASCIIidentifierStartChars = \"" + startData.nonASCII + "\""); -console.log("let nonASCIIidentifierChars = \"" + contData.nonASCII + "\""); -console.log("const astralIdentifierStartCodes = " + JSON.stringify(startData.astral)); -console.log("const astralIdentifierCodes = " + JSON.stringify(contData.astral)); diff --git a/tools/eslint/node_modules/acorn/bin/update_authors.sh b/tools/eslint/node_modules/acorn/bin/update_authors.sh deleted file mode 100755 index e08f57273cdd1e..00000000000000 --- a/tools/eslint/node_modules/acorn/bin/update_authors.sh +++ /dev/null @@ -1,6 +0,0 @@ -# Combine existing list of authors with everyone known in git, sort, add header. -tail --lines=+3 AUTHORS > AUTHORS.tmp -git log --format='%aN' | grep -v abraidwood | grep -v Rich-Harris | grep -v ForbesLindesay >> AUTHORS.tmp -echo -e "List of Acorn contributors. Updated before every release.\n" > AUTHORS -sort -u AUTHORS.tmp >> AUTHORS -rm -f AUTHORS.tmp diff --git a/tools/eslint/node_modules/acorn/dist/acorn.es.js b/tools/eslint/node_modules/acorn/dist/acorn.es.js index adb3dd30f3012a..32dd5954ea0e68 100644 --- a/tools/eslint/node_modules/acorn/dist/acorn.es.js +++ b/tools/eslint/node_modules/acorn/dist/acorn.es.js @@ -1305,7 +1305,12 @@ pp$1.checkVariableExport = function(exports, decls) { } pp$1.shouldParseExportStatement = function() { - return this.type.keyword || this.isLet() || this.isAsyncFunction() + return this.type.keyword === "var" + || this.type.keyword === "const" + || this.type.keyword === "class" + || this.type.keyword === "function" + || this.isLet() + || this.isAsyncFunction() } // Parses a comma-separated list of module exports. @@ -1617,6 +1622,24 @@ pp$2.checkLVal = function(expr, isBinding, checkClashes) { } } +// A recursive descent parser operates by defining functions for all +// syntactic elements, and recursively calling those, each function +// advancing the input stream and returning an AST node. Precedence +// of constructs (for example, the fact that `!x[1]` means `!(x[1])` +// instead of `(!x)[1]` is handled by the fact that the parser +// function that parses unary prefix operators is called first, and +// in turn calls the function that parses `[]` subscripts — that +// way, it'll receive the node for `x[1]` already parsed, and wraps +// *that* in the unary operator node. +// +// Acorn uses an [operator precedence parser][opp] to handle binary +// operator precedence, because it is much more compact than using +// the technique outlined above, which uses different, nesting +// functions to specify precedence, for all of the ten binary +// precedence levels that JavaScript defines. +// +// [opp]: http://en.wikipedia.org/wiki/Operator-precedence_parser + var pp$3 = Parser.prototype // Check if property name clashes with already added. @@ -2481,6 +2504,10 @@ pp$5.finishNodeAt = function(node, type, pos, loc) { return finishNodeAt.call(this, node, type, pos, loc) } +// The algorithm used to determine whether a regexp can appear at a +// given point in the program is loosely based on sweet.js' approach. +// See https://github.com/mozilla/sweet.js/wiki/design + var TokContext = function TokContext(token, isExpr, preserveSpace, override) { this.token = token this.isExpr = !!isExpr @@ -3290,7 +3317,28 @@ pp$7.readWord = function() { return this.finishToken(type, word) } -var version = "4.0.3" +// Acorn is a tiny, fast JavaScript parser written in JavaScript. +// +// Acorn was written by Marijn Haverbeke, Ingvar Stepanyan, and +// various contributors and released under an MIT license. +// +// Git repositories for Acorn are available at +// +// http://marijnhaverbeke.nl/git/acorn +// https://github.com/ternjs/acorn.git +// +// Please use the [github bug tracker][ghbt] to report issues. +// +// [ghbt]: https://github.com/ternjs/acorn/issues +// +// This file defines the main parser interface. The library also comes +// with a [error-tolerant parser][dammit] and an +// [abstract syntax tree walker][walk], defined in other files. +// +// [dammit]: acorn_loose.js +// [walk]: util/walk.js + +var version = "4.0.4" // The main exported interface (under `self.acorn` when in the // browser) is a `parse` function that takes a code string and diff --git a/tools/eslint/node_modules/acorn/dist/acorn.js b/tools/eslint/node_modules/acorn/dist/acorn.js index 0fc4086bb72fb6..ea572b3ebd3f4b 100644 --- a/tools/eslint/node_modules/acorn/dist/acorn.js +++ b/tools/eslint/node_modules/acorn/dist/acorn.js @@ -2,3362 +2,3410 @@ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (factory((global.acorn = global.acorn || {}))); -}(this, function (exports) { 'use strict'; - - // Reserved word lists for various dialects of the language - - var reservedWords = { - 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile", - 5: "class enum extends super const export import", - 6: "enum", - strict: "implements interface let package private protected public static yield", - strictBind: "eval arguments" - } - - // And the keywords - - var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this" +}(this, (function (exports) { 'use strict'; + +// Reserved word lists for various dialects of the language + +var reservedWords = { + 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile", + 5: "class enum extends super const export import", + 6: "enum", + strict: "implements interface let package private protected public static yield", + strictBind: "eval arguments" +} + +// And the keywords + +var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this" + +var keywords = { + 5: ecma5AndLessKeywords, + 6: ecma5AndLessKeywords + " const class extends export import super" +} + +// ## Character categories + +// Big ugly regular expressions that match characters in the +// whitespace, identifier, and identifier-start categories. These +// are only applied when a character is found to actually have a +// code point above 128. +// Generated by `bin/generate-identifier-regex.js`. + +var nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0-\u08b4\u08b6-\u08bd\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fd5\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7ae\ua7b0-\ua7b7\ua7f7-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab65\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc" +var nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d4-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c03\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d01-\u0d03\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf2-\u1cf4\u1cf8\u1cf9\u1dc0-\u1df5\u1dfb-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua900-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f" + +var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]") +var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]") + +nonASCIIidentifierStartChars = nonASCIIidentifierChars = null + +// These are a run-length and offset encoded representation of the +// >0xffff code points that are a valid part of identifiers. The +// offset starts at 0x10000, and each pair of numbers represents an +// offset to the next range, and then a size of the range. They were +// generated by bin/generate-identifier-regex.js +var astralIdentifierStartCodes = [0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,17,26,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,26,45,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,785,52,76,44,33,24,27,35,42,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,85,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,54,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,86,25,391,63,32,0,449,56,264,8,2,36,18,0,50,29,881,921,103,110,18,195,2749,1070,4050,582,8634,568,8,30,114,29,19,47,17,3,32,20,6,18,881,68,12,0,67,12,65,0,32,6124,20,754,9486,1,3071,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,4149,196,60,67,1213,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42710,42,4148,12,221,3,5761,10591,541] +var astralIdentifierCodes = [509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,1306,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,52,0,13,2,49,13,10,2,4,9,83,11,7,0,161,11,6,9,7,3,57,0,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,87,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,423,9,838,7,2,7,17,9,57,21,2,13,19882,9,135,4,60,6,26,9,1016,45,17,3,19723,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,2214,6,110,6,6,9,792487,239] + +// This has a complexity linear to the value of the code. The +// assumption is that looking up astral identifier characters is +// rare. +function isInAstralSet(code, set) { + var pos = 0x10000 + for (var i = 0; i < set.length; i += 2) { + pos += set[i] + if (pos > code) return false + pos += set[i + 1] + if (pos >= code) return true + } +} + +// Test whether a given character code starts an identifier. + +function isIdentifierStart(code, astral) { + if (code < 65) return code === 36 + if (code < 91) return true + if (code < 97) return code === 95 + if (code < 123) return true + if (code <= 0xffff) return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) + if (astral === false) return false + return isInAstralSet(code, astralIdentifierStartCodes) +} + +// Test whether a given character is part of an identifier. + +function isIdentifierChar(code, astral) { + if (code < 48) return code === 36 + if (code < 58) return true + if (code < 65) return false + if (code < 91) return true + if (code < 97) return code === 95 + if (code < 123) return true + if (code <= 0xffff) return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) + if (astral === false) return false + return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes) +} + +// ## Token types + +// The assignment of fine-grained, information-carrying type objects +// allows the tokenizer to store the information it has about a +// token in a way that is very cheap for the parser to look up. + +// All token type variables start with an underscore, to make them +// easy to recognize. + +// The `beforeExpr` property is used to disambiguate between regular +// expressions and divisions. It is set on all token types that can +// be followed by an expression (thus, a slash after them would be a +// regular expression). +// +// The `startsExpr` property is used to check if the token ends a +// `yield` expression. It is set on all token types that either can +// directly start an expression (like a quotation mark) or can +// continue an expression (like the body of a string). +// +// `isLoop` marks a keyword as starting a loop, which is important +// to know when parsing a label, in order to allow or disallow +// continue jumps to that label. + +var TokenType = function TokenType(label, conf) { + if ( conf === void 0 ) conf = {}; + + this.label = label + this.keyword = conf.keyword + this.beforeExpr = !!conf.beforeExpr + this.startsExpr = !!conf.startsExpr + this.isLoop = !!conf.isLoop + this.isAssign = !!conf.isAssign + this.prefix = !!conf.prefix + this.postfix = !!conf.postfix + this.binop = conf.binop || null + this.updateContext = null +}; + +function binop(name, prec) { + return new TokenType(name, {beforeExpr: true, binop: prec}) +} +var beforeExpr = {beforeExpr: true}; +var startsExpr = {startsExpr: true}; +// Map keyword names to token types. + +var keywordTypes = {} + +// Succinct definitions of keyword token types +function kw(name, options) { + if ( options === void 0 ) options = {}; + + options.keyword = name + return keywordTypes[name] = new TokenType(name, options) +} + +var tt = { + num: new TokenType("num", startsExpr), + regexp: new TokenType("regexp", startsExpr), + string: new TokenType("string", startsExpr), + name: new TokenType("name", startsExpr), + eof: new TokenType("eof"), + + // Punctuation token types. + bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}), + bracketR: new TokenType("]"), + braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}), + braceR: new TokenType("}"), + parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}), + parenR: new TokenType(")"), + comma: new TokenType(",", beforeExpr), + semi: new TokenType(";", beforeExpr), + colon: new TokenType(":", beforeExpr), + dot: new TokenType("."), + question: new TokenType("?", beforeExpr), + arrow: new TokenType("=>", beforeExpr), + template: new TokenType("template"), + ellipsis: new TokenType("...", beforeExpr), + backQuote: new TokenType("`", startsExpr), + dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}), + + // Operators. These carry several kinds of properties to help the + // parser use them properly (the presence of these properties is + // what categorizes them as operators). + // + // `binop`, when present, specifies that this operator is a binary + // operator, and will refer to its precedence. + // + // `prefix` and `postfix` mark the operator as a prefix or postfix + // unary operator. + // + // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as + // binary operators with a very low precedence, that should result + // in AssignmentExpression nodes. + + eq: new TokenType("=", {beforeExpr: true, isAssign: true}), + assign: new TokenType("_=", {beforeExpr: true, isAssign: true}), + incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}), + prefix: new TokenType("prefix", {beforeExpr: true, prefix: true, startsExpr: true}), + logicalOR: binop("||", 1), + logicalAND: binop("&&", 2), + bitwiseOR: binop("|", 3), + bitwiseXOR: binop("^", 4), + bitwiseAND: binop("&", 5), + equality: binop("==/!=", 6), + relational: binop("", 7), + bitShift: binop("<>", 8), + plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}), + modulo: binop("%", 10), + star: binop("*", 10), + slash: binop("/", 10), + starstar: new TokenType("**", {beforeExpr: true}), + + // Keyword token types. + _break: kw("break"), + _case: kw("case", beforeExpr), + _catch: kw("catch"), + _continue: kw("continue"), + _debugger: kw("debugger"), + _default: kw("default", beforeExpr), + _do: kw("do", {isLoop: true, beforeExpr: true}), + _else: kw("else", beforeExpr), + _finally: kw("finally"), + _for: kw("for", {isLoop: true}), + _function: kw("function", startsExpr), + _if: kw("if"), + _return: kw("return", beforeExpr), + _switch: kw("switch"), + _throw: kw("throw", beforeExpr), + _try: kw("try"), + _var: kw("var"), + _const: kw("const"), + _while: kw("while", {isLoop: true}), + _with: kw("with"), + _new: kw("new", {beforeExpr: true, startsExpr: true}), + _this: kw("this", startsExpr), + _super: kw("super", startsExpr), + _class: kw("class"), + _extends: kw("extends", beforeExpr), + _export: kw("export"), + _import: kw("import"), + _null: kw("null", startsExpr), + _true: kw("true", startsExpr), + _false: kw("false", startsExpr), + _in: kw("in", {beforeExpr: true, binop: 7}), + _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}), + _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}), + _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}), + _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true}) +} + +// Matches a whole line break (where CRLF is considered a single +// line break). Used to count lines. + +var lineBreak = /\r\n?|\n|\u2028|\u2029/ +var lineBreakG = new RegExp(lineBreak.source, "g") + +function isNewLine(code) { + return code === 10 || code === 13 || code === 0x2028 || code === 0x2029 +} + +var nonASCIIwhitespace = /[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/ + +var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g + +function isArray(obj) { + return Object.prototype.toString.call(obj) === "[object Array]" +} + +// Checks if an object has a property. + +function has(obj, propName) { + return Object.prototype.hasOwnProperty.call(obj, propName) +} + +// These are used when `options.locations` is on, for the +// `startLoc` and `endLoc` properties. + +var Position = function Position(line, col) { + this.line = line + this.column = col +}; + +Position.prototype.offset = function offset (n) { + return new Position(this.line, this.column + n) +}; + +var SourceLocation = function SourceLocation(p, start, end) { + this.start = start + this.end = end + if (p.sourceFile !== null) this.source = p.sourceFile +}; + +// The `getLineInfo` function is mostly useful when the +// `locations` option is off (for performance reasons) and you +// want to find the line/column position for a given character +// offset. `input` should be the code string that the offset refers +// into. + +function getLineInfo(input, offset) { + for (var line = 1, cur = 0;;) { + lineBreakG.lastIndex = cur + var match = lineBreakG.exec(input) + if (match && match.index < offset) { + ++line + cur = match.index + match[0].length + } else { + return new Position(line, offset - cur) + } + } +} + +// A second optional argument can be given to further configure +// the parser process. These options are recognized: + +var defaultOptions = { + // `ecmaVersion` indicates the ECMAScript version to parse. Must + // be either 3, 5, 6 (2015), 7 (2016), or 8 (2017). This influences support + // for strict mode, the set of reserved words, and support for + // new syntax features. The default is 7. + ecmaVersion: 7, + // `sourceType` indicates the mode the code should be parsed in. + // Can be either `"script"` or `"module"`. This influences global + // strict mode and parsing of `import` and `export` declarations. + sourceType: "script", + // `onInsertedSemicolon` can be a callback that will be called + // when a semicolon is automatically inserted. It will be passed + // th position of the comma as an offset, and if `locations` is + // enabled, it is given the location as a `{line, column}` object + // as second argument. + onInsertedSemicolon: null, + // `onTrailingComma` is similar to `onInsertedSemicolon`, but for + // trailing commas. + onTrailingComma: null, + // By default, reserved words are only enforced if ecmaVersion >= 5. + // Set `allowReserved` to a boolean value to explicitly turn this on + // an off. When this option has the value "never", reserved words + // and keywords can also not be used as property names. + allowReserved: null, + // When enabled, a return at the top level is not considered an + // error. + allowReturnOutsideFunction: false, + // When enabled, import/export statements are not constrained to + // appearing at the top of the program. + allowImportExportEverywhere: false, + // When enabled, hashbang directive in the beginning of file + // is allowed and treated as a line comment. + allowHashBang: false, + // When `locations` is on, `loc` properties holding objects with + // `start` and `end` properties in `{line, column}` form (with + // line being 1-based and column 0-based) will be attached to the + // nodes. + locations: false, + // A function can be passed as `onToken` option, which will + // cause Acorn to call that function with object in the same + // format as tokens returned from `tokenizer().getToken()`. Note + // that you are not allowed to call the parser from the + // callback—that will corrupt its internal state. + onToken: null, + // A function can be passed as `onComment` option, which will + // cause Acorn to call that function with `(block, text, start, + // end)` parameters whenever a comment is skipped. `block` is a + // boolean indicating whether this is a block (`/* */`) comment, + // `text` is the content of the comment, and `start` and `end` are + // character offsets that denote the start and end of the comment. + // When the `locations` option is on, two more parameters are + // passed, the full `{line, column}` locations of the start and + // end of the comments. Note that you are not allowed to call the + // parser from the callback—that will corrupt its internal state. + onComment: null, + // Nodes have their start and end characters offsets recorded in + // `start` and `end` properties (directly on the node, rather than + // the `loc` object, which holds line/column data. To also add a + // [semi-standardized][range] `range` property holding a `[start, + // end]` array with the same numbers, set the `ranges` option to + // `true`. + // + // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678 + ranges: false, + // It is possible to parse multiple files into a single AST by + // passing the tree produced by parsing the first file as + // `program` option in subsequent parses. This will add the + // toplevel forms of the parsed file to the `Program` (top) node + // of an existing parse tree. + program: null, + // When `locations` is on, you can pass this to record the source + // file in every node's `loc` object. + sourceFile: null, + // This value, if given, is stored in every node, whether + // `locations` is on or off. + directSourceFile: null, + // When enabled, parenthesized expressions are represented by + // (non-standard) ParenthesizedExpression nodes + preserveParens: false, + plugins: {} +} + +// Interpret and default an options object + +function getOptions(opts) { + var options = {} + + for (var opt in defaultOptions) + options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt] + + if (options.ecmaVersion >= 2015) + options.ecmaVersion -= 2009 + + if (options.allowReserved == null) + options.allowReserved = options.ecmaVersion < 5 + + if (isArray(options.onToken)) { + var tokens = options.onToken + options.onToken = function (token) { return tokens.push(token); } + } + if (isArray(options.onComment)) + options.onComment = pushComment(options, options.onComment) + + return options +} + +function pushComment(options, array) { + return function (block, text, start, end, startLoc, endLoc) { + var comment = { + type: block ? 'Block' : 'Line', + value: text, + start: start, + end: end + } + if (options.locations) + comment.loc = new SourceLocation(this, startLoc, endLoc) + if (options.ranges) + comment.range = [start, end] + array.push(comment) + } +} + +// Registered plugins +var plugins = {} + +function keywordRegexp(words) { + return new RegExp("^(" + words.replace(/ /g, "|") + ")$") +} + +var Parser = function Parser(options, input, startPos) { + this.options = options = getOptions(options) + this.sourceFile = options.sourceFile + this.keywords = keywordRegexp(keywords[options.ecmaVersion >= 6 ? 6 : 5]) + var reserved = "" + if (!options.allowReserved) { + for (var v = options.ecmaVersion;; v--) + if (reserved = reservedWords[v]) break + if (options.sourceType == "module") reserved += " await" + } + this.reservedWords = keywordRegexp(reserved) + var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict + this.reservedWordsStrict = keywordRegexp(reservedStrict) + this.reservedWordsStrictBind = keywordRegexp(reservedStrict + " " + reservedWords.strictBind) + this.input = String(input) + + // Used to signal to callers of `readWord1` whether the word + // contained any escape sequences. This is needed because words with + // escape sequences must not be interpreted as keywords. + this.containsEsc = false + + // Load plugins + this.loadPlugins(options.plugins) + + // Set up token state + + // The current position of the tokenizer in the input. + if (startPos) { + this.pos = startPos + this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1 + this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length + } else { + this.pos = this.lineStart = 0 + this.curLine = 1 + } + + // Properties of the current token: + // Its type + this.type = tt.eof + // For tokens that include more information than their type, the value + this.value = null + // Its start and end offset + this.start = this.end = this.pos + // And, if locations are used, the {line, column} object + // corresponding to those offsets + this.startLoc = this.endLoc = this.curPosition() + + // Position information for the previous token + this.lastTokEndLoc = this.lastTokStartLoc = null + this.lastTokStart = this.lastTokEnd = this.pos + + // The context stack is used to superficially track syntactic + // context to predict whether a regular expression is allowed in a + // given position. + this.context = this.initialContext() + this.exprAllowed = true + + // Figure out if it's a module code. + this.strict = this.inModule = options.sourceType === "module" + + // Used to signify the start of a potential arrow function + this.potentialArrowAt = -1 + + // Flags to track whether we are in a function, a generator, an async function. + this.inFunction = this.inGenerator = this.inAsync = false + // Positions to delayed-check that yield/await does not exist in default parameters. + this.yieldPos = this.awaitPos = 0 + // Labels in scope. + this.labels = [] + + // If enabled, skip leading hashbang line. + if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === '#!') + this.skipLineComment(2) +}; + +// DEPRECATED Kept for backwards compatibility until 3.0 in case a plugin uses them +Parser.prototype.isKeyword = function isKeyword (word) { return this.keywords.test(word) }; +Parser.prototype.isReservedWord = function isReservedWord (word) { return this.reservedWords.test(word) }; + +Parser.prototype.extend = function extend (name, f) { + this[name] = f(this[name]) +}; + +Parser.prototype.loadPlugins = function loadPlugins (pluginConfigs) { + var this$1 = this; - var keywords = { - 5: ecma5AndLessKeywords, - 6: ecma5AndLessKeywords + " const class extends export import super" + for (var name in pluginConfigs) { + var plugin = plugins[name] + if (!plugin) throw new Error("Plugin '" + name + "' not found") + plugin(this$1, pluginConfigs[name]) } +}; - // ## Character categories +Parser.prototype.parse = function parse () { + var node = this.options.program || this.startNode() + this.nextToken() + return this.parseTopLevel(node) +}; - // Big ugly regular expressions that match characters in the - // whitespace, identifier, and identifier-start categories. These - // are only applied when a character is found to actually have a - // code point above 128. - // Generated by `bin/generate-identifier-regex.js`. +var pp = Parser.prototype - var nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0-\u08b4\u08b6-\u08bd\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fd5\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7ae\ua7b0-\ua7b7\ua7f7-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab65\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc" - var nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d4-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c03\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d01-\u0d03\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf2-\u1cf4\u1cf8\u1cf9\u1dc0-\u1df5\u1dfb-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua900-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f" +// ## Parser utilities - var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]") - var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]") +// Test whether a statement node is the string literal `"use strict"`. - nonASCIIidentifierStartChars = nonASCIIidentifierChars = null +pp.isUseStrict = function(stmt) { + return this.options.ecmaVersion >= 5 && stmt.type === "ExpressionStatement" && + stmt.expression.type === "Literal" && + stmt.expression.raw.slice(1, -1) === "use strict" +} - // These are a run-length and offset encoded representation of the - // >0xffff code points that are a valid part of identifiers. The - // offset starts at 0x10000, and each pair of numbers represents an - // offset to the next range, and then a size of the range. They were - // generated by bin/generate-identifier-regex.js - var astralIdentifierStartCodes = [0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,17,26,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,26,45,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,785,52,76,44,33,24,27,35,42,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,85,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,54,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,86,25,391,63,32,0,449,56,264,8,2,36,18,0,50,29,881,921,103,110,18,195,2749,1070,4050,582,8634,568,8,30,114,29,19,47,17,3,32,20,6,18,881,68,12,0,67,12,65,0,32,6124,20,754,9486,1,3071,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,4149,196,60,67,1213,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42710,42,4148,12,221,3,5761,10591,541] - var astralIdentifierCodes = [509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,1306,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,52,0,13,2,49,13,10,2,4,9,83,11,7,0,161,11,6,9,7,3,57,0,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,87,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,423,9,838,7,2,7,17,9,57,21,2,13,19882,9,135,4,60,6,26,9,1016,45,17,3,19723,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,2214,6,110,6,6,9,792487,239] +// Predicate that tests whether the next token is of the given +// type, and if yes, consumes it as a side effect. - // This has a complexity linear to the value of the code. The - // assumption is that looking up astral identifier characters is - // rare. - function isInAstralSet(code, set) { - var pos = 0x10000 - for (var i = 0; i < set.length; i += 2) { - pos += set[i] - if (pos > code) return false - pos += set[i + 1] - if (pos >= code) return true - } +pp.eat = function(type) { + if (this.type === type) { + this.next() + return true + } else { + return false } +} - // Test whether a given character code starts an identifier. - - function isIdentifierStart(code, astral) { - if (code < 65) return code === 36 - if (code < 91) return true - if (code < 97) return code === 95 - if (code < 123) return true - if (code <= 0xffff) return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) - if (astral === false) return false - return isInAstralSet(code, astralIdentifierStartCodes) - } +// Tests whether parsed token is a contextual keyword. - // Test whether a given character is part of an identifier. +pp.isContextual = function(name) { + return this.type === tt.name && this.value === name +} - function isIdentifierChar(code, astral) { - if (code < 48) return code === 36 - if (code < 58) return true - if (code < 65) return false - if (code < 91) return true - if (code < 97) return code === 95 - if (code < 123) return true - if (code <= 0xffff) return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) - if (astral === false) return false - return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes) - } +// Consumes contextual keyword if possible. - // ## Token types +pp.eatContextual = function(name) { + return this.value === name && this.eat(tt.name) +} - // The assignment of fine-grained, information-carrying type objects - // allows the tokenizer to store the information it has about a - // token in a way that is very cheap for the parser to look up. +// Asserts that following token is given contextual keyword. - // All token type variables start with an underscore, to make them - // easy to recognize. +pp.expectContextual = function(name) { + if (!this.eatContextual(name)) this.unexpected() +} - // The `beforeExpr` property is used to disambiguate between regular - // expressions and divisions. It is set on all token types that can - // be followed by an expression (thus, a slash after them would be a - // regular expression). - // - // The `startsExpr` property is used to check if the token ends a - // `yield` expression. It is set on all token types that either can - // directly start an expression (like a quotation mark) or can - // continue an expression (like the body of a string). - // - // `isLoop` marks a keyword as starting a loop, which is important - // to know when parsing a label, in order to allow or disallow - // continue jumps to that label. - - var TokenType = function TokenType(label, conf) { - if ( conf === void 0 ) conf = {}; - - this.label = label - this.keyword = conf.keyword - this.beforeExpr = !!conf.beforeExpr - this.startsExpr = !!conf.startsExpr - this.isLoop = !!conf.isLoop - this.isAssign = !!conf.isAssign - this.prefix = !!conf.prefix - this.postfix = !!conf.postfix - this.binop = conf.binop || null - this.updateContext = null - }; - - function binop(name, prec) { - return new TokenType(name, {beforeExpr: true, binop: prec}) - } - var beforeExpr = {beforeExpr: true}; - var startsExpr = {startsExpr: true}; - // Map keyword names to token types. - - var keywordTypes = {} - - // Succinct definitions of keyword token types - function kw(name, options) { - if ( options === void 0 ) options = {}; - - options.keyword = name - return keywordTypes[name] = new TokenType(name, options) - } - - var tt = { - num: new TokenType("num", startsExpr), - regexp: new TokenType("regexp", startsExpr), - string: new TokenType("string", startsExpr), - name: new TokenType("name", startsExpr), - eof: new TokenType("eof"), - - // Punctuation token types. - bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}), - bracketR: new TokenType("]"), - braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}), - braceR: new TokenType("}"), - parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}), - parenR: new TokenType(")"), - comma: new TokenType(",", beforeExpr), - semi: new TokenType(";", beforeExpr), - colon: new TokenType(":", beforeExpr), - dot: new TokenType("."), - question: new TokenType("?", beforeExpr), - arrow: new TokenType("=>", beforeExpr), - template: new TokenType("template"), - ellipsis: new TokenType("...", beforeExpr), - backQuote: new TokenType("`", startsExpr), - dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}), - - // Operators. These carry several kinds of properties to help the - // parser use them properly (the presence of these properties is - // what categorizes them as operators). - // - // `binop`, when present, specifies that this operator is a binary - // operator, and will refer to its precedence. - // - // `prefix` and `postfix` mark the operator as a prefix or postfix - // unary operator. - // - // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as - // binary operators with a very low precedence, that should result - // in AssignmentExpression nodes. - - eq: new TokenType("=", {beforeExpr: true, isAssign: true}), - assign: new TokenType("_=", {beforeExpr: true, isAssign: true}), - incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}), - prefix: new TokenType("prefix", {beforeExpr: true, prefix: true, startsExpr: true}), - logicalOR: binop("||", 1), - logicalAND: binop("&&", 2), - bitwiseOR: binop("|", 3), - bitwiseXOR: binop("^", 4), - bitwiseAND: binop("&", 5), - equality: binop("==/!=", 6), - relational: binop("", 7), - bitShift: binop("<>", 8), - plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}), - modulo: binop("%", 10), - star: binop("*", 10), - slash: binop("/", 10), - starstar: new TokenType("**", {beforeExpr: true}), - - // Keyword token types. - _break: kw("break"), - _case: kw("case", beforeExpr), - _catch: kw("catch"), - _continue: kw("continue"), - _debugger: kw("debugger"), - _default: kw("default", beforeExpr), - _do: kw("do", {isLoop: true, beforeExpr: true}), - _else: kw("else", beforeExpr), - _finally: kw("finally"), - _for: kw("for", {isLoop: true}), - _function: kw("function", startsExpr), - _if: kw("if"), - _return: kw("return", beforeExpr), - _switch: kw("switch"), - _throw: kw("throw", beforeExpr), - _try: kw("try"), - _var: kw("var"), - _const: kw("const"), - _while: kw("while", {isLoop: true}), - _with: kw("with"), - _new: kw("new", {beforeExpr: true, startsExpr: true}), - _this: kw("this", startsExpr), - _super: kw("super", startsExpr), - _class: kw("class"), - _extends: kw("extends", beforeExpr), - _export: kw("export"), - _import: kw("import"), - _null: kw("null", startsExpr), - _true: kw("true", startsExpr), - _false: kw("false", startsExpr), - _in: kw("in", {beforeExpr: true, binop: 7}), - _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}), - _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}), - _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}), - _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true}) - } - - // Matches a whole line break (where CRLF is considered a single - // line break). Used to count lines. - - var lineBreak = /\r\n?|\n|\u2028|\u2029/ - var lineBreakG = new RegExp(lineBreak.source, "g") - - function isNewLine(code) { - return code === 10 || code === 13 || code === 0x2028 || code === 0x2029 - } - - var nonASCIIwhitespace = /[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/ - - var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g - - function isArray(obj) { - return Object.prototype.toString.call(obj) === "[object Array]" - } - - // Checks if an object has a property. - - function has(obj, propName) { - return Object.prototype.hasOwnProperty.call(obj, propName) - } - - // These are used when `options.locations` is on, for the - // `startLoc` and `endLoc` properties. - - var Position = function Position(line, col) { - this.line = line - this.column = col - }; - - Position.prototype.offset = function offset (n) { - return new Position(this.line, this.column + n) - }; - - var SourceLocation = function SourceLocation(p, start, end) { - this.start = start - this.end = end - if (p.sourceFile !== null) this.source = p.sourceFile - }; - - // The `getLineInfo` function is mostly useful when the - // `locations` option is off (for performance reasons) and you - // want to find the line/column position for a given character - // offset. `input` should be the code string that the offset refers - // into. - - function getLineInfo(input, offset) { - for (var line = 1, cur = 0;;) { - lineBreakG.lastIndex = cur - var match = lineBreakG.exec(input) - if (match && match.index < offset) { - ++line - cur = match.index + match[0].length - } else { - return new Position(line, offset - cur) - } - } - } +// Test whether a semicolon can be inserted at the current position. - // A second optional argument can be given to further configure - // the parser process. These options are recognized: - - var defaultOptions = { - // `ecmaVersion` indicates the ECMAScript version to parse. Must - // be either 3, 5, 6 (2015), 7 (2016), or 8 (2017). This influences support - // for strict mode, the set of reserved words, and support for - // new syntax features. The default is 7. - ecmaVersion: 7, - // `sourceType` indicates the mode the code should be parsed in. - // Can be either `"script"` or `"module"`. This influences global - // strict mode and parsing of `import` and `export` declarations. - sourceType: "script", - // `onInsertedSemicolon` can be a callback that will be called - // when a semicolon is automatically inserted. It will be passed - // th position of the comma as an offset, and if `locations` is - // enabled, it is given the location as a `{line, column}` object - // as second argument. - onInsertedSemicolon: null, - // `onTrailingComma` is similar to `onInsertedSemicolon`, but for - // trailing commas. - onTrailingComma: null, - // By default, reserved words are only enforced if ecmaVersion >= 5. - // Set `allowReserved` to a boolean value to explicitly turn this on - // an off. When this option has the value "never", reserved words - // and keywords can also not be used as property names. - allowReserved: null, - // When enabled, a return at the top level is not considered an - // error. - allowReturnOutsideFunction: false, - // When enabled, import/export statements are not constrained to - // appearing at the top of the program. - allowImportExportEverywhere: false, - // When enabled, hashbang directive in the beginning of file - // is allowed and treated as a line comment. - allowHashBang: false, - // When `locations` is on, `loc` properties holding objects with - // `start` and `end` properties in `{line, column}` form (with - // line being 1-based and column 0-based) will be attached to the - // nodes. - locations: false, - // A function can be passed as `onToken` option, which will - // cause Acorn to call that function with object in the same - // format as tokens returned from `tokenizer().getToken()`. Note - // that you are not allowed to call the parser from the - // callback—that will corrupt its internal state. - onToken: null, - // A function can be passed as `onComment` option, which will - // cause Acorn to call that function with `(block, text, start, - // end)` parameters whenever a comment is skipped. `block` is a - // boolean indicating whether this is a block (`/* */`) comment, - // `text` is the content of the comment, and `start` and `end` are - // character offsets that denote the start and end of the comment. - // When the `locations` option is on, two more parameters are - // passed, the full `{line, column}` locations of the start and - // end of the comments. Note that you are not allowed to call the - // parser from the callback—that will corrupt its internal state. - onComment: null, - // Nodes have their start and end characters offsets recorded in - // `start` and `end` properties (directly on the node, rather than - // the `loc` object, which holds line/column data. To also add a - // [semi-standardized][range] `range` property holding a `[start, - // end]` array with the same numbers, set the `ranges` option to - // `true`. - // - // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678 - ranges: false, - // It is possible to parse multiple files into a single AST by - // passing the tree produced by parsing the first file as - // `program` option in subsequent parses. This will add the - // toplevel forms of the parsed file to the `Program` (top) node - // of an existing parse tree. - program: null, - // When `locations` is on, you can pass this to record the source - // file in every node's `loc` object. - sourceFile: null, - // This value, if given, is stored in every node, whether - // `locations` is on or off. - directSourceFile: null, - // When enabled, parenthesized expressions are represented by - // (non-standard) ParenthesizedExpression nodes - preserveParens: false, - plugins: {} - } - - // Interpret and default an options object - - function getOptions(opts) { - var options = {} - - for (var opt in defaultOptions) - options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt] - - if (options.ecmaVersion >= 2015) - options.ecmaVersion -= 2009 - - if (options.allowReserved == null) - options.allowReserved = options.ecmaVersion < 5 - - if (isArray(options.onToken)) { - var tokens = options.onToken - options.onToken = function (token) { return tokens.push(token); } - } - if (isArray(options.onComment)) - options.onComment = pushComment(options, options.onComment) +pp.canInsertSemicolon = function() { + return this.type === tt.eof || + this.type === tt.braceR || + lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) +} - return options +pp.insertSemicolon = function() { + if (this.canInsertSemicolon()) { + if (this.options.onInsertedSemicolon) + this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc) + return true } +} - function pushComment(options, array) { - return function (block, text, start, end, startLoc, endLoc) { - var comment = { - type: block ? 'Block' : 'Line', - value: text, - start: start, - end: end - } - if (options.locations) - comment.loc = new SourceLocation(this, startLoc, endLoc) - if (options.ranges) - comment.range = [start, end] - array.push(comment) - } - } +// Consume a semicolon, or, failing that, see if we are allowed to +// pretend that there is a semicolon at this position. - // Registered plugins - var plugins = {} +pp.semicolon = function() { + if (!this.eat(tt.semi) && !this.insertSemicolon()) this.unexpected() +} - function keywordRegexp(words) { - return new RegExp("^(" + words.replace(/ /g, "|") + ")$") +pp.afterTrailingComma = function(tokType, notNext) { + if (this.type == tokType) { + if (this.options.onTrailingComma) + this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc) + if (!notNext) + this.next() + return true } +} - var Parser = function Parser(options, input, startPos) { - this.options = options = getOptions(options) - this.sourceFile = options.sourceFile - this.keywords = keywordRegexp(keywords[options.ecmaVersion >= 6 ? 6 : 5]) - var reserved = "" - if (!options.allowReserved) { - for (var v = options.ecmaVersion;; v--) - if (reserved = reservedWords[v]) break - if (options.sourceType == "module") reserved += " await" - } - this.reservedWords = keywordRegexp(reserved) - var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict - this.reservedWordsStrict = keywordRegexp(reservedStrict) - this.reservedWordsStrictBind = keywordRegexp(reservedStrict + " " + reservedWords.strictBind) - this.input = String(input) - - // Used to signal to callers of `readWord1` whether the word - // contained any escape sequences. This is needed because words with - // escape sequences must not be interpreted as keywords. - this.containsEsc = false - - // Load plugins - this.loadPlugins(options.plugins) - - // Set up token state - - // The current position of the tokenizer in the input. - if (startPos) { - this.pos = startPos - this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1 - this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length - } else { - this.pos = this.lineStart = 0 - this.curLine = 1 - } - - // Properties of the current token: - // Its type - this.type = tt.eof - // For tokens that include more information than their type, the value - this.value = null - // Its start and end offset - this.start = this.end = this.pos - // And, if locations are used, the {line, column} object - // corresponding to those offsets - this.startLoc = this.endLoc = this.curPosition() - - // Position information for the previous token - this.lastTokEndLoc = this.lastTokStartLoc = null - this.lastTokStart = this.lastTokEnd = this.pos - - // The context stack is used to superficially track syntactic - // context to predict whether a regular expression is allowed in a - // given position. - this.context = this.initialContext() - this.exprAllowed = true - - // Figure out if it's a module code. - this.strict = this.inModule = options.sourceType === "module" +// Expect a token of a given type. If found, consume it, otherwise, +// raise an unexpected token error. - // Used to signify the start of a potential arrow function - this.potentialArrowAt = -1 +pp.expect = function(type) { + this.eat(type) || this.unexpected() +} - // Flags to track whether we are in a function, a generator, an async function. - this.inFunction = this.inGenerator = this.inAsync = false - // Positions to delayed-check that yield/await does not exist in default parameters. - this.yieldPos = this.awaitPos = 0 - // Labels in scope. - this.labels = [] +// Raise an unexpected token error. - // If enabled, skip leading hashbang line. - if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === '#!') - this.skipLineComment(2) - }; +pp.unexpected = function(pos) { + this.raise(pos != null ? pos : this.start, "Unexpected token") +} - // DEPRECATED Kept for backwards compatibility until 3.0 in case a plugin uses them - Parser.prototype.isKeyword = function isKeyword (word) { return this.keywords.test(word) }; - Parser.prototype.isReservedWord = function isReservedWord (word) { return this.reservedWords.test(word) }; +var DestructuringErrors = function DestructuringErrors() { + this.shorthandAssign = 0 + this.trailingComma = 0 +}; - Parser.prototype.extend = function extend (name, f) { - this[name] = f(this[name]) - }; +pp.checkPatternErrors = function(refDestructuringErrors, andThrow) { + var trailing = refDestructuringErrors && refDestructuringErrors.trailingComma + if (!andThrow) return !!trailing + if (trailing) this.raise(trailing, "Comma is not permitted after the rest element") +} - Parser.prototype.loadPlugins = function loadPlugins (pluginConfigs) { - var this$1 = this; +pp.checkExpressionErrors = function(refDestructuringErrors, andThrow) { + var pos = refDestructuringErrors && refDestructuringErrors.shorthandAssign + if (!andThrow) return !!pos + if (pos) this.raise(pos, "Shorthand property assignments are valid only in destructuring patterns") +} - for (var name in pluginConfigs) { - var plugin = plugins[name] - if (!plugin) throw new Error("Plugin '" + name + "' not found") - plugin(this$1, pluginConfigs[name]) - } - }; +pp.checkYieldAwaitInDefaultParams = function() { + if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos)) + this.raise(this.yieldPos, "Yield expression cannot be a default value") + if (this.awaitPos) + this.raise(this.awaitPos, "Await expression cannot be a default value") +} - Parser.prototype.parse = function parse () { - var node = this.options.program || this.startNode() - this.nextToken() - return this.parseTopLevel(node) - }; +var pp$1 = Parser.prototype - var pp = Parser.prototype +// ### Statement parsing - // ## Parser utilities +// Parse a program. Initializes the parser, reads any number of +// statements, and wraps them in a Program node. Optionally takes a +// `program` argument. If present, the statements will be appended +// to its body instead of creating a new node. - // Test whether a statement node is the string literal `"use strict"`. +pp$1.parseTopLevel = function(node) { + var this$1 = this; - pp.isUseStrict = function(stmt) { - return this.options.ecmaVersion >= 5 && stmt.type === "ExpressionStatement" && - stmt.expression.type === "Literal" && - stmt.expression.raw.slice(1, -1) === "use strict" + var first = true, exports = {} + if (!node.body) node.body = [] + while (this.type !== tt.eof) { + var stmt = this$1.parseStatement(true, true, exports) + node.body.push(stmt) + if (first) { + if (this$1.isUseStrict(stmt)) this$1.setStrict(true) + first = false + } } + this.next() + if (this.options.ecmaVersion >= 6) { + node.sourceType = this.options.sourceType + } + return this.finishNode(node, "Program") +} + +var loopLabel = {kind: "loop"}; +var switchLabel = {kind: "switch"}; +pp$1.isLet = function() { + if (this.type !== tt.name || this.options.ecmaVersion < 6 || this.value != "let") return false + skipWhiteSpace.lastIndex = this.pos + var skip = skipWhiteSpace.exec(this.input) + var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next) + if (nextCh === 91 || nextCh == 123) return true // '{' and '[' + if (isIdentifierStart(nextCh, true)) { + for (var pos = next + 1; isIdentifierChar(this.input.charCodeAt(pos), true); ++pos) {} + var ident = this.input.slice(next, pos) + if (!this.isKeyword(ident)) return true + } + return false +} + +// check 'async [no LineTerminator here] function' +// - 'async /*foo*/ function' is OK. +// - 'async /*\n*/ function' is invalid. +pp$1.isAsyncFunction = function() { + if (this.type !== tt.name || this.options.ecmaVersion < 8 || this.value != "async") + return false - // Predicate that tests whether the next token is of the given - // type, and if yes, consumes it as a side effect. - - pp.eat = function(type) { - if (this.type === type) { + skipWhiteSpace.lastIndex = this.pos + var skip = skipWhiteSpace.exec(this.input) + var next = this.pos + skip[0].length + return !lineBreak.test(this.input.slice(this.pos, next)) && + this.input.slice(next, next + 8) === "function" && + (next + 8 == this.input.length || !isIdentifierChar(this.input.charAt(next + 8))) +} + +// Parse a single statement. +// +// If expecting a statement and finding a slash operator, parse a +// regular expression literal. This is to handle cases like +// `if (foo) /blah/.exec(foo)`, where looking at the previous token +// does not help. + +pp$1.parseStatement = function(declaration, topLevel, exports) { + var starttype = this.type, node = this.startNode(), kind + + if (this.isLet()) { + starttype = tt._var + kind = "let" + } + + // Most types of statements are recognized by the keyword they + // start with. Many are trivial to parse, some require a bit of + // complexity. + + switch (starttype) { + case tt._break: case tt._continue: return this.parseBreakContinueStatement(node, starttype.keyword) + case tt._debugger: return this.parseDebuggerStatement(node) + case tt._do: return this.parseDoStatement(node) + case tt._for: return this.parseForStatement(node) + case tt._function: + if (!declaration && this.options.ecmaVersion >= 6) this.unexpected() + return this.parseFunctionStatement(node, false) + case tt._class: + if (!declaration) this.unexpected() + return this.parseClass(node, true) + case tt._if: return this.parseIfStatement(node) + case tt._return: return this.parseReturnStatement(node) + case tt._switch: return this.parseSwitchStatement(node) + case tt._throw: return this.parseThrowStatement(node) + case tt._try: return this.parseTryStatement(node) + case tt._const: case tt._var: + kind = kind || this.value + if (!declaration && kind != "var") this.unexpected() + return this.parseVarStatement(node, kind) + case tt._while: return this.parseWhileStatement(node) + case tt._with: return this.parseWithStatement(node) + case tt.braceL: return this.parseBlock() + case tt.semi: return this.parseEmptyStatement(node) + case tt._export: + case tt._import: + if (!this.options.allowImportExportEverywhere) { + if (!topLevel) + this.raise(this.start, "'import' and 'export' may only appear at the top level") + if (!this.inModule) + this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'") + } + return starttype === tt._import ? this.parseImport(node) : this.parseExport(node, exports) + + // If the statement does not start with a statement keyword or a + // brace, it's an ExpressionStatement or LabeledStatement. We + // simply start parsing an expression, and afterwards, if the + // next token is a colon and the expression was a simple + // Identifier node, we switch to interpreting it as a label. + default: + if (this.isAsyncFunction() && declaration) { this.next() - return true - } else { - return false + return this.parseFunctionStatement(node, true) } + + var maybeName = this.value, expr = this.parseExpression() + if (starttype === tt.name && expr.type === "Identifier" && this.eat(tt.colon)) + return this.parseLabeledStatement(node, maybeName, expr) + else return this.parseExpressionStatement(node, expr) } +} - // Tests whether parsed token is a contextual keyword. +pp$1.parseBreakContinueStatement = function(node, keyword) { + var this$1 = this; - pp.isContextual = function(name) { - return this.type === tt.name && this.value === name + var isBreak = keyword == "break" + this.next() + if (this.eat(tt.semi) || this.insertSemicolon()) node.label = null + else if (this.type !== tt.name) this.unexpected() + else { + node.label = this.parseIdent() + this.semicolon() } - // Consumes contextual keyword if possible. - - pp.eatContextual = function(name) { - return this.value === name && this.eat(tt.name) + // Verify that there is an actual destination to break or + // continue to. + for (var i = 0; i < this.labels.length; ++i) { + var lab = this$1.labels[i] + if (node.label == null || lab.name === node.label.name) { + if (lab.kind != null && (isBreak || lab.kind === "loop")) break + if (node.label && isBreak) break + } + } + if (i === this.labels.length) this.raise(node.start, "Unsyntactic " + keyword) + return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement") +} + +pp$1.parseDebuggerStatement = function(node) { + this.next() + this.semicolon() + return this.finishNode(node, "DebuggerStatement") +} + +pp$1.parseDoStatement = function(node) { + this.next() + this.labels.push(loopLabel) + node.body = this.parseStatement(false) + this.labels.pop() + this.expect(tt._while) + node.test = this.parseParenExpression() + if (this.options.ecmaVersion >= 6) + this.eat(tt.semi) + else + this.semicolon() + return this.finishNode(node, "DoWhileStatement") +} + +// Disambiguating between a `for` and a `for`/`in` or `for`/`of` +// loop is non-trivial. Basically, we have to parse the init `var` +// statement or expression, disallowing the `in` operator (see +// the second parameter to `parseExpression`), and then check +// whether the next token is `in` or `of`. When there is no init +// part (semicolon immediately after the opening parenthesis), it +// is a regular `for` loop. + +pp$1.parseForStatement = function(node) { + this.next() + this.labels.push(loopLabel) + this.expect(tt.parenL) + if (this.type === tt.semi) return this.parseFor(node, null) + var isLet = this.isLet() + if (this.type === tt._var || this.type === tt._const || isLet) { + var init$1 = this.startNode(), kind = isLet ? "let" : this.value + this.next() + this.parseVar(init$1, true, kind) + this.finishNode(init$1, "VariableDeclaration") + if ((this.type === tt._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1 && + !(kind !== "var" && init$1.declarations[0].init)) + return this.parseForIn(node, init$1) + return this.parseFor(node, init$1) + } + var refDestructuringErrors = new DestructuringErrors + var init = this.parseExpression(true, refDestructuringErrors) + if (this.type === tt._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) { + this.checkPatternErrors(refDestructuringErrors, true) + this.toAssignable(init) + this.checkLVal(init) + return this.parseForIn(node, init) + } else { + this.checkExpressionErrors(refDestructuringErrors, true) + } + return this.parseFor(node, init) +} + +pp$1.parseFunctionStatement = function(node, isAsync) { + this.next() + return this.parseFunction(node, true, false, isAsync) +} + +pp$1.isFunction = function() { + return this.type === tt._function || this.isAsyncFunction() +} + +pp$1.parseIfStatement = function(node) { + this.next() + node.test = this.parseParenExpression() + // allow function declarations in branches, but only in non-strict mode + node.consequent = this.parseStatement(!this.strict && this.isFunction()) + node.alternate = this.eat(tt._else) ? this.parseStatement(!this.strict && this.isFunction()) : null + return this.finishNode(node, "IfStatement") +} + +pp$1.parseReturnStatement = function(node) { + if (!this.inFunction && !this.options.allowReturnOutsideFunction) + this.raise(this.start, "'return' outside of function") + this.next() + + // In `return` (and `break`/`continue`), the keywords with + // optional arguments, we eagerly look for a semicolon or the + // possibility to insert one. + + if (this.eat(tt.semi) || this.insertSemicolon()) node.argument = null + else { node.argument = this.parseExpression(); this.semicolon() } + return this.finishNode(node, "ReturnStatement") +} + +pp$1.parseSwitchStatement = function(node) { + var this$1 = this; + + this.next() + node.discriminant = this.parseParenExpression() + node.cases = [] + this.expect(tt.braceL) + this.labels.push(switchLabel) + + // Statements under must be grouped (by label) in SwitchCase + // nodes. `cur` is used to keep the node that we are currently + // adding statements to. + + for (var cur, sawDefault = false; this.type != tt.braceR;) { + if (this$1.type === tt._case || this$1.type === tt._default) { + var isCase = this$1.type === tt._case + if (cur) this$1.finishNode(cur, "SwitchCase") + node.cases.push(cur = this$1.startNode()) + cur.consequent = [] + this$1.next() + if (isCase) { + cur.test = this$1.parseExpression() + } else { + if (sawDefault) this$1.raiseRecoverable(this$1.lastTokStart, "Multiple default clauses") + sawDefault = true + cur.test = null + } + this$1.expect(tt.colon) + } else { + if (!cur) this$1.unexpected() + cur.consequent.push(this$1.parseStatement(true)) + } + } + if (cur) this.finishNode(cur, "SwitchCase") + this.next() // Closing brace + this.labels.pop() + return this.finishNode(node, "SwitchStatement") +} + +pp$1.parseThrowStatement = function(node) { + this.next() + if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) + this.raise(this.lastTokEnd, "Illegal newline after throw") + node.argument = this.parseExpression() + this.semicolon() + return this.finishNode(node, "ThrowStatement") +} + +// Reused empty array added for node fields that are always empty. + +var empty = [] + +pp$1.parseTryStatement = function(node) { + this.next() + node.block = this.parseBlock() + node.handler = null + if (this.type === tt._catch) { + var clause = this.startNode() + this.next() + this.expect(tt.parenL) + clause.param = this.parseBindingAtom() + this.checkLVal(clause.param, true) + this.expect(tt.parenR) + clause.body = this.parseBlock() + node.handler = this.finishNode(clause, "CatchClause") + } + node.finalizer = this.eat(tt._finally) ? this.parseBlock() : null + if (!node.handler && !node.finalizer) + this.raise(node.start, "Missing catch or finally clause") + return this.finishNode(node, "TryStatement") +} + +pp$1.parseVarStatement = function(node, kind) { + this.next() + this.parseVar(node, false, kind) + this.semicolon() + return this.finishNode(node, "VariableDeclaration") +} + +pp$1.parseWhileStatement = function(node) { + this.next() + node.test = this.parseParenExpression() + this.labels.push(loopLabel) + node.body = this.parseStatement(false) + this.labels.pop() + return this.finishNode(node, "WhileStatement") +} + +pp$1.parseWithStatement = function(node) { + if (this.strict) this.raise(this.start, "'with' in strict mode") + this.next() + node.object = this.parseParenExpression() + node.body = this.parseStatement(false) + return this.finishNode(node, "WithStatement") +} + +pp$1.parseEmptyStatement = function(node) { + this.next() + return this.finishNode(node, "EmptyStatement") +} + +pp$1.parseLabeledStatement = function(node, maybeName, expr) { + var this$1 = this; + + for (var i = 0; i < this.labels.length; ++i) + if (this$1.labels[i].name === maybeName) this$1.raise(expr.start, "Label '" + maybeName + "' is already declared") + var kind = this.type.isLoop ? "loop" : this.type === tt._switch ? "switch" : null + for (var i$1 = this.labels.length - 1; i$1 >= 0; i$1--) { + var label = this$1.labels[i$1] + if (label.statementStart == node.start) { + label.statementStart = this$1.start + label.kind = kind + } else break + } + this.labels.push({name: maybeName, kind: kind, statementStart: this.start}) + node.body = this.parseStatement(true) + this.labels.pop() + node.label = expr + return this.finishNode(node, "LabeledStatement") +} + +pp$1.parseExpressionStatement = function(node, expr) { + node.expression = expr + this.semicolon() + return this.finishNode(node, "ExpressionStatement") +} + +// Parse a semicolon-enclosed block of statements, handling `"use +// strict"` declarations when `allowStrict` is true (used for +// function bodies). + +pp$1.parseBlock = function(allowStrict) { + var this$1 = this; + + var node = this.startNode(), first = true, oldStrict + node.body = [] + this.expect(tt.braceL) + while (!this.eat(tt.braceR)) { + var stmt = this$1.parseStatement(true) + node.body.push(stmt) + if (first && allowStrict && this$1.isUseStrict(stmt)) { + oldStrict = this$1.strict + this$1.setStrict(this$1.strict = true) + } + first = false + } + if (oldStrict === false) this.setStrict(false) + return this.finishNode(node, "BlockStatement") +} + +// Parse a regular `for` loop. The disambiguation code in +// `parseStatement` will already have parsed the init statement or +// expression. + +pp$1.parseFor = function(node, init) { + node.init = init + this.expect(tt.semi) + node.test = this.type === tt.semi ? null : this.parseExpression() + this.expect(tt.semi) + node.update = this.type === tt.parenR ? null : this.parseExpression() + this.expect(tt.parenR) + node.body = this.parseStatement(false) + this.labels.pop() + return this.finishNode(node, "ForStatement") +} + +// Parse a `for`/`in` and `for`/`of` loop, which are almost +// same from parser's perspective. + +pp$1.parseForIn = function(node, init) { + var type = this.type === tt._in ? "ForInStatement" : "ForOfStatement" + this.next() + node.left = init + node.right = this.parseExpression() + this.expect(tt.parenR) + node.body = this.parseStatement(false) + this.labels.pop() + return this.finishNode(node, type) +} + +// Parse a list of variable declarations. + +pp$1.parseVar = function(node, isFor, kind) { + var this$1 = this; + + node.declarations = [] + node.kind = kind + for (;;) { + var decl = this$1.startNode() + this$1.parseVarId(decl) + if (this$1.eat(tt.eq)) { + decl.init = this$1.parseMaybeAssign(isFor) + } else if (kind === "const" && !(this$1.type === tt._in || (this$1.options.ecmaVersion >= 6 && this$1.isContextual("of")))) { + this$1.unexpected() + } else if (decl.id.type != "Identifier" && !(isFor && (this$1.type === tt._in || this$1.isContextual("of")))) { + this$1.raise(this$1.lastTokEnd, "Complex binding patterns require an initialization value") + } else { + decl.init = null + } + node.declarations.push(this$1.finishNode(decl, "VariableDeclarator")) + if (!this$1.eat(tt.comma)) break + } + return node +} + +pp$1.parseVarId = function(decl) { + decl.id = this.parseBindingAtom() + this.checkLVal(decl.id, true) +} + +// Parse a function declaration or literal (depending on the +// `isStatement` parameter). + +pp$1.parseFunction = function(node, isStatement, allowExpressionBody, isAsync) { + this.initFunction(node) + if (this.options.ecmaVersion >= 6 && !isAsync) + node.generator = this.eat(tt.star) + if (this.options.ecmaVersion >= 8) + node.async = !!isAsync + + if (isStatement) + node.id = this.parseIdent() + + var oldInGen = this.inGenerator, oldInAsync = this.inAsync, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos + this.inGenerator = node.generator + this.inAsync = node.async + this.yieldPos = 0 + this.awaitPos = 0 + + if (!isStatement && this.type === tt.name) + node.id = this.parseIdent() + this.parseFunctionParams(node) + this.parseFunctionBody(node, allowExpressionBody) + + this.inGenerator = oldInGen + this.inAsync = oldInAsync + this.yieldPos = oldYieldPos + this.awaitPos = oldAwaitPos + return this.finishNode(node, isStatement ? "FunctionDeclaration" : "FunctionExpression") +} + +pp$1.parseFunctionParams = function(node) { + this.expect(tt.parenL) + node.params = this.parseBindingList(tt.parenR, false, this.options.ecmaVersion >= 8, true) + this.checkYieldAwaitInDefaultParams() +} + +// Parse a class declaration or literal (depending on the +// `isStatement` parameter). + +pp$1.parseClass = function(node, isStatement) { + var this$1 = this; + + this.next() + this.parseClassId(node, isStatement) + this.parseClassSuper(node) + var classBody = this.startNode() + var hadConstructor = false + classBody.body = [] + this.expect(tt.braceL) + while (!this.eat(tt.braceR)) { + if (this$1.eat(tt.semi)) continue + var method = this$1.startNode() + var isGenerator = this$1.eat(tt.star) + var isAsync = false + var isMaybeStatic = this$1.type === tt.name && this$1.value === "static" + this$1.parsePropertyName(method) + method.static = isMaybeStatic && this$1.type !== tt.parenL + if (method.static) { + if (isGenerator) this$1.unexpected() + isGenerator = this$1.eat(tt.star) + this$1.parsePropertyName(method) + } + if (this$1.options.ecmaVersion >= 8 && !isGenerator && !method.computed && + method.key.type === "Identifier" && method.key.name === "async" && this$1.type !== tt.parenL && + !this$1.canInsertSemicolon()) { + isAsync = true + this$1.parsePropertyName(method) + } + method.kind = "method" + var isGetSet = false + if (!method.computed) { + var key = method.key; + if (!isGenerator && !isAsync && key.type === "Identifier" && this$1.type !== tt.parenL && (key.name === "get" || key.name === "set")) { + isGetSet = true + method.kind = key.name + key = this$1.parsePropertyName(method) + } + if (!method.static && (key.type === "Identifier" && key.name === "constructor" || + key.type === "Literal" && key.value === "constructor")) { + if (hadConstructor) this$1.raise(key.start, "Duplicate constructor in the same class") + if (isGetSet) this$1.raise(key.start, "Constructor can't have get/set modifier") + if (isGenerator) this$1.raise(key.start, "Constructor can't be a generator") + if (isAsync) this$1.raise(key.start, "Constructor can't be an async method") + method.kind = "constructor" + hadConstructor = true + } + } + this$1.parseClassMethod(classBody, method, isGenerator, isAsync) + if (isGetSet) { + var paramCount = method.kind === "get" ? 0 : 1 + if (method.value.params.length !== paramCount) { + var start = method.value.start + if (method.kind === "get") + this$1.raiseRecoverable(start, "getter should have no params") + else + this$1.raiseRecoverable(start, "setter should have exactly one param") + } else { + if (method.kind === "set" && method.value.params[0].type === "RestElement") + this$1.raiseRecoverable(method.value.params[0].start, "Setter cannot use rest params") + } + } } + node.body = this.finishNode(classBody, "ClassBody") + return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression") +} - // Asserts that following token is given contextual keyword. +pp$1.parseClassMethod = function(classBody, method, isGenerator, isAsync) { + method.value = this.parseMethod(isGenerator, isAsync) + classBody.body.push(this.finishNode(method, "MethodDefinition")) +} - pp.expectContextual = function(name) { - if (!this.eatContextual(name)) this.unexpected() - } +pp$1.parseClassId = function(node, isStatement) { + node.id = this.type === tt.name ? this.parseIdent() : isStatement ? this.unexpected() : null +} - // Test whether a semicolon can be inserted at the current position. +pp$1.parseClassSuper = function(node) { + node.superClass = this.eat(tt._extends) ? this.parseExprSubscripts() : null +} - pp.canInsertSemicolon = function() { - return this.type === tt.eof || - this.type === tt.braceR || - lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) - } +// Parses module export declaration. - pp.insertSemicolon = function() { - if (this.canInsertSemicolon()) { - if (this.options.onInsertedSemicolon) - this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc) - return true +pp$1.parseExport = function(node, exports) { + var this$1 = this; + + this.next() + // export * from '...' + if (this.eat(tt.star)) { + this.expectContextual("from") + node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected() + this.semicolon() + return this.finishNode(node, "ExportAllDeclaration") + } + if (this.eat(tt._default)) { // export default ... + this.checkExport(exports, "default", this.lastTokStart) + var parens = this.type == tt.parenL + var expr = this.parseMaybeAssign() + var needsSemi = true + if (!parens && (expr.type == "FunctionExpression" || + expr.type == "ClassExpression")) { + needsSemi = false + if (expr.id) { + expr.type = expr.type == "FunctionExpression" + ? "FunctionDeclaration" + : "ClassDeclaration" + } } + node.declaration = expr + if (needsSemi) this.semicolon() + return this.finishNode(node, "ExportDefaultDeclaration") } + // export var|const|let|function|class ... + if (this.shouldParseExportStatement()) { + node.declaration = this.parseStatement(true) + if (node.declaration.type === "VariableDeclaration") + this.checkVariableExport(exports, node.declaration.declarations) + else + this.checkExport(exports, node.declaration.id.name, node.declaration.id.start) + node.specifiers = [] + node.source = null + } else { // export { x, y as z } [from '...'] + node.declaration = null + node.specifiers = this.parseExportSpecifiers(exports) + if (this.eatContextual("from")) { + node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected() + } else { + // check for keywords used as local names + for (var i = 0; i < node.specifiers.length; i++) { + if (this$1.keywords.test(node.specifiers[i].local.name) || this$1.reservedWords.test(node.specifiers[i].local.name)) { + this$1.unexpected(node.specifiers[i].local.start) + } + } - // Consume a semicolon, or, failing that, see if we are allowed to - // pretend that there is a semicolon at this position. - - pp.semicolon = function() { - if (!this.eat(tt.semi) && !this.insertSemicolon()) this.unexpected() + node.source = null + } + this.semicolon() } - - pp.afterTrailingComma = function(tokType, notNext) { - if (this.type == tokType) { - if (this.options.onTrailingComma) - this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc) - if (!notNext) - this.next() - return true + return this.finishNode(node, "ExportNamedDeclaration") +} + +pp$1.checkExport = function(exports, name, pos) { + if (!exports) return + if (Object.prototype.hasOwnProperty.call(exports, name)) + this.raiseRecoverable(pos, "Duplicate export '" + name + "'") + exports[name] = true +} + +pp$1.checkPatternExport = function(exports, pat) { + var this$1 = this; + + var type = pat.type + if (type == "Identifier") + this.checkExport(exports, pat.name, pat.start) + else if (type == "ObjectPattern") + for (var i = 0; i < pat.properties.length; ++i) + this$1.checkPatternExport(exports, pat.properties[i].value) + else if (type == "ArrayPattern") + for (var i$1 = 0; i$1 < pat.elements.length; ++i$1) { + var elt = pat.elements[i$1] + if (elt) this$1.checkPatternExport(exports, elt) + } + else if (type == "AssignmentPattern") + this.checkPatternExport(exports, pat.left) + else if (type == "ParenthesizedExpression") + this.checkPatternExport(exports, pat.expression) +} + +pp$1.checkVariableExport = function(exports, decls) { + var this$1 = this; + + if (!exports) return + for (var i = 0; i < decls.length; i++) + this$1.checkPatternExport(exports, decls[i].id) +} + +pp$1.shouldParseExportStatement = function() { + return this.type.keyword === "var" + || this.type.keyword === "const" + || this.type.keyword === "class" + || this.type.keyword === "function" + || this.isLet() + || this.isAsyncFunction() +} + +// Parses a comma-separated list of module exports. + +pp$1.parseExportSpecifiers = function(exports) { + var this$1 = this; + + var nodes = [], first = true + // export { x, y as z } [from '...'] + this.expect(tt.braceL) + while (!this.eat(tt.braceR)) { + if (!first) { + this$1.expect(tt.comma) + if (this$1.afterTrailingComma(tt.braceR)) break + } else first = false + + var node = this$1.startNode() + node.local = this$1.parseIdent(this$1.type === tt._default) + node.exported = this$1.eatContextual("as") ? this$1.parseIdent(true) : node.local + this$1.checkExport(exports, node.exported.name, node.exported.start) + nodes.push(this$1.finishNode(node, "ExportSpecifier")) + } + return nodes +} + +// Parses import declaration. + +pp$1.parseImport = function(node) { + this.next() + // import '...' + if (this.type === tt.string) { + node.specifiers = empty + node.source = this.parseExprAtom() + } else { + node.specifiers = this.parseImportSpecifiers() + this.expectContextual("from") + node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected() + } + this.semicolon() + return this.finishNode(node, "ImportDeclaration") +} + +// Parses a comma-separated list of module imports. + +pp$1.parseImportSpecifiers = function() { + var this$1 = this; + + var nodes = [], first = true + if (this.type === tt.name) { + // import defaultObj, { x, y as z } from '...' + var node = this.startNode() + node.local = this.parseIdent() + this.checkLVal(node.local, true) + nodes.push(this.finishNode(node, "ImportDefaultSpecifier")) + if (!this.eat(tt.comma)) return nodes + } + if (this.type === tt.star) { + var node$1 = this.startNode() + this.next() + this.expectContextual("as") + node$1.local = this.parseIdent() + this.checkLVal(node$1.local, true) + nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier")) + return nodes + } + this.expect(tt.braceL) + while (!this.eat(tt.braceR)) { + if (!first) { + this$1.expect(tt.comma) + if (this$1.afterTrailingComma(tt.braceR)) break + } else first = false + + var node$2 = this$1.startNode() + node$2.imported = this$1.parseIdent(true) + if (this$1.eatContextual("as")) { + node$2.local = this$1.parseIdent() + } else { + node$2.local = node$2.imported + if (this$1.isKeyword(node$2.local.name)) this$1.unexpected(node$2.local.start) + if (this$1.reservedWordsStrict.test(node$2.local.name)) this$1.raiseRecoverable(node$2.local.start, "The keyword '" + node$2.local.name + "' is reserved") } + this$1.checkLVal(node$2.local, true) + nodes.push(this$1.finishNode(node$2, "ImportSpecifier")) } + return nodes +} - // Expect a token of a given type. If found, consume it, otherwise, - // raise an unexpected token error. - - pp.expect = function(type) { - this.eat(type) || this.unexpected() - } +var pp$2 = Parser.prototype - // Raise an unexpected token error. +// Convert existing expression atom to assignable pattern +// if possible. - pp.unexpected = function(pos) { - this.raise(pos != null ? pos : this.start, "Unexpected token") - } +pp$2.toAssignable = function(node, isBinding) { + var this$1 = this; - var DestructuringErrors = function DestructuringErrors() { - this.shorthandAssign = 0 - this.trailingComma = 0 - }; + if (this.options.ecmaVersion >= 6 && node) { + switch (node.type) { + case "Identifier": + if (this.inAsync && node.name === "await") + this.raise(node.start, "Can not use 'await' as identifier inside an async function") + break - pp.checkPatternErrors = function(refDestructuringErrors, andThrow) { - var trailing = refDestructuringErrors && refDestructuringErrors.trailingComma - if (!andThrow) return !!trailing - if (trailing) this.raise(trailing, "Comma is not permitted after the rest element") - } + case "ObjectPattern": + case "ArrayPattern": + break - pp.checkExpressionErrors = function(refDestructuringErrors, andThrow) { - var pos = refDestructuringErrors && refDestructuringErrors.shorthandAssign - if (!andThrow) return !!pos - if (pos) this.raise(pos, "Shorthand property assignments are valid only in destructuring patterns") - } + case "ObjectExpression": + node.type = "ObjectPattern" + for (var i = 0; i < node.properties.length; i++) { + var prop = node.properties[i] + if (prop.kind !== "init") this$1.raise(prop.key.start, "Object pattern can't contain getter or setter") + this$1.toAssignable(prop.value, isBinding) + } + break - pp.checkYieldAwaitInDefaultParams = function() { - if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos)) - this.raise(this.yieldPos, "Yield expression cannot be a default value") - if (this.awaitPos) - this.raise(this.awaitPos, "Await expression cannot be a default value") - } + case "ArrayExpression": + node.type = "ArrayPattern" + this.toAssignableList(node.elements, isBinding) + break - var pp$1 = Parser.prototype + case "AssignmentExpression": + if (node.operator === "=") { + node.type = "AssignmentPattern" + delete node.operator + this.toAssignable(node.left, isBinding) + // falls through to AssignmentPattern + } else { + this.raise(node.left.end, "Only '=' operator can be used for specifying default value.") + break + } - // ### Statement parsing + case "AssignmentPattern": + break - // Parse a program. Initializes the parser, reads any number of - // statements, and wraps them in a Program node. Optionally takes a - // `program` argument. If present, the statements will be appended - // to its body instead of creating a new node. + case "ParenthesizedExpression": + node.expression = this.toAssignable(node.expression, isBinding) + break - pp$1.parseTopLevel = function(node) { - var this$1 = this; + case "MemberExpression": + if (!isBinding) break - var first = true, exports = {} - if (!node.body) node.body = [] - while (this.type !== tt.eof) { - var stmt = this$1.parseStatement(true, true, exports) - node.body.push(stmt) - if (first) { - if (this$1.isUseStrict(stmt)) this$1.setStrict(true) - first = false - } - } - this.next() - if (this.options.ecmaVersion >= 6) { - node.sourceType = this.options.sourceType - } - return this.finishNode(node, "Program") - } - - var loopLabel = {kind: "loop"}; - var switchLabel = {kind: "switch"}; - pp$1.isLet = function() { - if (this.type !== tt.name || this.options.ecmaVersion < 6 || this.value != "let") return false - skipWhiteSpace.lastIndex = this.pos - var skip = skipWhiteSpace.exec(this.input) - var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next) - if (nextCh === 91 || nextCh == 123) return true // '{' and '[' - if (isIdentifierStart(nextCh, true)) { - for (var pos = next + 1; isIdentifierChar(this.input.charCodeAt(pos), true); ++pos) {} - var ident = this.input.slice(next, pos) - if (!this.isKeyword(ident)) return true + default: + this.raise(node.start, "Assigning to rvalue") } - return false } + return node +} - // check 'async [no LineTerminator here] function' - // - 'async /*foo*/ function' is OK. - // - 'async /*\n*/ function' is invalid. - pp$1.isAsyncFunction = function() { - if (this.type !== tt.name || this.options.ecmaVersion < 8 || this.value != "async") - return false +// Convert list of expression atoms to binding list. - skipWhiteSpace.lastIndex = this.pos - var skip = skipWhiteSpace.exec(this.input) - var next = this.pos + skip[0].length - return !lineBreak.test(this.input.slice(this.pos, next)) && - this.input.slice(next, next + 8) === "function" && - (next + 8 == this.input.length || !isIdentifierChar(this.input.charAt(next + 8))) +pp$2.toAssignableList = function(exprList, isBinding) { + var this$1 = this; + + var end = exprList.length + if (end) { + var last = exprList[end - 1] + if (last && last.type == "RestElement") { + --end + } else if (last && last.type == "SpreadElement") { + last.type = "RestElement" + var arg = last.argument + this.toAssignable(arg, isBinding) + if (arg.type !== "Identifier" && arg.type !== "MemberExpression" && arg.type !== "ArrayPattern") + this.unexpected(arg.start) + --end + } + + if (isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier") + this.unexpected(last.argument.start) + } + for (var i = 0; i < end; i++) { + var elt = exprList[i] + if (elt) this$1.toAssignable(elt, isBinding) } + return exprList +} - // Parse a single statement. - // - // If expecting a statement and finding a slash operator, parse a - // regular expression literal. This is to handle cases like - // `if (foo) /blah/.exec(foo)`, where looking at the previous token - // does not help. +// Parses spread element. - pp$1.parseStatement = function(declaration, topLevel, exports) { - var starttype = this.type, node = this.startNode(), kind +pp$2.parseSpread = function(refDestructuringErrors) { + var node = this.startNode() + this.next() + node.argument = this.parseMaybeAssign(false, refDestructuringErrors) + return this.finishNode(node, "SpreadElement") +} - if (this.isLet()) { - starttype = tt._var - kind = "let" - } +pp$2.parseRest = function(allowNonIdent) { + var node = this.startNode() + this.next() - // Most types of statements are recognized by the keyword they - // start with. Many are trivial to parse, some require a bit of - // complexity. - - switch (starttype) { - case tt._break: case tt._continue: return this.parseBreakContinueStatement(node, starttype.keyword) - case tt._debugger: return this.parseDebuggerStatement(node) - case tt._do: return this.parseDoStatement(node) - case tt._for: return this.parseForStatement(node) - case tt._function: - if (!declaration && this.options.ecmaVersion >= 6) this.unexpected() - return this.parseFunctionStatement(node, false) - case tt._class: - if (!declaration) this.unexpected() - return this.parseClass(node, true) - case tt._if: return this.parseIfStatement(node) - case tt._return: return this.parseReturnStatement(node) - case tt._switch: return this.parseSwitchStatement(node) - case tt._throw: return this.parseThrowStatement(node) - case tt._try: return this.parseTryStatement(node) - case tt._const: case tt._var: - kind = kind || this.value - if (!declaration && kind != "var") this.unexpected() - return this.parseVarStatement(node, kind) - case tt._while: return this.parseWhileStatement(node) - case tt._with: return this.parseWithStatement(node) - case tt.braceL: return this.parseBlock() - case tt.semi: return this.parseEmptyStatement(node) - case tt._export: - case tt._import: - if (!this.options.allowImportExportEverywhere) { - if (!topLevel) - this.raise(this.start, "'import' and 'export' may only appear at the top level") - if (!this.inModule) - this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'") - } - return starttype === tt._import ? this.parseImport(node) : this.parseExport(node, exports) + // RestElement inside of a function parameter must be an identifier + if (allowNonIdent) node.argument = this.type === tt.name ? this.parseIdent() : this.unexpected() + else node.argument = this.type === tt.name || this.type === tt.bracketL ? this.parseBindingAtom() : this.unexpected() - // If the statement does not start with a statement keyword or a - // brace, it's an ExpressionStatement or LabeledStatement. We - // simply start parsing an expression, and afterwards, if the - // next token is a colon and the expression was a simple - // Identifier node, we switch to interpreting it as a label. - default: - if (this.isAsyncFunction() && declaration) { - this.next() - return this.parseFunctionStatement(node, true) - } + return this.finishNode(node, "RestElement") +} - var maybeName = this.value, expr = this.parseExpression() - if (starttype === tt.name && expr.type === "Identifier" && this.eat(tt.colon)) - return this.parseLabeledStatement(node, maybeName, expr) - else return this.parseExpressionStatement(node, expr) - } - } +// Parses lvalue (assignable) atom. - pp$1.parseBreakContinueStatement = function(node, keyword) { - var this$1 = this; +pp$2.parseBindingAtom = function() { + if (this.options.ecmaVersion < 6) return this.parseIdent() + switch (this.type) { + case tt.name: + return this.parseIdent() - var isBreak = keyword == "break" + case tt.bracketL: + var node = this.startNode() this.next() - if (this.eat(tt.semi) || this.insertSemicolon()) node.label = null - else if (this.type !== tt.name) this.unexpected() - else { - node.label = this.parseIdent() - this.semicolon() - } + node.elements = this.parseBindingList(tt.bracketR, true, true) + return this.finishNode(node, "ArrayPattern") - // Verify that there is an actual destination to break or - // continue to. - for (var i = 0; i < this.labels.length; ++i) { - var lab = this$1.labels[i] - if (node.label == null || lab.name === node.label.name) { - if (lab.kind != null && (isBreak || lab.kind === "loop")) break - if (node.label && isBreak) break - } - } - if (i === this.labels.length) this.raise(node.start, "Unsyntactic " + keyword) - return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement") - } + case tt.braceL: + return this.parseObj(true) - pp$1.parseDebuggerStatement = function(node) { - this.next() - this.semicolon() - return this.finishNode(node, "DebuggerStatement") + default: + this.unexpected() } +} + +pp$2.parseBindingList = function(close, allowEmpty, allowTrailingComma, allowNonIdent) { + var this$1 = this; - pp$1.parseDoStatement = function(node) { + var elts = [], first = true + while (!this.eat(close)) { + if (first) first = false + else this$1.expect(tt.comma) + if (allowEmpty && this$1.type === tt.comma) { + elts.push(null) + } else if (allowTrailingComma && this$1.afterTrailingComma(close)) { + break + } else if (this$1.type === tt.ellipsis) { + var rest = this$1.parseRest(allowNonIdent) + this$1.parseBindingListItem(rest) + elts.push(rest) + if (this$1.type === tt.comma) this$1.raise(this$1.start, "Comma is not permitted after the rest element") + this$1.expect(close) + break + } else { + var elem = this$1.parseMaybeDefault(this$1.start, this$1.startLoc) + this$1.parseBindingListItem(elem) + elts.push(elem) + } + } + return elts +} + +pp$2.parseBindingListItem = function(param) { + return param +} + +// Parses assignment pattern around given atom if possible. + +pp$2.parseMaybeDefault = function(startPos, startLoc, left) { + left = left || this.parseBindingAtom() + if (this.options.ecmaVersion < 6 || !this.eat(tt.eq)) return left + var node = this.startNodeAt(startPos, startLoc) + node.left = left + node.right = this.parseMaybeAssign() + return this.finishNode(node, "AssignmentPattern") +} + +// Verify that a node is an lval — something that can be assigned +// to. + +pp$2.checkLVal = function(expr, isBinding, checkClashes) { + var this$1 = this; + + switch (expr.type) { + case "Identifier": + if (this.strict && this.reservedWordsStrictBind.test(expr.name)) + this.raiseRecoverable(expr.start, (isBinding ? "Binding " : "Assigning to ") + expr.name + " in strict mode") + if (checkClashes) { + if (has(checkClashes, expr.name)) + this.raiseRecoverable(expr.start, "Argument name clash") + checkClashes[expr.name] = true + } + break + + case "MemberExpression": + if (isBinding) this.raiseRecoverable(expr.start, (isBinding ? "Binding" : "Assigning to") + " member expression") + break + + case "ObjectPattern": + for (var i = 0; i < expr.properties.length; i++) + this$1.checkLVal(expr.properties[i].value, isBinding, checkClashes) + break + + case "ArrayPattern": + for (var i$1 = 0; i$1 < expr.elements.length; i$1++) { + var elem = expr.elements[i$1] + if (elem) this$1.checkLVal(elem, isBinding, checkClashes) + } + break + + case "AssignmentPattern": + this.checkLVal(expr.left, isBinding, checkClashes) + break + + case "RestElement": + this.checkLVal(expr.argument, isBinding, checkClashes) + break + + case "ParenthesizedExpression": + this.checkLVal(expr.expression, isBinding, checkClashes) + break + + default: + this.raise(expr.start, (isBinding ? "Binding" : "Assigning to") + " rvalue") + } +} + +// A recursive descent parser operates by defining functions for all +// syntactic elements, and recursively calling those, each function +// advancing the input stream and returning an AST node. Precedence +// of constructs (for example, the fact that `!x[1]` means `!(x[1])` +// instead of `(!x)[1]` is handled by the fact that the parser +// function that parses unary prefix operators is called first, and +// in turn calls the function that parses `[]` subscripts — that +// way, it'll receive the node for `x[1]` already parsed, and wraps +// *that* in the unary operator node. +// +// Acorn uses an [operator precedence parser][opp] to handle binary +// operator precedence, because it is much more compact than using +// the technique outlined above, which uses different, nesting +// functions to specify precedence, for all of the ten binary +// precedence levels that JavaScript defines. +// +// [opp]: http://en.wikipedia.org/wiki/Operator-precedence_parser + +var pp$3 = Parser.prototype + +// Check if property name clashes with already added. +// Object/class getters and setters are not allowed to clash — +// either with each other or with an init property — and in +// strict mode, init properties are also not allowed to be repeated. + +pp$3.checkPropClash = function(prop, propHash) { + if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand)) + return + var key = prop.key; + var name + switch (key.type) { + case "Identifier": name = key.name; break + case "Literal": name = String(key.value); break + default: return + } + var kind = prop.kind; + if (this.options.ecmaVersion >= 6) { + if (name === "__proto__" && kind === "init") { + if (propHash.proto) this.raiseRecoverable(key.start, "Redefinition of __proto__ property") + propHash.proto = true + } + return + } + name = "$" + name + var other = propHash[name] + if (other) { + var isGetSet = kind !== "init" + if ((this.strict || isGetSet) && other[kind] || !(isGetSet ^ other.init)) + this.raiseRecoverable(key.start, "Redefinition of property") + } else { + other = propHash[name] = { + init: false, + get: false, + set: false + } + } + other[kind] = true +} + +// ### Expression parsing + +// These nest, from the most general expression type at the top to +// 'atomic', nondivisible expression types at the bottom. Most of +// the functions will simply let the function(s) below them parse, +// and, *if* the syntactic construct they handle is present, wrap +// the AST node that the inner parser gave them in another node. + +// Parse a full expression. The optional arguments are used to +// forbid the `in` operator (in for loops initalization expressions) +// and provide reference for storing '=' operator inside shorthand +// property assignment in contexts where both object expression +// and object pattern might appear (so it's possible to raise +// delayed syntax error at correct position). + +pp$3.parseExpression = function(noIn, refDestructuringErrors) { + var this$1 = this; + + var startPos = this.start, startLoc = this.startLoc + var expr = this.parseMaybeAssign(noIn, refDestructuringErrors) + if (this.type === tt.comma) { + var node = this.startNodeAt(startPos, startLoc) + node.expressions = [expr] + while (this.eat(tt.comma)) node.expressions.push(this$1.parseMaybeAssign(noIn, refDestructuringErrors)) + return this.finishNode(node, "SequenceExpression") + } + return expr +} + +// Parse an assignment expression. This includes applications of +// operators like `+=`. + +pp$3.parseMaybeAssign = function(noIn, refDestructuringErrors, afterLeftParse) { + if (this.inGenerator && this.isContextual("yield")) return this.parseYield() + + var ownDestructuringErrors = false + if (!refDestructuringErrors) { + refDestructuringErrors = new DestructuringErrors + ownDestructuringErrors = true + } + var startPos = this.start, startLoc = this.startLoc + if (this.type == tt.parenL || this.type == tt.name) + this.potentialArrowAt = this.start + var left = this.parseMaybeConditional(noIn, refDestructuringErrors) + if (afterLeftParse) left = afterLeftParse.call(this, left, startPos, startLoc) + if (this.type.isAssign) { + this.checkPatternErrors(refDestructuringErrors, true) + if (!ownDestructuringErrors) DestructuringErrors.call(refDestructuringErrors) + var node = this.startNodeAt(startPos, startLoc) + node.operator = this.value + node.left = this.type === tt.eq ? this.toAssignable(left) : left + refDestructuringErrors.shorthandAssign = 0 // reset because shorthand default was used correctly + this.checkLVal(left) this.next() - this.labels.push(loopLabel) - node.body = this.parseStatement(false) - this.labels.pop() - this.expect(tt._while) - node.test = this.parseParenExpression() - if (this.options.ecmaVersion >= 6) - this.eat(tt.semi) - else - this.semicolon() - return this.finishNode(node, "DoWhileStatement") + node.right = this.parseMaybeAssign(noIn) + return this.finishNode(node, "AssignmentExpression") + } else { + if (ownDestructuringErrors) this.checkExpressionErrors(refDestructuringErrors, true) } + return left +} - // Disambiguating between a `for` and a `for`/`in` or `for`/`of` - // loop is non-trivial. Basically, we have to parse the init `var` - // statement or expression, disallowing the `in` operator (see - // the second parameter to `parseExpression`), and then check - // whether the next token is `in` or `of`. When there is no init - // part (semicolon immediately after the opening parenthesis), it - // is a regular `for` loop. +// Parse a ternary conditional (`?:`) operator. - pp$1.parseForStatement = function(node) { - this.next() - this.labels.push(loopLabel) - this.expect(tt.parenL) - if (this.type === tt.semi) return this.parseFor(node, null) - var isLet = this.isLet() - if (this.type === tt._var || this.type === tt._const || isLet) { - var init$1 = this.startNode(), kind = isLet ? "let" : this.value +pp$3.parseMaybeConditional = function(noIn, refDestructuringErrors) { + var startPos = this.start, startLoc = this.startLoc + var expr = this.parseExprOps(noIn, refDestructuringErrors) + if (this.checkExpressionErrors(refDestructuringErrors)) return expr + if (this.eat(tt.question)) { + var node = this.startNodeAt(startPos, startLoc) + node.test = expr + node.consequent = this.parseMaybeAssign() + this.expect(tt.colon) + node.alternate = this.parseMaybeAssign(noIn) + return this.finishNode(node, "ConditionalExpression") + } + return expr +} + +// Start the precedence parser. + +pp$3.parseExprOps = function(noIn, refDestructuringErrors) { + var startPos = this.start, startLoc = this.startLoc + var expr = this.parseMaybeUnary(refDestructuringErrors, false) + if (this.checkExpressionErrors(refDestructuringErrors)) return expr + return this.parseExprOp(expr, startPos, startLoc, -1, noIn) +} + +// Parse binary operators with the operator precedence parsing +// algorithm. `left` is the left-hand side of the operator. +// `minPrec` provides context that allows the function to stop and +// defer further parser to one of its callers when it encounters an +// operator that has a lower precedence than the set it is parsing. + +pp$3.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, noIn) { + var prec = this.type.binop + if (prec != null && (!noIn || this.type !== tt._in)) { + if (prec > minPrec) { + var logical = this.type === tt.logicalOR || this.type === tt.logicalAND + var op = this.value this.next() - this.parseVar(init$1, true, kind) - this.finishNode(init$1, "VariableDeclaration") - if ((this.type === tt._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1 && - !(kind !== "var" && init$1.declarations[0].init)) - return this.parseForIn(node, init$1) - return this.parseFor(node, init$1) + var startPos = this.start, startLoc = this.startLoc + var right = this.parseExprOp(this.parseMaybeUnary(null, false), startPos, startLoc, prec, noIn) + var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical) + return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn) + } + } + return left +} + +pp$3.buildBinary = function(startPos, startLoc, left, right, op, logical) { + var node = this.startNodeAt(startPos, startLoc) + node.left = left + node.operator = op + node.right = right + return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression") +} + +// Parse unary operators, both prefix and postfix. + +pp$3.parseMaybeUnary = function(refDestructuringErrors, sawUnary) { + var this$1 = this; + + var startPos = this.start, startLoc = this.startLoc, expr + if (this.inAsync && this.isContextual("await")) { + expr = this.parseAwait(refDestructuringErrors) + sawUnary = true + } else if (this.type.prefix) { + var node = this.startNode(), update = this.type === tt.incDec + node.operator = this.value + node.prefix = true + this.next() + node.argument = this.parseMaybeUnary(null, true) + this.checkExpressionErrors(refDestructuringErrors, true) + if (update) this.checkLVal(node.argument) + else if (this.strict && node.operator === "delete" && + node.argument.type === "Identifier") + this.raiseRecoverable(node.start, "Deleting local variable in strict mode") + else sawUnary = true + expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression") + } else { + expr = this.parseExprSubscripts(refDestructuringErrors) + if (this.checkExpressionErrors(refDestructuringErrors)) return expr + while (this.type.postfix && !this.canInsertSemicolon()) { + var node$1 = this$1.startNodeAt(startPos, startLoc) + node$1.operator = this$1.value + node$1.prefix = false + node$1.argument = expr + this$1.checkLVal(expr) + this$1.next() + expr = this$1.finishNode(node$1, "UpdateExpression") } - var refDestructuringErrors = new DestructuringErrors - var init = this.parseExpression(true, refDestructuringErrors) - if (this.type === tt._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) { - this.checkPatternErrors(refDestructuringErrors, true) - this.toAssignable(init) - this.checkLVal(init) - return this.parseForIn(node, init) + } + + if (!sawUnary && this.eat(tt.starstar)) + return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false), "**", false) + else + return expr +} + +// Parse call, dot, and `[]`-subscript expressions. + +pp$3.parseExprSubscripts = function(refDestructuringErrors) { + var startPos = this.start, startLoc = this.startLoc + var expr = this.parseExprAtom(refDestructuringErrors) + var skipArrowSubscripts = expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")" + if (this.checkExpressionErrors(refDestructuringErrors) || skipArrowSubscripts) return expr + return this.parseSubscripts(expr, startPos, startLoc) +} + +pp$3.parseSubscripts = function(base, startPos, startLoc, noCalls) { + var this$1 = this; + + for (;;) { + var maybeAsyncArrow = this$1.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" && !this$1.canInsertSemicolon() + if (this$1.eat(tt.dot)) { + var node = this$1.startNodeAt(startPos, startLoc) + node.object = base + node.property = this$1.parseIdent(true) + node.computed = false + base = this$1.finishNode(node, "MemberExpression") + } else if (this$1.eat(tt.bracketL)) { + var node$1 = this$1.startNodeAt(startPos, startLoc) + node$1.object = base + node$1.property = this$1.parseExpression() + node$1.computed = true + this$1.expect(tt.bracketR) + base = this$1.finishNode(node$1, "MemberExpression") + } else if (!noCalls && this$1.eat(tt.parenL)) { + var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this$1.yieldPos, oldAwaitPos = this$1.awaitPos + this$1.yieldPos = 0 + this$1.awaitPos = 0 + var exprList = this$1.parseExprList(tt.parenR, this$1.options.ecmaVersion >= 8, false, refDestructuringErrors) + if (maybeAsyncArrow && !this$1.canInsertSemicolon() && this$1.eat(tt.arrow)) { + this$1.checkPatternErrors(refDestructuringErrors, true) + this$1.checkYieldAwaitInDefaultParams() + this$1.yieldPos = oldYieldPos + this$1.awaitPos = oldAwaitPos + return this$1.parseArrowExpression(this$1.startNodeAt(startPos, startLoc), exprList, true) + } + this$1.checkExpressionErrors(refDestructuringErrors, true) + this$1.yieldPos = oldYieldPos || this$1.yieldPos + this$1.awaitPos = oldAwaitPos || this$1.awaitPos + var node$2 = this$1.startNodeAt(startPos, startLoc) + node$2.callee = base + node$2.arguments = exprList + base = this$1.finishNode(node$2, "CallExpression") + } else if (this$1.type === tt.backQuote) { + var node$3 = this$1.startNodeAt(startPos, startLoc) + node$3.tag = base + node$3.quasi = this$1.parseTemplate() + base = this$1.finishNode(node$3, "TaggedTemplateExpression") } else { - this.checkExpressionErrors(refDestructuringErrors, true) + return base } - return this.parseFor(node, init) } +} - pp$1.parseFunctionStatement = function(node, isAsync) { - this.next() - return this.parseFunction(node, true, false, isAsync) - } +// Parse an atomic expression — either a single token that is an +// expression, an expression started by a keyword like `function` or +// `new`, or an expression wrapped in punctuation like `()`, `[]`, +// or `{}`. - pp$1.isFunction = function() { - return this.type === tt._function || this.isAsyncFunction() - } +pp$3.parseExprAtom = function(refDestructuringErrors) { + var node, canBeArrow = this.potentialArrowAt == this.start + switch (this.type) { + case tt._super: + if (!this.inFunction) + this.raise(this.start, "'super' outside of function or class") - pp$1.parseIfStatement = function(node) { + case tt._this: + var type = this.type === tt._this ? "ThisExpression" : "Super" + node = this.startNode() this.next() - node.test = this.parseParenExpression() - // allow function declarations in branches, but only in non-strict mode - node.consequent = this.parseStatement(!this.strict && this.isFunction()) - node.alternate = this.eat(tt._else) ? this.parseStatement(!this.strict && this.isFunction()) : null - return this.finishNode(node, "IfStatement") - } + return this.finishNode(node, type) - pp$1.parseReturnStatement = function(node) { - if (!this.inFunction && !this.options.allowReturnOutsideFunction) - this.raise(this.start, "'return' outside of function") - this.next() + case tt.name: + var startPos = this.start, startLoc = this.startLoc + var id = this.parseIdent(this.type !== tt.name) + if (this.options.ecmaVersion >= 8 && id.name === "async" && !this.canInsertSemicolon() && this.eat(tt._function)) + return this.parseFunction(this.startNodeAt(startPos, startLoc), false, false, true) + if (canBeArrow && !this.canInsertSemicolon()) { + if (this.eat(tt.arrow)) + return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false) + if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === tt.name) { + id = this.parseIdent() + if (this.canInsertSemicolon() || !this.eat(tt.arrow)) + this.unexpected() + return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true) + } + } + return id - // In `return` (and `break`/`continue`), the keywords with - // optional arguments, we eagerly look for a semicolon or the - // possibility to insert one. + case tt.regexp: + var value = this.value + node = this.parseLiteral(value.value) + node.regex = {pattern: value.pattern, flags: value.flags} + return node - if (this.eat(tt.semi) || this.insertSemicolon()) node.argument = null - else { node.argument = this.parseExpression(); this.semicolon() } - return this.finishNode(node, "ReturnStatement") - } + case tt.num: case tt.string: + return this.parseLiteral(this.value) - pp$1.parseSwitchStatement = function(node) { - var this$1 = this; + case tt._null: case tt._true: case tt._false: + node = this.startNode() + node.value = this.type === tt._null ? null : this.type === tt._true + node.raw = this.type.keyword + this.next() + return this.finishNode(node, "Literal") + case tt.parenL: + return this.parseParenAndDistinguishExpression(canBeArrow) + + case tt.bracketL: + node = this.startNode() this.next() - node.discriminant = this.parseParenExpression() - node.cases = [] - this.expect(tt.braceL) - this.labels.push(switchLabel) - - // Statements under must be grouped (by label) in SwitchCase - // nodes. `cur` is used to keep the node that we are currently - // adding statements to. - - for (var cur, sawDefault = false; this.type != tt.braceR;) { - if (this$1.type === tt._case || this$1.type === tt._default) { - var isCase = this$1.type === tt._case - if (cur) this$1.finishNode(cur, "SwitchCase") - node.cases.push(cur = this$1.startNode()) - cur.consequent = [] - this$1.next() - if (isCase) { - cur.test = this$1.parseExpression() - } else { - if (sawDefault) this$1.raiseRecoverable(this$1.lastTokStart, "Multiple default clauses") - sawDefault = true - cur.test = null - } - this$1.expect(tt.colon) - } else { - if (!cur) this$1.unexpected() - cur.consequent.push(this$1.parseStatement(true)) - } - } - if (cur) this.finishNode(cur, "SwitchCase") - this.next() // Closing brace - this.labels.pop() - return this.finishNode(node, "SwitchStatement") - } + node.elements = this.parseExprList(tt.bracketR, true, true, refDestructuringErrors) + return this.finishNode(node, "ArrayExpression") + + case tt.braceL: + return this.parseObj(false, refDestructuringErrors) - pp$1.parseThrowStatement = function(node) { + case tt._function: + node = this.startNode() this.next() - if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) - this.raise(this.lastTokEnd, "Illegal newline after throw") - node.argument = this.parseExpression() - this.semicolon() - return this.finishNode(node, "ThrowStatement") - } + return this.parseFunction(node, false) - // Reused empty array added for node fields that are always empty. + case tt._class: + return this.parseClass(this.startNode(), false) - var empty = [] + case tt._new: + return this.parseNew() - pp$1.parseTryStatement = function(node) { - this.next() - node.block = this.parseBlock() - node.handler = null - if (this.type === tt._catch) { - var clause = this.startNode() - this.next() - this.expect(tt.parenL) - clause.param = this.parseBindingAtom() - this.checkLVal(clause.param, true) - this.expect(tt.parenR) - clause.body = this.parseBlock() - node.handler = this.finishNode(clause, "CatchClause") - } - node.finalizer = this.eat(tt._finally) ? this.parseBlock() : null - if (!node.handler && !node.finalizer) - this.raise(node.start, "Missing catch or finally clause") - return this.finishNode(node, "TryStatement") - } + case tt.backQuote: + return this.parseTemplate() - pp$1.parseVarStatement = function(node, kind) { - this.next() - this.parseVar(node, false, kind) - this.semicolon() - return this.finishNode(node, "VariableDeclaration") + default: + this.unexpected() } +} - pp$1.parseWhileStatement = function(node) { - this.next() - node.test = this.parseParenExpression() - this.labels.push(loopLabel) - node.body = this.parseStatement(false) - this.labels.pop() - return this.finishNode(node, "WhileStatement") - } +pp$3.parseLiteral = function(value) { + var node = this.startNode() + node.value = value + node.raw = this.input.slice(this.start, this.end) + this.next() + return this.finishNode(node, "Literal") +} - pp$1.parseWithStatement = function(node) { - if (this.strict) this.raise(this.start, "'with' in strict mode") - this.next() - node.object = this.parseParenExpression() - node.body = this.parseStatement(false) - return this.finishNode(node, "WithStatement") - } +pp$3.parseParenExpression = function() { + this.expect(tt.parenL) + var val = this.parseExpression() + this.expect(tt.parenR) + return val +} - pp$1.parseEmptyStatement = function(node) { +pp$3.parseParenAndDistinguishExpression = function(canBeArrow) { + var this$1 = this; + + var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8 + if (this.options.ecmaVersion >= 6) { this.next() - return this.finishNode(node, "EmptyStatement") - } - pp$1.parseLabeledStatement = function(node, maybeName, expr) { - var this$1 = this; + var innerStartPos = this.start, innerStartLoc = this.startLoc + var exprList = [], first = true, lastIsComma = false + var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart, innerParenStart + this.yieldPos = 0 + this.awaitPos = 0 + while (this.type !== tt.parenR) { + first ? first = false : this$1.expect(tt.comma) + if (allowTrailingComma && this$1.afterTrailingComma(tt.parenR, true)) { + lastIsComma = true + break + } else if (this$1.type === tt.ellipsis) { + spreadStart = this$1.start + exprList.push(this$1.parseParenItem(this$1.parseRest())) + if (this$1.type === tt.comma) this$1.raise(this$1.start, "Comma is not permitted after the rest element") + break + } else { + if (this$1.type === tt.parenL && !innerParenStart) { + innerParenStart = this$1.start + } + exprList.push(this$1.parseMaybeAssign(false, refDestructuringErrors, this$1.parseParenItem)) + } + } + var innerEndPos = this.start, innerEndLoc = this.startLoc + this.expect(tt.parenR) - for (var i = 0; i < this.labels.length; ++i) - if (this$1.labels[i].name === maybeName) this$1.raise(expr.start, "Label '" + maybeName + "' is already declared") - var kind = this.type.isLoop ? "loop" : this.type === tt._switch ? "switch" : null - for (var i$1 = this.labels.length - 1; i$1 >= 0; i$1--) { - var label = this$1.labels[i$1] - if (label.statementStart == node.start) { - label.statementStart = this$1.start - label.kind = kind - } else break + if (canBeArrow && !this.canInsertSemicolon() && this.eat(tt.arrow)) { + this.checkPatternErrors(refDestructuringErrors, true) + this.checkYieldAwaitInDefaultParams() + if (innerParenStart) this.unexpected(innerParenStart) + this.yieldPos = oldYieldPos + this.awaitPos = oldAwaitPos + return this.parseParenArrowList(startPos, startLoc, exprList) + } + + if (!exprList.length || lastIsComma) this.unexpected(this.lastTokStart) + if (spreadStart) this.unexpected(spreadStart) + this.checkExpressionErrors(refDestructuringErrors, true) + this.yieldPos = oldYieldPos || this.yieldPos + this.awaitPos = oldAwaitPos || this.awaitPos + + if (exprList.length > 1) { + val = this.startNodeAt(innerStartPos, innerStartLoc) + val.expressions = exprList + this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc) + } else { + val = exprList[0] } - this.labels.push({name: maybeName, kind: kind, statementStart: this.start}) - node.body = this.parseStatement(true) - this.labels.pop() - node.label = expr - return this.finishNode(node, "LabeledStatement") + } else { + val = this.parseParenExpression() } - pp$1.parseExpressionStatement = function(node, expr) { - node.expression = expr - this.semicolon() - return this.finishNode(node, "ExpressionStatement") + if (this.options.preserveParens) { + var par = this.startNodeAt(startPos, startLoc) + par.expression = val + return this.finishNode(par, "ParenthesizedExpression") + } else { + return val } - - // Parse a semicolon-enclosed block of statements, handling `"use - // strict"` declarations when `allowStrict` is true (used for - // function bodies). - - pp$1.parseBlock = function(allowStrict) { - var this$1 = this; - - var node = this.startNode(), first = true, oldStrict - node.body = [] - this.expect(tt.braceL) - while (!this.eat(tt.braceR)) { - var stmt = this$1.parseStatement(true) - node.body.push(stmt) - if (first && allowStrict && this$1.isUseStrict(stmt)) { - oldStrict = this$1.strict - this$1.setStrict(this$1.strict = true) +} + +pp$3.parseParenItem = function(item) { + return item +} + +pp$3.parseParenArrowList = function(startPos, startLoc, exprList) { + return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList) +} + +// New's precedence is slightly tricky. It must allow its argument to +// be a `[]` or dot subscript expression, but not a call — at least, +// not without wrapping it in parentheses. Thus, it uses the noCalls +// argument to parseSubscripts to prevent it from consuming the +// argument list. + +var empty$1 = [] + +pp$3.parseNew = function() { + var node = this.startNode() + var meta = this.parseIdent(true) + if (this.options.ecmaVersion >= 6 && this.eat(tt.dot)) { + node.meta = meta + node.property = this.parseIdent(true) + if (node.property.name !== "target") + this.raiseRecoverable(node.property.start, "The only valid meta property for new is new.target") + if (!this.inFunction) + this.raiseRecoverable(node.start, "new.target can only be used in functions") + return this.finishNode(node, "MetaProperty") + } + var startPos = this.start, startLoc = this.startLoc + node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true) + if (this.eat(tt.parenL)) node.arguments = this.parseExprList(tt.parenR, this.options.ecmaVersion >= 8, false) + else node.arguments = empty$1 + return this.finishNode(node, "NewExpression") +} + +// Parse template expression. + +pp$3.parseTemplateElement = function() { + var elem = this.startNode() + elem.value = { + raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, '\n'), + cooked: this.value + } + this.next() + elem.tail = this.type === tt.backQuote + return this.finishNode(elem, "TemplateElement") +} + +pp$3.parseTemplate = function() { + var this$1 = this; + + var node = this.startNode() + this.next() + node.expressions = [] + var curElt = this.parseTemplateElement() + node.quasis = [curElt] + while (!curElt.tail) { + this$1.expect(tt.dollarBraceL) + node.expressions.push(this$1.parseExpression()) + this$1.expect(tt.braceR) + node.quasis.push(curElt = this$1.parseTemplateElement()) + } + this.next() + return this.finishNode(node, "TemplateLiteral") +} + +// Parse an object literal or binding pattern. + +pp$3.parseObj = function(isPattern, refDestructuringErrors) { + var this$1 = this; + + var node = this.startNode(), first = true, propHash = {} + node.properties = [] + this.next() + while (!this.eat(tt.braceR)) { + if (!first) { + this$1.expect(tt.comma) + if (this$1.afterTrailingComma(tt.braceR)) break + } else first = false + + var prop = this$1.startNode(), isGenerator, isAsync, startPos, startLoc + if (this$1.options.ecmaVersion >= 6) { + prop.method = false + prop.shorthand = false + if (isPattern || refDestructuringErrors) { + startPos = this$1.start + startLoc = this$1.startLoc } - first = false + if (!isPattern) + isGenerator = this$1.eat(tt.star) } - if (oldStrict === false) this.setStrict(false) - return this.finishNode(node, "BlockStatement") - } + this$1.parsePropertyName(prop) + if (!isPattern && this$1.options.ecmaVersion >= 8 && !isGenerator && !prop.computed && + prop.key.type === "Identifier" && prop.key.name === "async" && this$1.type !== tt.parenL && + this$1.type !== tt.colon && !this$1.canInsertSemicolon()) { + isAsync = true + this$1.parsePropertyName(prop, refDestructuringErrors) + } else { + isAsync = false + } + this$1.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors) + this$1.checkPropClash(prop, propHash) + node.properties.push(this$1.finishNode(prop, "Property")) + } + return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression") +} + +pp$3.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors) { + if ((isGenerator || isAsync) && this.type === tt.colon) + this.unexpected() + + if (this.eat(tt.colon)) { + prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors) + prop.kind = "init" + } else if (this.options.ecmaVersion >= 6 && this.type === tt.parenL) { + if (isPattern) this.unexpected() + prop.kind = "init" + prop.method = true + prop.value = this.parseMethod(isGenerator, isAsync) + } else if (this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" && + (prop.key.name === "get" || prop.key.name === "set") && + (this.type != tt.comma && this.type != tt.braceR)) { + if (isGenerator || isAsync || isPattern) this.unexpected() + prop.kind = prop.key.name + this.parsePropertyName(prop) + prop.value = this.parseMethod(false) + var paramCount = prop.kind === "get" ? 0 : 1 + if (prop.value.params.length !== paramCount) { + var start = prop.value.start + if (prop.kind === "get") + this.raiseRecoverable(start, "getter should have no params") + else + this.raiseRecoverable(start, "setter should have exactly one param") + } else { + if (prop.kind === "set" && prop.value.params[0].type === "RestElement") + this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params") + } + } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") { + if (this.keywords.test(prop.key.name) || + (this.strict ? this.reservedWordsStrict : this.reservedWords).test(prop.key.name) || + (this.inGenerator && prop.key.name == "yield") || + (this.inAsync && prop.key.name == "await")) + this.raiseRecoverable(prop.key.start, "'" + prop.key.name + "' can not be used as shorthand property") + prop.kind = "init" + if (isPattern) { + prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key) + } else if (this.type === tt.eq && refDestructuringErrors) { + if (!refDestructuringErrors.shorthandAssign) + refDestructuringErrors.shorthandAssign = this.start + prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key) + } else { + prop.value = prop.key + } + prop.shorthand = true + } else this.unexpected() +} + +pp$3.parsePropertyName = function(prop) { + if (this.options.ecmaVersion >= 6) { + if (this.eat(tt.bracketL)) { + prop.computed = true + prop.key = this.parseMaybeAssign() + this.expect(tt.bracketR) + return prop.key + } else { + prop.computed = false + } + } + return prop.key = this.type === tt.num || this.type === tt.string ? this.parseExprAtom() : this.parseIdent(true) +} + +// Initialize empty function node. + +pp$3.initFunction = function(node) { + node.id = null + if (this.options.ecmaVersion >= 6) { + node.generator = false + node.expression = false + } + if (this.options.ecmaVersion >= 8) + node.async = false +} + +// Parse object or class method. + +pp$3.parseMethod = function(isGenerator, isAsync) { + var node = this.startNode(), oldInGen = this.inGenerator, oldInAsync = this.inAsync, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos + + this.initFunction(node) + if (this.options.ecmaVersion >= 6) + node.generator = isGenerator + if (this.options.ecmaVersion >= 8) + node.async = !!isAsync + + this.inGenerator = node.generator + this.inAsync = node.async + this.yieldPos = 0 + this.awaitPos = 0 + + this.expect(tt.parenL) + node.params = this.parseBindingList(tt.parenR, false, this.options.ecmaVersion >= 8) + this.checkYieldAwaitInDefaultParams() + this.parseFunctionBody(node, false) + + this.inGenerator = oldInGen + this.inAsync = oldInAsync + this.yieldPos = oldYieldPos + this.awaitPos = oldAwaitPos + return this.finishNode(node, "FunctionExpression") +} + +// Parse arrow function expression with given parameters. + +pp$3.parseArrowExpression = function(node, params, isAsync) { + var oldInGen = this.inGenerator, oldInAsync = this.inAsync, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos + + this.initFunction(node) + if (this.options.ecmaVersion >= 8) + node.async = !!isAsync + + this.inGenerator = false + this.inAsync = node.async + this.yieldPos = 0 + this.awaitPos = 0 + + node.params = this.toAssignableList(params, true) + this.parseFunctionBody(node, true) + + this.inGenerator = oldInGen + this.inAsync = oldInAsync + this.yieldPos = oldYieldPos + this.awaitPos = oldAwaitPos + return this.finishNode(node, "ArrowFunctionExpression") +} + +// Parse function body and check parameters. + +pp$3.parseFunctionBody = function(node, isArrowFunction) { + var isExpression = isArrowFunction && this.type !== tt.braceL + + if (isExpression) { + node.body = this.parseMaybeAssign() + node.expression = true + } else { + // Start a new scope with regard to labels and the `inFunction` + // flag (restore them to their old value afterwards). + var oldInFunc = this.inFunction, oldLabels = this.labels + this.inFunction = true; this.labels = [] + node.body = this.parseBlock(true) + node.expression = false + this.inFunction = oldInFunc; this.labels = oldLabels + } + + // If this is a strict mode function, verify that argument names + // are not repeated, and it does not try to bind the words `eval` + // or `arguments`. + var useStrict = (!isExpression && node.body.body.length && this.isUseStrict(node.body.body[0])) ? node.body.body[0] : null + if (useStrict && this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params)) + this.raiseRecoverable(useStrict.start, "Illegal 'use strict' directive in function with non-simple parameter list") + + if (this.strict || useStrict) { + var oldStrict = this.strict + this.strict = true + if (node.id) + this.checkLVal(node.id, true) + this.checkParams(node) + this.strict = oldStrict + } else if (isArrowFunction || !this.isSimpleParamList(node.params)) { + this.checkParams(node) + } +} + +pp$3.isSimpleParamList = function(params) { + for (var i = 0; i < params.length; i++) + if (params[i].type !== "Identifier") return false + return true +} + +// Checks function params for various disallowed patterns such as using "eval" +// or "arguments" and duplicate parameters. + +pp$3.checkParams = function(node) { + var this$1 = this; + + var nameHash = {} + for (var i = 0; i < node.params.length; i++) this$1.checkLVal(node.params[i], true, nameHash) +} + +// Parses a comma-separated list of expressions, and returns them as +// an array. `close` is the token type that ends the list, and +// `allowEmpty` can be turned on to allow subsequent commas with +// nothing in between them to be parsed as `null` (which is needed +// for array literals). + +pp$3.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) { + var this$1 = this; + + var elts = [], first = true + while (!this.eat(close)) { + if (!first) { + this$1.expect(tt.comma) + if (allowTrailingComma && this$1.afterTrailingComma(close)) break + } else first = false + + var elt + if (allowEmpty && this$1.type === tt.comma) + elt = null + else if (this$1.type === tt.ellipsis) { + elt = this$1.parseSpread(refDestructuringErrors) + if (this$1.type === tt.comma && refDestructuringErrors && !refDestructuringErrors.trailingComma) { + refDestructuringErrors.trailingComma = this$1.start + } + } else + elt = this$1.parseMaybeAssign(false, refDestructuringErrors) + elts.push(elt) + } + return elts +} + +// Parse the next token as an identifier. If `liberal` is true (used +// when parsing properties), it will also convert keywords into +// identifiers. + +pp$3.parseIdent = function(liberal) { + var node = this.startNode() + if (liberal && this.options.allowReserved == "never") liberal = false + if (this.type === tt.name) { + if (!liberal && (this.strict ? this.reservedWordsStrict : this.reservedWords).test(this.value) && + (this.options.ecmaVersion >= 6 || + this.input.slice(this.start, this.end).indexOf("\\") == -1)) + this.raiseRecoverable(this.start, "The keyword '" + this.value + "' is reserved") + if (this.inGenerator && this.value === "yield") + this.raiseRecoverable(this.start, "Can not use 'yield' as identifier inside a generator") + if (this.inAsync && this.value === "await") + this.raiseRecoverable(this.start, "Can not use 'await' as identifier inside an async function") + node.name = this.value + } else if (liberal && this.type.keyword) { + node.name = this.type.keyword + } else { + this.unexpected() + } + this.next() + return this.finishNode(node, "Identifier") +} + +// Parses yield expression inside generator. + +pp$3.parseYield = function() { + if (!this.yieldPos) this.yieldPos = this.start + + var node = this.startNode() + this.next() + if (this.type == tt.semi || this.canInsertSemicolon() || (this.type != tt.star && !this.type.startsExpr)) { + node.delegate = false + node.argument = null + } else { + node.delegate = this.eat(tt.star) + node.argument = this.parseMaybeAssign() + } + return this.finishNode(node, "YieldExpression") +} + +pp$3.parseAwait = function() { + if (!this.awaitPos) this.awaitPos = this.start + + var node = this.startNode() + this.next() + node.argument = this.parseMaybeUnary(null, true) + return this.finishNode(node, "AwaitExpression") +} + +var pp$4 = Parser.prototype + +// This function is used to raise exceptions on parse errors. It +// takes an offset integer (into the current `input`) to indicate +// the location of the error, attaches the position to the end +// of the error message, and then raises a `SyntaxError` with that +// message. + +pp$4.raise = function(pos, message) { + var loc = getLineInfo(this.input, pos) + message += " (" + loc.line + ":" + loc.column + ")" + var err = new SyntaxError(message) + err.pos = pos; err.loc = loc; err.raisedAt = this.pos + throw err +} + +pp$4.raiseRecoverable = pp$4.raise + +pp$4.curPosition = function() { + if (this.options.locations) { + return new Position(this.curLine, this.pos - this.lineStart) + } +} + +var Node = function Node(parser, pos, loc) { + this.type = "" + this.start = pos + this.end = 0 + if (parser.options.locations) + this.loc = new SourceLocation(parser, loc) + if (parser.options.directSourceFile) + this.sourceFile = parser.options.directSourceFile + if (parser.options.ranges) + this.range = [pos, 0] +}; + +// Start an AST node, attaching a start offset. + +var pp$5 = Parser.prototype + +pp$5.startNode = function() { + return new Node(this, this.start, this.startLoc) +} + +pp$5.startNodeAt = function(pos, loc) { + return new Node(this, pos, loc) +} + +// Finish an AST node, adding `type` and `end` properties. + +function finishNodeAt(node, type, pos, loc) { + node.type = type + node.end = pos + if (this.options.locations) + node.loc.end = loc + if (this.options.ranges) + node.range[1] = pos + return node +} + +pp$5.finishNode = function(node, type) { + return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc) +} + +// Finish node at given position + +pp$5.finishNodeAt = function(node, type, pos, loc) { + return finishNodeAt.call(this, node, type, pos, loc) +} + +// The algorithm used to determine whether a regexp can appear at a +// given point in the program is loosely based on sweet.js' approach. +// See https://github.com/mozilla/sweet.js/wiki/design + +var TokContext = function TokContext(token, isExpr, preserveSpace, override) { + this.token = token + this.isExpr = !!isExpr + this.preserveSpace = !!preserveSpace + this.override = override +}; + +var types = { + b_stat: new TokContext("{", false), + b_expr: new TokContext("{", true), + b_tmpl: new TokContext("${", true), + p_stat: new TokContext("(", false), + p_expr: new TokContext("(", true), + q_tmpl: new TokContext("`", true, true, function (p) { return p.readTmplToken(); }), + f_expr: new TokContext("function", true) +} + +var pp$6 = Parser.prototype + +pp$6.initialContext = function() { + return [types.b_stat] +} + +pp$6.braceIsBlock = function(prevType) { + if (prevType === tt.colon) { + var parent = this.curContext() + if (parent === types.b_stat || parent === types.b_expr) + return !parent.isExpr + } + if (prevType === tt._return) + return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) + if (prevType === tt._else || prevType === tt.semi || prevType === tt.eof || prevType === tt.parenR) + return true + if (prevType == tt.braceL) + return this.curContext() === types.b_stat + return !this.exprAllowed +} + +pp$6.updateContext = function(prevType) { + var update, type = this.type + if (type.keyword && prevType == tt.dot) + this.exprAllowed = false + else if (update = type.updateContext) + update.call(this, prevType) + else + this.exprAllowed = type.beforeExpr +} - // Parse a regular `for` loop. The disambiguation code in - // `parseStatement` will already have parsed the init statement or - // expression. +// Token-specific context update code - pp$1.parseFor = function(node, init) { - node.init = init - this.expect(tt.semi) - node.test = this.type === tt.semi ? null : this.parseExpression() - this.expect(tt.semi) - node.update = this.type === tt.parenR ? null : this.parseExpression() - this.expect(tt.parenR) - node.body = this.parseStatement(false) - this.labels.pop() - return this.finishNode(node, "ForStatement") +tt.parenR.updateContext = tt.braceR.updateContext = function() { + if (this.context.length == 1) { + this.exprAllowed = true + return } - - // Parse a `for`/`in` and `for`/`of` loop, which are almost - // same from parser's perspective. - - pp$1.parseForIn = function(node, init) { - var type = this.type === tt._in ? "ForInStatement" : "ForOfStatement" - this.next() - node.left = init - node.right = this.parseExpression() - this.expect(tt.parenR) - node.body = this.parseStatement(false) - this.labels.pop() - return this.finishNode(node, type) + var out = this.context.pop() + if (out === types.b_stat && this.curContext() === types.f_expr) { + this.context.pop() + this.exprAllowed = false + } else if (out === types.b_tmpl) { + this.exprAllowed = true + } else { + this.exprAllowed = !out.isExpr + } +} + +tt.braceL.updateContext = function(prevType) { + this.context.push(this.braceIsBlock(prevType) ? types.b_stat : types.b_expr) + this.exprAllowed = true +} + +tt.dollarBraceL.updateContext = function() { + this.context.push(types.b_tmpl) + this.exprAllowed = true +} + +tt.parenL.updateContext = function(prevType) { + var statementParens = prevType === tt._if || prevType === tt._for || prevType === tt._with || prevType === tt._while + this.context.push(statementParens ? types.p_stat : types.p_expr) + this.exprAllowed = true +} + +tt.incDec.updateContext = function() { + // tokExprAllowed stays unchanged +} + +tt._function.updateContext = function(prevType) { + if (prevType.beforeExpr && prevType !== tt.semi && prevType !== tt._else && + !((prevType === tt.colon || prevType === tt.braceL) && this.curContext() === types.b_stat)) + this.context.push(types.f_expr) + this.exprAllowed = false +} + +tt.backQuote.updateContext = function() { + if (this.curContext() === types.q_tmpl) + this.context.pop() + else + this.context.push(types.q_tmpl) + this.exprAllowed = false +} + +// Object type used to represent tokens. Note that normally, tokens +// simply exist as properties on the parser object. This is only +// used for the onToken callback and the external tokenizer. + +var Token = function Token(p) { + this.type = p.type + this.value = p.value + this.start = p.start + this.end = p.end + if (p.options.locations) + this.loc = new SourceLocation(p, p.startLoc, p.endLoc) + if (p.options.ranges) + this.range = [p.start, p.end] +}; + +// ## Tokenizer + +var pp$7 = Parser.prototype + +// Are we running under Rhino? +var isRhino = typeof Packages == "object" && Object.prototype.toString.call(Packages) == "[object JavaPackage]" + +// Move to the next token + +pp$7.next = function() { + if (this.options.onToken) + this.options.onToken(new Token(this)) + + this.lastTokEnd = this.end + this.lastTokStart = this.start + this.lastTokEndLoc = this.endLoc + this.lastTokStartLoc = this.startLoc + this.nextToken() +} + +pp$7.getToken = function() { + this.next() + return new Token(this) +} + +// If we're in an ES6 environment, make parsers iterable +if (typeof Symbol !== "undefined") + pp$7[Symbol.iterator] = function () { + var self = this + return {next: function () { + var token = self.getToken() + return { + done: token.type === tt.eof, + value: token + } + }} } - // Parse a list of variable declarations. +// Toggle strict mode. Re-reads the next number or string to please +// pedantic tests (`"use strict"; 010;` should fail). - pp$1.parseVar = function(node, isFor, kind) { - var this$1 = this; +pp$7.setStrict = function(strict) { + var this$1 = this; - node.declarations = [] - node.kind = kind - for (;;) { - var decl = this$1.startNode() - this$1.parseVarId(decl) - if (this$1.eat(tt.eq)) { - decl.init = this$1.parseMaybeAssign(isFor) - } else if (kind === "const" && !(this$1.type === tt._in || (this$1.options.ecmaVersion >= 6 && this$1.isContextual("of")))) { - this$1.unexpected() - } else if (decl.id.type != "Identifier" && !(isFor && (this$1.type === tt._in || this$1.isContextual("of")))) { - this$1.raise(this$1.lastTokEnd, "Complex binding patterns require an initialization value") - } else { - decl.init = null - } - node.declarations.push(this$1.finishNode(decl, "VariableDeclarator")) - if (!this$1.eat(tt.comma)) break + this.strict = strict + if (this.type !== tt.num && this.type !== tt.string) return + this.pos = this.start + if (this.options.locations) { + while (this.pos < this.lineStart) { + this$1.lineStart = this$1.input.lastIndexOf("\n", this$1.lineStart - 2) + 1 + --this$1.curLine } - return node - } - - pp$1.parseVarId = function(decl) { - decl.id = this.parseBindingAtom() - this.checkLVal(decl.id, true) } + this.nextToken() +} - // Parse a function declaration or literal (depending on the - // `isStatement` parameter). +pp$7.curContext = function() { + return this.context[this.context.length - 1] +} - pp$1.parseFunction = function(node, isStatement, allowExpressionBody, isAsync) { - this.initFunction(node) - if (this.options.ecmaVersion >= 6 && !isAsync) - node.generator = this.eat(tt.star) - if (this.options.ecmaVersion >= 8) - node.async = !!isAsync +// Read a single token, updating the parser object's token-related +// properties. - if (isStatement) - node.id = this.parseIdent() +pp$7.nextToken = function() { + var curContext = this.curContext() + if (!curContext || !curContext.preserveSpace) this.skipSpace() - var oldInGen = this.inGenerator, oldInAsync = this.inAsync, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos - this.inGenerator = node.generator - this.inAsync = node.async - this.yieldPos = 0 - this.awaitPos = 0 + this.start = this.pos + if (this.options.locations) this.startLoc = this.curPosition() + if (this.pos >= this.input.length) return this.finishToken(tt.eof) - if (!isStatement && this.type === tt.name) - node.id = this.parseIdent() - this.parseFunctionParams(node) - this.parseFunctionBody(node, allowExpressionBody) + if (curContext.override) return curContext.override(this) + else this.readToken(this.fullCharCodeAtPos()) +} - this.inGenerator = oldInGen - this.inAsync = oldInAsync - this.yieldPos = oldYieldPos - this.awaitPos = oldAwaitPos - return this.finishNode(node, isStatement ? "FunctionDeclaration" : "FunctionExpression") - } +pp$7.readToken = function(code) { + // Identifier or keyword. '\uXXXX' sequences are allowed in + // identifiers, so '\' also dispatches to that. + if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */) + return this.readWord() - pp$1.parseFunctionParams = function(node) { - this.expect(tt.parenL) - node.params = this.parseBindingList(tt.parenR, false, this.options.ecmaVersion >= 8, true) - this.checkYieldAwaitInDefaultParams() - } + return this.getTokenFromCode(code) +} - // Parse a class declaration or literal (depending on the - // `isStatement` parameter). +pp$7.fullCharCodeAtPos = function() { + var code = this.input.charCodeAt(this.pos) + if (code <= 0xd7ff || code >= 0xe000) return code + var next = this.input.charCodeAt(this.pos + 1) + return (code << 10) + next - 0x35fdc00 +} - pp$1.parseClass = function(node, isStatement) { - var this$1 = this; +pp$7.skipBlockComment = function() { + var this$1 = this; - this.next() - this.parseClassId(node, isStatement) - this.parseClassSuper(node) - var classBody = this.startNode() - var hadConstructor = false - classBody.body = [] - this.expect(tt.braceL) - while (!this.eat(tt.braceR)) { - if (this$1.eat(tt.semi)) continue - var method = this$1.startNode() - var isGenerator = this$1.eat(tt.star) - var isAsync = false - var isMaybeStatic = this$1.type === tt.name && this$1.value === "static" - this$1.parsePropertyName(method) - method.static = isMaybeStatic && this$1.type !== tt.parenL - if (method.static) { - if (isGenerator) this$1.unexpected() - isGenerator = this$1.eat(tt.star) - this$1.parsePropertyName(method) - } - if (this$1.options.ecmaVersion >= 8 && !isGenerator && !method.computed && - method.key.type === "Identifier" && method.key.name === "async" && this$1.type !== tt.parenL && - !this$1.canInsertSemicolon()) { - isAsync = true - this$1.parsePropertyName(method) - } - method.kind = "method" - var isGetSet = false - if (!method.computed) { - var key = method.key; - if (!isGenerator && !isAsync && key.type === "Identifier" && this$1.type !== tt.parenL && (key.name === "get" || key.name === "set")) { - isGetSet = true - method.kind = key.name - key = this$1.parsePropertyName(method) - } - if (!method.static && (key.type === "Identifier" && key.name === "constructor" || - key.type === "Literal" && key.value === "constructor")) { - if (hadConstructor) this$1.raise(key.start, "Duplicate constructor in the same class") - if (isGetSet) this$1.raise(key.start, "Constructor can't have get/set modifier") - if (isGenerator) this$1.raise(key.start, "Constructor can't be a generator") - if (isAsync) this$1.raise(key.start, "Constructor can't be an async method") - method.kind = "constructor" - hadConstructor = true - } - } - this$1.parseClassMethod(classBody, method, isGenerator, isAsync) - if (isGetSet) { - var paramCount = method.kind === "get" ? 0 : 1 - if (method.value.params.length !== paramCount) { - var start = method.value.start - if (method.kind === "get") - this$1.raiseRecoverable(start, "getter should have no params") - else - this$1.raiseRecoverable(start, "setter should have exactly one param") - } else { - if (method.kind === "set" && method.value.params[0].type === "RestElement") - this$1.raiseRecoverable(method.value.params[0].start, "Setter cannot use rest params") - } - } + var startLoc = this.options.onComment && this.curPosition() + var start = this.pos, end = this.input.indexOf("*/", this.pos += 2) + if (end === -1) this.raise(this.pos - 2, "Unterminated comment") + this.pos = end + 2 + if (this.options.locations) { + lineBreakG.lastIndex = start + var match + while ((match = lineBreakG.exec(this.input)) && match.index < this.pos) { + ++this$1.curLine + this$1.lineStart = match.index + match[0].length } - node.body = this.finishNode(classBody, "ClassBody") - return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression") } + if (this.options.onComment) + this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos, + startLoc, this.curPosition()) +} - pp$1.parseClassMethod = function(classBody, method, isGenerator, isAsync) { - method.value = this.parseMethod(isGenerator, isAsync) - classBody.body.push(this.finishNode(method, "MethodDefinition")) - } +pp$7.skipLineComment = function(startSkip) { + var this$1 = this; - pp$1.parseClassId = function(node, isStatement) { - node.id = this.type === tt.name ? this.parseIdent() : isStatement ? this.unexpected() : null + var start = this.pos + var startLoc = this.options.onComment && this.curPosition() + var ch = this.input.charCodeAt(this.pos+=startSkip) + while (this.pos < this.input.length && ch !== 10 && ch !== 13 && ch !== 8232 && ch !== 8233) { + ++this$1.pos + ch = this$1.input.charCodeAt(this$1.pos) } + if (this.options.onComment) + this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos, + startLoc, this.curPosition()) +} - pp$1.parseClassSuper = function(node) { - node.superClass = this.eat(tt._extends) ? this.parseExprSubscripts() : null - } +// Called at the start of the parse and after every token. Skips +// whitespace and comments, and. - // Parses module export declaration. +pp$7.skipSpace = function() { + var this$1 = this; - pp$1.parseExport = function(node, exports) { - var this$1 = this; - - this.next() - // export * from '...' - if (this.eat(tt.star)) { - this.expectContextual("from") - node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected() - this.semicolon() - return this.finishNode(node, "ExportAllDeclaration") - } - if (this.eat(tt._default)) { // export default ... - this.checkExport(exports, "default", this.lastTokStart) - var parens = this.type == tt.parenL - var expr = this.parseMaybeAssign() - var needsSemi = true - if (!parens && (expr.type == "FunctionExpression" || - expr.type == "ClassExpression")) { - needsSemi = false - if (expr.id) { - expr.type = expr.type == "FunctionExpression" - ? "FunctionDeclaration" - : "ClassDeclaration" - } - } - node.declaration = expr - if (needsSemi) this.semicolon() - return this.finishNode(node, "ExportDefaultDeclaration") - } - // export var|const|let|function|class ... - if (this.shouldParseExportStatement()) { - node.declaration = this.parseStatement(true) - if (node.declaration.type === "VariableDeclaration") - this.checkVariableExport(exports, node.declaration.declarations) - else - this.checkExport(exports, node.declaration.id.name, node.declaration.id.start) - node.specifiers = [] - node.source = null - } else { // export { x, y as z } [from '...'] - node.declaration = null - node.specifiers = this.parseExportSpecifiers(exports) - if (this.eatContextual("from")) { - node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected() - } else { - // check for keywords used as local names - for (var i = 0; i < node.specifiers.length; i++) { - if (this$1.keywords.test(node.specifiers[i].local.name) || this$1.reservedWords.test(node.specifiers[i].local.name)) { - this$1.unexpected(node.specifiers[i].local.start) - } - } - - node.source = null - } - this.semicolon() - } - return this.finishNode(node, "ExportNamedDeclaration") - } - - pp$1.checkExport = function(exports, name, pos) { - if (!exports) return - if (Object.prototype.hasOwnProperty.call(exports, name)) - this.raiseRecoverable(pos, "Duplicate export '" + name + "'") - exports[name] = true - } - - pp$1.checkPatternExport = function(exports, pat) { - var this$1 = this; - - var type = pat.type - if (type == "Identifier") - this.checkExport(exports, pat.name, pat.start) - else if (type == "ObjectPattern") - for (var i = 0; i < pat.properties.length; ++i) - this$1.checkPatternExport(exports, pat.properties[i].value) - else if (type == "ArrayPattern") - for (var i$1 = 0; i$1 < pat.elements.length; ++i$1) { - var elt = pat.elements[i$1] - if (elt) this$1.checkPatternExport(exports, elt) - } - else if (type == "AssignmentPattern") - this.checkPatternExport(exports, pat.left) - else if (type == "ParenthesizedExpression") - this.checkPatternExport(exports, pat.expression) - } - - pp$1.checkVariableExport = function(exports, decls) { - var this$1 = this; - - if (!exports) return - for (var i = 0; i < decls.length; i++) - this$1.checkPatternExport(exports, decls[i].id) - } - - pp$1.shouldParseExportStatement = function() { - return this.type.keyword || this.isLet() || this.isAsyncFunction() - } - - // Parses a comma-separated list of module exports. - - pp$1.parseExportSpecifiers = function(exports) { - var this$1 = this; - - var nodes = [], first = true - // export { x, y as z } [from '...'] - this.expect(tt.braceL) - while (!this.eat(tt.braceR)) { - if (!first) { - this$1.expect(tt.comma) - if (this$1.afterTrailingComma(tt.braceR)) break - } else first = false - - var node = this$1.startNode() - node.local = this$1.parseIdent(this$1.type === tt._default) - node.exported = this$1.eatContextual("as") ? this$1.parseIdent(true) : node.local - this$1.checkExport(exports, node.exported.name, node.exported.start) - nodes.push(this$1.finishNode(node, "ExportSpecifier")) - } - return nodes - } - - // Parses import declaration. - - pp$1.parseImport = function(node) { - this.next() - // import '...' - if (this.type === tt.string) { - node.specifiers = empty - node.source = this.parseExprAtom() - } else { - node.specifiers = this.parseImportSpecifiers() - this.expectContextual("from") - node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected() - } - this.semicolon() - return this.finishNode(node, "ImportDeclaration") - } - - // Parses a comma-separated list of module imports. - - pp$1.parseImportSpecifiers = function() { - var this$1 = this; - - var nodes = [], first = true - if (this.type === tt.name) { - // import defaultObj, { x, y as z } from '...' - var node = this.startNode() - node.local = this.parseIdent() - this.checkLVal(node.local, true) - nodes.push(this.finishNode(node, "ImportDefaultSpecifier")) - if (!this.eat(tt.comma)) return nodes - } - if (this.type === tt.star) { - var node$1 = this.startNode() - this.next() - this.expectContextual("as") - node$1.local = this.parseIdent() - this.checkLVal(node$1.local, true) - nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier")) - return nodes - } - this.expect(tt.braceL) - while (!this.eat(tt.braceR)) { - if (!first) { - this$1.expect(tt.comma) - if (this$1.afterTrailingComma(tt.braceR)) break - } else first = false - - var node$2 = this$1.startNode() - node$2.imported = this$1.parseIdent(true) - if (this$1.eatContextual("as")) { - node$2.local = this$1.parseIdent() - } else { - node$2.local = node$2.imported - if (this$1.isKeyword(node$2.local.name)) this$1.unexpected(node$2.local.start) - if (this$1.reservedWordsStrict.test(node$2.local.name)) this$1.raiseRecoverable(node$2.local.start, "The keyword '" + node$2.local.name + "' is reserved") - } - this$1.checkLVal(node$2.local, true) - nodes.push(this$1.finishNode(node$2, "ImportSpecifier")) - } - return nodes - } - - var pp$2 = Parser.prototype - - // Convert existing expression atom to assignable pattern - // if possible. - - pp$2.toAssignable = function(node, isBinding) { - var this$1 = this; - - if (this.options.ecmaVersion >= 6 && node) { - switch (node.type) { - case "Identifier": - if (this.inAsync && node.name === "await") - this.raise(node.start, "Can not use 'await' as identifier inside an async function") - break - - case "ObjectPattern": - case "ArrayPattern": - break - - case "ObjectExpression": - node.type = "ObjectPattern" - for (var i = 0; i < node.properties.length; i++) { - var prop = node.properties[i] - if (prop.kind !== "init") this$1.raise(prop.key.start, "Object pattern can't contain getter or setter") - this$1.toAssignable(prop.value, isBinding) - } - break - - case "ArrayExpression": - node.type = "ArrayPattern" - this.toAssignableList(node.elements, isBinding) - break - - case "AssignmentExpression": - if (node.operator === "=") { - node.type = "AssignmentPattern" - delete node.operator - this.toAssignable(node.left, isBinding) - // falls through to AssignmentPattern - } else { - this.raise(node.left.end, "Only '=' operator can be used for specifying default value.") - break - } - - case "AssignmentPattern": - break - - case "ParenthesizedExpression": - node.expression = this.toAssignable(node.expression, isBinding) - break - - case "MemberExpression": - if (!isBinding) break - - default: - this.raise(node.start, "Assigning to rvalue") - } - } - return node - } - - // Convert list of expression atoms to binding list. - - pp$2.toAssignableList = function(exprList, isBinding) { - var this$1 = this; - - var end = exprList.length - if (end) { - var last = exprList[end - 1] - if (last && last.type == "RestElement") { - --end - } else if (last && last.type == "SpreadElement") { - last.type = "RestElement" - var arg = last.argument - this.toAssignable(arg, isBinding) - if (arg.type !== "Identifier" && arg.type !== "MemberExpression" && arg.type !== "ArrayPattern") - this.unexpected(arg.start) - --end - } - - if (isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier") - this.unexpected(last.argument.start) - } - for (var i = 0; i < end; i++) { - var elt = exprList[i] - if (elt) this$1.toAssignable(elt, isBinding) - } - return exprList - } - - // Parses spread element. - - pp$2.parseSpread = function(refDestructuringErrors) { - var node = this.startNode() - this.next() - node.argument = this.parseMaybeAssign(false, refDestructuringErrors) - return this.finishNode(node, "SpreadElement") - } - - pp$2.parseRest = function(allowNonIdent) { - var node = this.startNode() - this.next() - - // RestElement inside of a function parameter must be an identifier - if (allowNonIdent) node.argument = this.type === tt.name ? this.parseIdent() : this.unexpected() - else node.argument = this.type === tt.name || this.type === tt.bracketL ? this.parseBindingAtom() : this.unexpected() - - return this.finishNode(node, "RestElement") - } - - // Parses lvalue (assignable) atom. - - pp$2.parseBindingAtom = function() { - if (this.options.ecmaVersion < 6) return this.parseIdent() - switch (this.type) { - case tt.name: - return this.parseIdent() - - case tt.bracketL: - var node = this.startNode() - this.next() - node.elements = this.parseBindingList(tt.bracketR, true, true) - return this.finishNode(node, "ArrayPattern") - - case tt.braceL: - return this.parseObj(true) - - default: - this.unexpected() - } - } - - pp$2.parseBindingList = function(close, allowEmpty, allowTrailingComma, allowNonIdent) { - var this$1 = this; - - var elts = [], first = true - while (!this.eat(close)) { - if (first) first = false - else this$1.expect(tt.comma) - if (allowEmpty && this$1.type === tt.comma) { - elts.push(null) - } else if (allowTrailingComma && this$1.afterTrailingComma(close)) { - break - } else if (this$1.type === tt.ellipsis) { - var rest = this$1.parseRest(allowNonIdent) - this$1.parseBindingListItem(rest) - elts.push(rest) - if (this$1.type === tt.comma) this$1.raise(this$1.start, "Comma is not permitted after the rest element") - this$1.expect(close) - break - } else { - var elem = this$1.parseMaybeDefault(this$1.start, this$1.startLoc) - this$1.parseBindingListItem(elem) - elts.push(elem) - } - } - return elts - } - - pp$2.parseBindingListItem = function(param) { - return param - } - - // Parses assignment pattern around given atom if possible. - - pp$2.parseMaybeDefault = function(startPos, startLoc, left) { - left = left || this.parseBindingAtom() - if (this.options.ecmaVersion < 6 || !this.eat(tt.eq)) return left - var node = this.startNodeAt(startPos, startLoc) - node.left = left - node.right = this.parseMaybeAssign() - return this.finishNode(node, "AssignmentPattern") - } - - // Verify that a node is an lval — something that can be assigned - // to. - - pp$2.checkLVal = function(expr, isBinding, checkClashes) { - var this$1 = this; - - switch (expr.type) { - case "Identifier": - if (this.strict && this.reservedWordsStrictBind.test(expr.name)) - this.raiseRecoverable(expr.start, (isBinding ? "Binding " : "Assigning to ") + expr.name + " in strict mode") - if (checkClashes) { - if (has(checkClashes, expr.name)) - this.raiseRecoverable(expr.start, "Argument name clash") - checkClashes[expr.name] = true - } - break - - case "MemberExpression": - if (isBinding) this.raiseRecoverable(expr.start, (isBinding ? "Binding" : "Assigning to") + " member expression") - break - - case "ObjectPattern": - for (var i = 0; i < expr.properties.length; i++) - this$1.checkLVal(expr.properties[i].value, isBinding, checkClashes) - break - - case "ArrayPattern": - for (var i$1 = 0; i$1 < expr.elements.length; i$1++) { - var elem = expr.elements[i$1] - if (elem) this$1.checkLVal(elem, isBinding, checkClashes) - } - break - - case "AssignmentPattern": - this.checkLVal(expr.left, isBinding, checkClashes) - break - - case "RestElement": - this.checkLVal(expr.argument, isBinding, checkClashes) - break - - case "ParenthesizedExpression": - this.checkLVal(expr.expression, isBinding, checkClashes) - break - - default: - this.raise(expr.start, (isBinding ? "Binding" : "Assigning to") + " rvalue") - } - } - - var pp$3 = Parser.prototype - - // Check if property name clashes with already added. - // Object/class getters and setters are not allowed to clash — - // either with each other or with an init property — and in - // strict mode, init properties are also not allowed to be repeated. - - pp$3.checkPropClash = function(prop, propHash) { - if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand)) - return - var key = prop.key; - var name - switch (key.type) { - case "Identifier": name = key.name; break - case "Literal": name = String(key.value); break - default: return - } - var kind = prop.kind; - if (this.options.ecmaVersion >= 6) { - if (name === "__proto__" && kind === "init") { - if (propHash.proto) this.raiseRecoverable(key.start, "Redefinition of __proto__ property") - propHash.proto = true - } - return - } - name = "$" + name - var other = propHash[name] - if (other) { - var isGetSet = kind !== "init" - if ((this.strict || isGetSet) && other[kind] || !(isGetSet ^ other.init)) - this.raiseRecoverable(key.start, "Redefinition of property") - } else { - other = propHash[name] = { - init: false, - get: false, - set: false - } - } - other[kind] = true - } - - // ### Expression parsing - - // These nest, from the most general expression type at the top to - // 'atomic', nondivisible expression types at the bottom. Most of - // the functions will simply let the function(s) below them parse, - // and, *if* the syntactic construct they handle is present, wrap - // the AST node that the inner parser gave them in another node. - - // Parse a full expression. The optional arguments are used to - // forbid the `in` operator (in for loops initalization expressions) - // and provide reference for storing '=' operator inside shorthand - // property assignment in contexts where both object expression - // and object pattern might appear (so it's possible to raise - // delayed syntax error at correct position). - - pp$3.parseExpression = function(noIn, refDestructuringErrors) { - var this$1 = this; - - var startPos = this.start, startLoc = this.startLoc - var expr = this.parseMaybeAssign(noIn, refDestructuringErrors) - if (this.type === tt.comma) { - var node = this.startNodeAt(startPos, startLoc) - node.expressions = [expr] - while (this.eat(tt.comma)) node.expressions.push(this$1.parseMaybeAssign(noIn, refDestructuringErrors)) - return this.finishNode(node, "SequenceExpression") - } - return expr - } - - // Parse an assignment expression. This includes applications of - // operators like `+=`. - - pp$3.parseMaybeAssign = function(noIn, refDestructuringErrors, afterLeftParse) { - if (this.inGenerator && this.isContextual("yield")) return this.parseYield() - - var ownDestructuringErrors = false - if (!refDestructuringErrors) { - refDestructuringErrors = new DestructuringErrors - ownDestructuringErrors = true - } - var startPos = this.start, startLoc = this.startLoc - if (this.type == tt.parenL || this.type == tt.name) - this.potentialArrowAt = this.start - var left = this.parseMaybeConditional(noIn, refDestructuringErrors) - if (afterLeftParse) left = afterLeftParse.call(this, left, startPos, startLoc) - if (this.type.isAssign) { - this.checkPatternErrors(refDestructuringErrors, true) - if (!ownDestructuringErrors) DestructuringErrors.call(refDestructuringErrors) - var node = this.startNodeAt(startPos, startLoc) - node.operator = this.value - node.left = this.type === tt.eq ? this.toAssignable(left) : left - refDestructuringErrors.shorthandAssign = 0 // reset because shorthand default was used correctly - this.checkLVal(left) - this.next() - node.right = this.parseMaybeAssign(noIn) - return this.finishNode(node, "AssignmentExpression") - } else { - if (ownDestructuringErrors) this.checkExpressionErrors(refDestructuringErrors, true) - } - return left - } - - // Parse a ternary conditional (`?:`) operator. - - pp$3.parseMaybeConditional = function(noIn, refDestructuringErrors) { - var startPos = this.start, startLoc = this.startLoc - var expr = this.parseExprOps(noIn, refDestructuringErrors) - if (this.checkExpressionErrors(refDestructuringErrors)) return expr - if (this.eat(tt.question)) { - var node = this.startNodeAt(startPos, startLoc) - node.test = expr - node.consequent = this.parseMaybeAssign() - this.expect(tt.colon) - node.alternate = this.parseMaybeAssign(noIn) - return this.finishNode(node, "ConditionalExpression") - } - return expr - } - - // Start the precedence parser. - - pp$3.parseExprOps = function(noIn, refDestructuringErrors) { - var startPos = this.start, startLoc = this.startLoc - var expr = this.parseMaybeUnary(refDestructuringErrors, false) - if (this.checkExpressionErrors(refDestructuringErrors)) return expr - return this.parseExprOp(expr, startPos, startLoc, -1, noIn) - } - - // Parse binary operators with the operator precedence parsing - // algorithm. `left` is the left-hand side of the operator. - // `minPrec` provides context that allows the function to stop and - // defer further parser to one of its callers when it encounters an - // operator that has a lower precedence than the set it is parsing. - - pp$3.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, noIn) { - var prec = this.type.binop - if (prec != null && (!noIn || this.type !== tt._in)) { - if (prec > minPrec) { - var logical = this.type === tt.logicalOR || this.type === tt.logicalAND - var op = this.value - this.next() - var startPos = this.start, startLoc = this.startLoc - var right = this.parseExprOp(this.parseMaybeUnary(null, false), startPos, startLoc, prec, noIn) - var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical) - return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn) - } - } - return left - } - - pp$3.buildBinary = function(startPos, startLoc, left, right, op, logical) { - var node = this.startNodeAt(startPos, startLoc) - node.left = left - node.operator = op - node.right = right - return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression") - } - - // Parse unary operators, both prefix and postfix. - - pp$3.parseMaybeUnary = function(refDestructuringErrors, sawUnary) { - var this$1 = this; - - var startPos = this.start, startLoc = this.startLoc, expr - if (this.inAsync && this.isContextual("await")) { - expr = this.parseAwait(refDestructuringErrors) - sawUnary = true - } else if (this.type.prefix) { - var node = this.startNode(), update = this.type === tt.incDec - node.operator = this.value - node.prefix = true - this.next() - node.argument = this.parseMaybeUnary(null, true) - this.checkExpressionErrors(refDestructuringErrors, true) - if (update) this.checkLVal(node.argument) - else if (this.strict && node.operator === "delete" && - node.argument.type === "Identifier") - this.raiseRecoverable(node.start, "Deleting local variable in strict mode") - else sawUnary = true - expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression") - } else { - expr = this.parseExprSubscripts(refDestructuringErrors) - if (this.checkExpressionErrors(refDestructuringErrors)) return expr - while (this.type.postfix && !this.canInsertSemicolon()) { - var node$1 = this$1.startNodeAt(startPos, startLoc) - node$1.operator = this$1.value - node$1.prefix = false - node$1.argument = expr - this$1.checkLVal(expr) - this$1.next() - expr = this$1.finishNode(node$1, "UpdateExpression") - } - } - - if (!sawUnary && this.eat(tt.starstar)) - return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false), "**", false) - else - return expr - } - - // Parse call, dot, and `[]`-subscript expressions. - - pp$3.parseExprSubscripts = function(refDestructuringErrors) { - var startPos = this.start, startLoc = this.startLoc - var expr = this.parseExprAtom(refDestructuringErrors) - var skipArrowSubscripts = expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")" - if (this.checkExpressionErrors(refDestructuringErrors) || skipArrowSubscripts) return expr - return this.parseSubscripts(expr, startPos, startLoc) - } - - pp$3.parseSubscripts = function(base, startPos, startLoc, noCalls) { - var this$1 = this; - - for (;;) { - var maybeAsyncArrow = this$1.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" && !this$1.canInsertSemicolon() - if (this$1.eat(tt.dot)) { - var node = this$1.startNodeAt(startPos, startLoc) - node.object = base - node.property = this$1.parseIdent(true) - node.computed = false - base = this$1.finishNode(node, "MemberExpression") - } else if (this$1.eat(tt.bracketL)) { - var node$1 = this$1.startNodeAt(startPos, startLoc) - node$1.object = base - node$1.property = this$1.parseExpression() - node$1.computed = true - this$1.expect(tt.bracketR) - base = this$1.finishNode(node$1, "MemberExpression") - } else if (!noCalls && this$1.eat(tt.parenL)) { - var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this$1.yieldPos, oldAwaitPos = this$1.awaitPos - this$1.yieldPos = 0 - this$1.awaitPos = 0 - var exprList = this$1.parseExprList(tt.parenR, this$1.options.ecmaVersion >= 8, false, refDestructuringErrors) - if (maybeAsyncArrow && !this$1.canInsertSemicolon() && this$1.eat(tt.arrow)) { - this$1.checkPatternErrors(refDestructuringErrors, true) - this$1.checkYieldAwaitInDefaultParams() - this$1.yieldPos = oldYieldPos - this$1.awaitPos = oldAwaitPos - return this$1.parseArrowExpression(this$1.startNodeAt(startPos, startLoc), exprList, true) - } - this$1.checkExpressionErrors(refDestructuringErrors, true) - this$1.yieldPos = oldYieldPos || this$1.yieldPos - this$1.awaitPos = oldAwaitPos || this$1.awaitPos - var node$2 = this$1.startNodeAt(startPos, startLoc) - node$2.callee = base - node$2.arguments = exprList - base = this$1.finishNode(node$2, "CallExpression") - } else if (this$1.type === tt.backQuote) { - var node$3 = this$1.startNodeAt(startPos, startLoc) - node$3.tag = base - node$3.quasi = this$1.parseTemplate() - base = this$1.finishNode(node$3, "TaggedTemplateExpression") - } else { - return base - } - } - } - - // Parse an atomic expression — either a single token that is an - // expression, an expression started by a keyword like `function` or - // `new`, or an expression wrapped in punctuation like `()`, `[]`, - // or `{}`. - - pp$3.parseExprAtom = function(refDestructuringErrors) { - var node, canBeArrow = this.potentialArrowAt == this.start - switch (this.type) { - case tt._super: - if (!this.inFunction) - this.raise(this.start, "'super' outside of function or class") - - case tt._this: - var type = this.type === tt._this ? "ThisExpression" : "Super" - node = this.startNode() - this.next() - return this.finishNode(node, type) - - case tt.name: - var startPos = this.start, startLoc = this.startLoc - var id = this.parseIdent(this.type !== tt.name) - if (this.options.ecmaVersion >= 8 && id.name === "async" && !this.canInsertSemicolon() && this.eat(tt._function)) - return this.parseFunction(this.startNodeAt(startPos, startLoc), false, false, true) - if (canBeArrow && !this.canInsertSemicolon()) { - if (this.eat(tt.arrow)) - return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false) - if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === tt.name) { - id = this.parseIdent() - if (this.canInsertSemicolon() || !this.eat(tt.arrow)) - this.unexpected() - return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true) - } - } - return id - - case tt.regexp: - var value = this.value - node = this.parseLiteral(value.value) - node.regex = {pattern: value.pattern, flags: value.flags} - return node - - case tt.num: case tt.string: - return this.parseLiteral(this.value) - - case tt._null: case tt._true: case tt._false: - node = this.startNode() - node.value = this.type === tt._null ? null : this.type === tt._true - node.raw = this.type.keyword - this.next() - return this.finishNode(node, "Literal") - - case tt.parenL: - return this.parseParenAndDistinguishExpression(canBeArrow) - - case tt.bracketL: - node = this.startNode() - this.next() - node.elements = this.parseExprList(tt.bracketR, true, true, refDestructuringErrors) - return this.finishNode(node, "ArrayExpression") - - case tt.braceL: - return this.parseObj(false, refDestructuringErrors) - - case tt._function: - node = this.startNode() - this.next() - return this.parseFunction(node, false) - - case tt._class: - return this.parseClass(this.startNode(), false) - - case tt._new: - return this.parseNew() - - case tt.backQuote: - return this.parseTemplate() - - default: - this.unexpected() - } - } - - pp$3.parseLiteral = function(value) { - var node = this.startNode() - node.value = value - node.raw = this.input.slice(this.start, this.end) - this.next() - return this.finishNode(node, "Literal") - } - - pp$3.parseParenExpression = function() { - this.expect(tt.parenL) - var val = this.parseExpression() - this.expect(tt.parenR) - return val - } - - pp$3.parseParenAndDistinguishExpression = function(canBeArrow) { - var this$1 = this; - - var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8 - if (this.options.ecmaVersion >= 6) { - this.next() - - var innerStartPos = this.start, innerStartLoc = this.startLoc - var exprList = [], first = true, lastIsComma = false - var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart, innerParenStart - this.yieldPos = 0 - this.awaitPos = 0 - while (this.type !== tt.parenR) { - first ? first = false : this$1.expect(tt.comma) - if (allowTrailingComma && this$1.afterTrailingComma(tt.parenR, true)) { - lastIsComma = true - break - } else if (this$1.type === tt.ellipsis) { - spreadStart = this$1.start - exprList.push(this$1.parseParenItem(this$1.parseRest())) - if (this$1.type === tt.comma) this$1.raise(this$1.start, "Comma is not permitted after the rest element") - break - } else { - if (this$1.type === tt.parenL && !innerParenStart) { - innerParenStart = this$1.start - } - exprList.push(this$1.parseMaybeAssign(false, refDestructuringErrors, this$1.parseParenItem)) - } - } - var innerEndPos = this.start, innerEndLoc = this.startLoc - this.expect(tt.parenR) - - if (canBeArrow && !this.canInsertSemicolon() && this.eat(tt.arrow)) { - this.checkPatternErrors(refDestructuringErrors, true) - this.checkYieldAwaitInDefaultParams() - if (innerParenStart) this.unexpected(innerParenStart) - this.yieldPos = oldYieldPos - this.awaitPos = oldAwaitPos - return this.parseParenArrowList(startPos, startLoc, exprList) - } - - if (!exprList.length || lastIsComma) this.unexpected(this.lastTokStart) - if (spreadStart) this.unexpected(spreadStart) - this.checkExpressionErrors(refDestructuringErrors, true) - this.yieldPos = oldYieldPos || this.yieldPos - this.awaitPos = oldAwaitPos || this.awaitPos - - if (exprList.length > 1) { - val = this.startNodeAt(innerStartPos, innerStartLoc) - val.expressions = exprList - this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc) - } else { - val = exprList[0] - } - } else { - val = this.parseParenExpression() - } - - if (this.options.preserveParens) { - var par = this.startNodeAt(startPos, startLoc) - par.expression = val - return this.finishNode(par, "ParenthesizedExpression") - } else { - return val - } - } - - pp$3.parseParenItem = function(item) { - return item - } - - pp$3.parseParenArrowList = function(startPos, startLoc, exprList) { - return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList) - } - - // New's precedence is slightly tricky. It must allow its argument to - // be a `[]` or dot subscript expression, but not a call — at least, - // not without wrapping it in parentheses. Thus, it uses the noCalls - // argument to parseSubscripts to prevent it from consuming the - // argument list. - - var empty$1 = [] - - pp$3.parseNew = function() { - var node = this.startNode() - var meta = this.parseIdent(true) - if (this.options.ecmaVersion >= 6 && this.eat(tt.dot)) { - node.meta = meta - node.property = this.parseIdent(true) - if (node.property.name !== "target") - this.raiseRecoverable(node.property.start, "The only valid meta property for new is new.target") - if (!this.inFunction) - this.raiseRecoverable(node.start, "new.target can only be used in functions") - return this.finishNode(node, "MetaProperty") - } - var startPos = this.start, startLoc = this.startLoc - node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true) - if (this.eat(tt.parenL)) node.arguments = this.parseExprList(tt.parenR, this.options.ecmaVersion >= 8, false) - else node.arguments = empty$1 - return this.finishNode(node, "NewExpression") - } - - // Parse template expression. - - pp$3.parseTemplateElement = function() { - var elem = this.startNode() - elem.value = { - raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, '\n'), - cooked: this.value - } - this.next() - elem.tail = this.type === tt.backQuote - return this.finishNode(elem, "TemplateElement") - } - - pp$3.parseTemplate = function() { - var this$1 = this; - - var node = this.startNode() - this.next() - node.expressions = [] - var curElt = this.parseTemplateElement() - node.quasis = [curElt] - while (!curElt.tail) { - this$1.expect(tt.dollarBraceL) - node.expressions.push(this$1.parseExpression()) - this$1.expect(tt.braceR) - node.quasis.push(curElt = this$1.parseTemplateElement()) - } - this.next() - return this.finishNode(node, "TemplateLiteral") - } - - // Parse an object literal or binding pattern. - - pp$3.parseObj = function(isPattern, refDestructuringErrors) { - var this$1 = this; - - var node = this.startNode(), first = true, propHash = {} - node.properties = [] - this.next() - while (!this.eat(tt.braceR)) { - if (!first) { - this$1.expect(tt.comma) - if (this$1.afterTrailingComma(tt.braceR)) break - } else first = false - - var prop = this$1.startNode(), isGenerator, isAsync, startPos, startLoc - if (this$1.options.ecmaVersion >= 6) { - prop.method = false - prop.shorthand = false - if (isPattern || refDestructuringErrors) { - startPos = this$1.start - startLoc = this$1.startLoc - } - if (!isPattern) - isGenerator = this$1.eat(tt.star) - } - this$1.parsePropertyName(prop) - if (!isPattern && this$1.options.ecmaVersion >= 8 && !isGenerator && !prop.computed && - prop.key.type === "Identifier" && prop.key.name === "async" && this$1.type !== tt.parenL && - this$1.type !== tt.colon && !this$1.canInsertSemicolon()) { - isAsync = true - this$1.parsePropertyName(prop, refDestructuringErrors) - } else { - isAsync = false - } - this$1.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors) - this$1.checkPropClash(prop, propHash) - node.properties.push(this$1.finishNode(prop, "Property")) - } - return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression") - } - - pp$3.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors) { - if ((isGenerator || isAsync) && this.type === tt.colon) - this.unexpected() - - if (this.eat(tt.colon)) { - prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors) - prop.kind = "init" - } else if (this.options.ecmaVersion >= 6 && this.type === tt.parenL) { - if (isPattern) this.unexpected() - prop.kind = "init" - prop.method = true - prop.value = this.parseMethod(isGenerator, isAsync) - } else if (this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" && - (prop.key.name === "get" || prop.key.name === "set") && - (this.type != tt.comma && this.type != tt.braceR)) { - if (isGenerator || isAsync || isPattern) this.unexpected() - prop.kind = prop.key.name - this.parsePropertyName(prop) - prop.value = this.parseMethod(false) - var paramCount = prop.kind === "get" ? 0 : 1 - if (prop.value.params.length !== paramCount) { - var start = prop.value.start - if (prop.kind === "get") - this.raiseRecoverable(start, "getter should have no params") - else - this.raiseRecoverable(start, "setter should have exactly one param") - } else { - if (prop.kind === "set" && prop.value.params[0].type === "RestElement") - this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params") - } - } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") { - if (this.keywords.test(prop.key.name) || - (this.strict ? this.reservedWordsStrict : this.reservedWords).test(prop.key.name) || - (this.inGenerator && prop.key.name == "yield") || - (this.inAsync && prop.key.name == "await")) - this.raiseRecoverable(prop.key.start, "'" + prop.key.name + "' can not be used as shorthand property") - prop.kind = "init" - if (isPattern) { - prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key) - } else if (this.type === tt.eq && refDestructuringErrors) { - if (!refDestructuringErrors.shorthandAssign) - refDestructuringErrors.shorthandAssign = this.start - prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key) - } else { - prop.value = prop.key - } - prop.shorthand = true - } else this.unexpected() - } - - pp$3.parsePropertyName = function(prop) { - if (this.options.ecmaVersion >= 6) { - if (this.eat(tt.bracketL)) { - prop.computed = true - prop.key = this.parseMaybeAssign() - this.expect(tt.bracketR) - return prop.key - } else { - prop.computed = false - } - } - return prop.key = this.type === tt.num || this.type === tt.string ? this.parseExprAtom() : this.parseIdent(true) - } - - // Initialize empty function node. - - pp$3.initFunction = function(node) { - node.id = null - if (this.options.ecmaVersion >= 6) { - node.generator = false - node.expression = false - } - if (this.options.ecmaVersion >= 8) - node.async = false - } - - // Parse object or class method. - - pp$3.parseMethod = function(isGenerator, isAsync) { - var node = this.startNode(), oldInGen = this.inGenerator, oldInAsync = this.inAsync, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos - - this.initFunction(node) - if (this.options.ecmaVersion >= 6) - node.generator = isGenerator - if (this.options.ecmaVersion >= 8) - node.async = !!isAsync - - this.inGenerator = node.generator - this.inAsync = node.async - this.yieldPos = 0 - this.awaitPos = 0 - - this.expect(tt.parenL) - node.params = this.parseBindingList(tt.parenR, false, this.options.ecmaVersion >= 8) - this.checkYieldAwaitInDefaultParams() - this.parseFunctionBody(node, false) - - this.inGenerator = oldInGen - this.inAsync = oldInAsync - this.yieldPos = oldYieldPos - this.awaitPos = oldAwaitPos - return this.finishNode(node, "FunctionExpression") - } - - // Parse arrow function expression with given parameters. - - pp$3.parseArrowExpression = function(node, params, isAsync) { - var oldInGen = this.inGenerator, oldInAsync = this.inAsync, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos - - this.initFunction(node) - if (this.options.ecmaVersion >= 8) - node.async = !!isAsync - - this.inGenerator = false - this.inAsync = node.async - this.yieldPos = 0 - this.awaitPos = 0 - - node.params = this.toAssignableList(params, true) - this.parseFunctionBody(node, true) - - this.inGenerator = oldInGen - this.inAsync = oldInAsync - this.yieldPos = oldYieldPos - this.awaitPos = oldAwaitPos - return this.finishNode(node, "ArrowFunctionExpression") - } - - // Parse function body and check parameters. - - pp$3.parseFunctionBody = function(node, isArrowFunction) { - var isExpression = isArrowFunction && this.type !== tt.braceL - - if (isExpression) { - node.body = this.parseMaybeAssign() - node.expression = true - } else { - // Start a new scope with regard to labels and the `inFunction` - // flag (restore them to their old value afterwards). - var oldInFunc = this.inFunction, oldLabels = this.labels - this.inFunction = true; this.labels = [] - node.body = this.parseBlock(true) - node.expression = false - this.inFunction = oldInFunc; this.labels = oldLabels - } - - // If this is a strict mode function, verify that argument names - // are not repeated, and it does not try to bind the words `eval` - // or `arguments`. - var useStrict = (!isExpression && node.body.body.length && this.isUseStrict(node.body.body[0])) ? node.body.body[0] : null - if (useStrict && this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params)) - this.raiseRecoverable(useStrict.start, "Illegal 'use strict' directive in function with non-simple parameter list") - - if (this.strict || useStrict) { - var oldStrict = this.strict - this.strict = true - if (node.id) - this.checkLVal(node.id, true) - this.checkParams(node) - this.strict = oldStrict - } else if (isArrowFunction || !this.isSimpleParamList(node.params)) { - this.checkParams(node) - } - } - - pp$3.isSimpleParamList = function(params) { - for (var i = 0; i < params.length; i++) - if (params[i].type !== "Identifier") return false - return true - } - - // Checks function params for various disallowed patterns such as using "eval" - // or "arguments" and duplicate parameters. - - pp$3.checkParams = function(node) { - var this$1 = this; - - var nameHash = {} - for (var i = 0; i < node.params.length; i++) this$1.checkLVal(node.params[i], true, nameHash) - } - - // Parses a comma-separated list of expressions, and returns them as - // an array. `close` is the token type that ends the list, and - // `allowEmpty` can be turned on to allow subsequent commas with - // nothing in between them to be parsed as `null` (which is needed - // for array literals). - - pp$3.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) { - var this$1 = this; - - var elts = [], first = true - while (!this.eat(close)) { - if (!first) { - this$1.expect(tt.comma) - if (allowTrailingComma && this$1.afterTrailingComma(close)) break - } else first = false - - var elt - if (allowEmpty && this$1.type === tt.comma) - elt = null - else if (this$1.type === tt.ellipsis) { - elt = this$1.parseSpread(refDestructuringErrors) - if (this$1.type === tt.comma && refDestructuringErrors && !refDestructuringErrors.trailingComma) { - refDestructuringErrors.trailingComma = this$1.start - } - } else - elt = this$1.parseMaybeAssign(false, refDestructuringErrors) - elts.push(elt) - } - return elts - } - - // Parse the next token as an identifier. If `liberal` is true (used - // when parsing properties), it will also convert keywords into - // identifiers. - - pp$3.parseIdent = function(liberal) { - var node = this.startNode() - if (liberal && this.options.allowReserved == "never") liberal = false - if (this.type === tt.name) { - if (!liberal && (this.strict ? this.reservedWordsStrict : this.reservedWords).test(this.value) && - (this.options.ecmaVersion >= 6 || - this.input.slice(this.start, this.end).indexOf("\\") == -1)) - this.raiseRecoverable(this.start, "The keyword '" + this.value + "' is reserved") - if (this.inGenerator && this.value === "yield") - this.raiseRecoverable(this.start, "Can not use 'yield' as identifier inside a generator") - if (this.inAsync && this.value === "await") - this.raiseRecoverable(this.start, "Can not use 'await' as identifier inside an async function") - node.name = this.value - } else if (liberal && this.type.keyword) { - node.name = this.type.keyword - } else { - this.unexpected() - } - this.next() - return this.finishNode(node, "Identifier") - } - - // Parses yield expression inside generator. - - pp$3.parseYield = function() { - if (!this.yieldPos) this.yieldPos = this.start - - var node = this.startNode() - this.next() - if (this.type == tt.semi || this.canInsertSemicolon() || (this.type != tt.star && !this.type.startsExpr)) { - node.delegate = false - node.argument = null - } else { - node.delegate = this.eat(tt.star) - node.argument = this.parseMaybeAssign() - } - return this.finishNode(node, "YieldExpression") - } - - pp$3.parseAwait = function() { - if (!this.awaitPos) this.awaitPos = this.start - - var node = this.startNode() - this.next() - node.argument = this.parseMaybeUnary(null, true) - return this.finishNode(node, "AwaitExpression") - } - - var pp$4 = Parser.prototype - - // This function is used to raise exceptions on parse errors. It - // takes an offset integer (into the current `input`) to indicate - // the location of the error, attaches the position to the end - // of the error message, and then raises a `SyntaxError` with that - // message. - - pp$4.raise = function(pos, message) { - var loc = getLineInfo(this.input, pos) - message += " (" + loc.line + ":" + loc.column + ")" - var err = new SyntaxError(message) - err.pos = pos; err.loc = loc; err.raisedAt = this.pos - throw err - } - - pp$4.raiseRecoverable = pp$4.raise - - pp$4.curPosition = function() { - if (this.options.locations) { - return new Position(this.curLine, this.pos - this.lineStart) - } - } - - var Node = function Node(parser, pos, loc) { - this.type = "" - this.start = pos - this.end = 0 - if (parser.options.locations) - this.loc = new SourceLocation(parser, loc) - if (parser.options.directSourceFile) - this.sourceFile = parser.options.directSourceFile - if (parser.options.ranges) - this.range = [pos, 0] - }; - - // Start an AST node, attaching a start offset. - - var pp$5 = Parser.prototype - - pp$5.startNode = function() { - return new Node(this, this.start, this.startLoc) - } - - pp$5.startNodeAt = function(pos, loc) { - return new Node(this, pos, loc) - } - - // Finish an AST node, adding `type` and `end` properties. - - function finishNodeAt(node, type, pos, loc) { - node.type = type - node.end = pos - if (this.options.locations) - node.loc.end = loc - if (this.options.ranges) - node.range[1] = pos - return node - } - - pp$5.finishNode = function(node, type) { - return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc) - } - - // Finish node at given position - - pp$5.finishNodeAt = function(node, type, pos, loc) { - return finishNodeAt.call(this, node, type, pos, loc) - } - - var TokContext = function TokContext(token, isExpr, preserveSpace, override) { - this.token = token - this.isExpr = !!isExpr - this.preserveSpace = !!preserveSpace - this.override = override - }; - - var types = { - b_stat: new TokContext("{", false), - b_expr: new TokContext("{", true), - b_tmpl: new TokContext("${", true), - p_stat: new TokContext("(", false), - p_expr: new TokContext("(", true), - q_tmpl: new TokContext("`", true, true, function (p) { return p.readTmplToken(); }), - f_expr: new TokContext("function", true) - } - - var pp$6 = Parser.prototype - - pp$6.initialContext = function() { - return [types.b_stat] - } - - pp$6.braceIsBlock = function(prevType) { - if (prevType === tt.colon) { - var parent = this.curContext() - if (parent === types.b_stat || parent === types.b_expr) - return !parent.isExpr - } - if (prevType === tt._return) - return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) - if (prevType === tt._else || prevType === tt.semi || prevType === tt.eof || prevType === tt.parenR) - return true - if (prevType == tt.braceL) - return this.curContext() === types.b_stat - return !this.exprAllowed - } - - pp$6.updateContext = function(prevType) { - var update, type = this.type - if (type.keyword && prevType == tt.dot) - this.exprAllowed = false - else if (update = type.updateContext) - update.call(this, prevType) - else - this.exprAllowed = type.beforeExpr - } - - // Token-specific context update code - - tt.parenR.updateContext = tt.braceR.updateContext = function() { - if (this.context.length == 1) { - this.exprAllowed = true - return - } - var out = this.context.pop() - if (out === types.b_stat && this.curContext() === types.f_expr) { - this.context.pop() - this.exprAllowed = false - } else if (out === types.b_tmpl) { - this.exprAllowed = true - } else { - this.exprAllowed = !out.isExpr - } - } - - tt.braceL.updateContext = function(prevType) { - this.context.push(this.braceIsBlock(prevType) ? types.b_stat : types.b_expr) - this.exprAllowed = true - } - - tt.dollarBraceL.updateContext = function() { - this.context.push(types.b_tmpl) - this.exprAllowed = true - } - - tt.parenL.updateContext = function(prevType) { - var statementParens = prevType === tt._if || prevType === tt._for || prevType === tt._with || prevType === tt._while - this.context.push(statementParens ? types.p_stat : types.p_expr) - this.exprAllowed = true - } - - tt.incDec.updateContext = function() { - // tokExprAllowed stays unchanged - } - - tt._function.updateContext = function(prevType) { - if (prevType.beforeExpr && prevType !== tt.semi && prevType !== tt._else && - !((prevType === tt.colon || prevType === tt.braceL) && this.curContext() === types.b_stat)) - this.context.push(types.f_expr) - this.exprAllowed = false - } - - tt.backQuote.updateContext = function() { - if (this.curContext() === types.q_tmpl) - this.context.pop() - else - this.context.push(types.q_tmpl) - this.exprAllowed = false - } - - // Object type used to represent tokens. Note that normally, tokens - // simply exist as properties on the parser object. This is only - // used for the onToken callback and the external tokenizer. - - var Token = function Token(p) { - this.type = p.type - this.value = p.value - this.start = p.start - this.end = p.end - if (p.options.locations) - this.loc = new SourceLocation(p, p.startLoc, p.endLoc) - if (p.options.ranges) - this.range = [p.start, p.end] - }; - - // ## Tokenizer - - var pp$7 = Parser.prototype - - // Are we running under Rhino? - var isRhino = typeof Packages == "object" && Object.prototype.toString.call(Packages) == "[object JavaPackage]" - - // Move to the next token - - pp$7.next = function() { - if (this.options.onToken) - this.options.onToken(new Token(this)) - - this.lastTokEnd = this.end - this.lastTokStart = this.start - this.lastTokEndLoc = this.endLoc - this.lastTokStartLoc = this.startLoc - this.nextToken() - } - - pp$7.getToken = function() { - this.next() - return new Token(this) - } - - // If we're in an ES6 environment, make parsers iterable - if (typeof Symbol !== "undefined") - pp$7[Symbol.iterator] = function () { - var self = this - return {next: function () { - var token = self.getToken() - return { - done: token.type === tt.eof, - value: token - } - }} - } - - // Toggle strict mode. Re-reads the next number or string to please - // pedantic tests (`"use strict"; 010;` should fail). - - pp$7.setStrict = function(strict) { - var this$1 = this; - - this.strict = strict - if (this.type !== tt.num && this.type !== tt.string) return - this.pos = this.start - if (this.options.locations) { - while (this.pos < this.lineStart) { - this$1.lineStart = this$1.input.lastIndexOf("\n", this$1.lineStart - 2) + 1 - --this$1.curLine - } - } - this.nextToken() - } - - pp$7.curContext = function() { - return this.context[this.context.length - 1] - } - - // Read a single token, updating the parser object's token-related - // properties. - - pp$7.nextToken = function() { - var curContext = this.curContext() - if (!curContext || !curContext.preserveSpace) this.skipSpace() - - this.start = this.pos - if (this.options.locations) this.startLoc = this.curPosition() - if (this.pos >= this.input.length) return this.finishToken(tt.eof) - - if (curContext.override) return curContext.override(this) - else this.readToken(this.fullCharCodeAtPos()) - } - - pp$7.readToken = function(code) { - // Identifier or keyword. '\uXXXX' sequences are allowed in - // identifiers, so '\' also dispatches to that. - if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */) - return this.readWord() - - return this.getTokenFromCode(code) - } - - pp$7.fullCharCodeAtPos = function() { - var code = this.input.charCodeAt(this.pos) - if (code <= 0xd7ff || code >= 0xe000) return code - var next = this.input.charCodeAt(this.pos + 1) - return (code << 10) + next - 0x35fdc00 - } - - pp$7.skipBlockComment = function() { - var this$1 = this; - - var startLoc = this.options.onComment && this.curPosition() - var start = this.pos, end = this.input.indexOf("*/", this.pos += 2) - if (end === -1) this.raise(this.pos - 2, "Unterminated comment") - this.pos = end + 2 - if (this.options.locations) { - lineBreakG.lastIndex = start - var match - while ((match = lineBreakG.exec(this.input)) && match.index < this.pos) { - ++this$1.curLine - this$1.lineStart = match.index + match[0].length - } - } - if (this.options.onComment) - this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos, - startLoc, this.curPosition()) - } - - pp$7.skipLineComment = function(startSkip) { - var this$1 = this; - - var start = this.pos - var startLoc = this.options.onComment && this.curPosition() - var ch = this.input.charCodeAt(this.pos+=startSkip) - while (this.pos < this.input.length && ch !== 10 && ch !== 13 && ch !== 8232 && ch !== 8233) { - ++this$1.pos - ch = this$1.input.charCodeAt(this$1.pos) - } - if (this.options.onComment) - this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos, - startLoc, this.curPosition()) - } - - // Called at the start of the parse and after every token. Skips - // whitespace and comments, and. - - pp$7.skipSpace = function() { - var this$1 = this; - - loop: while (this.pos < this.input.length) { - var ch = this$1.input.charCodeAt(this$1.pos) - switch (ch) { - case 32: case 160: // ' ' - ++this$1.pos - break - case 13: - if (this$1.input.charCodeAt(this$1.pos + 1) === 10) { - ++this$1.pos - } - case 10: case 8232: case 8233: + loop: while (this.pos < this.input.length) { + var ch = this$1.input.charCodeAt(this$1.pos) + switch (ch) { + case 32: case 160: // ' ' + ++this$1.pos + break + case 13: + if (this$1.input.charCodeAt(this$1.pos + 1) === 10) { ++this$1.pos - if (this$1.options.locations) { - ++this$1.curLine - this$1.lineStart = this$1.pos - } - break - case 47: // '/' - switch (this$1.input.charCodeAt(this$1.pos + 1)) { - case 42: // '*' - this$1.skipBlockComment() - break - case 47: - this$1.skipLineComment(2) - break - default: - break loop - } - break - default: - if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) { - ++this$1.pos - } else { + } + case 10: case 8232: case 8233: + ++this$1.pos + if (this$1.options.locations) { + ++this$1.curLine + this$1.lineStart = this$1.pos + } + break + case 47: // '/' + switch (this$1.input.charCodeAt(this$1.pos + 1)) { + case 42: // '*' + this$1.skipBlockComment() + break + case 47: + this$1.skipLineComment(2) + break + default: break loop - } - } - } - } - - // Called at the end of every token. Sets `end`, `val`, and - // maintains `context` and `exprAllowed`, and skips the space after - // the token, so that the next one's `start` will point at the - // right position. - - pp$7.finishToken = function(type, val) { - this.end = this.pos - if (this.options.locations) this.endLoc = this.curPosition() - var prevType = this.type - this.type = type - this.value = val - - this.updateContext(prevType) - } - - // ### Token reading - - // This is the function that is called to fetch the next token. It - // is somewhat obscure, because it works in character codes rather - // than characters, and because operator parsing has been inlined - // into it. - // - // All in the name of speed. - // - pp$7.readToken_dot = function() { - var next = this.input.charCodeAt(this.pos + 1) - if (next >= 48 && next <= 57) return this.readNumber(true) - var next2 = this.input.charCodeAt(this.pos + 2) - if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.' - this.pos += 3 - return this.finishToken(tt.ellipsis) - } else { - ++this.pos - return this.finishToken(tt.dot) - } - } - - pp$7.readToken_slash = function() { // '/' - var next = this.input.charCodeAt(this.pos + 1) - if (this.exprAllowed) {++this.pos; return this.readRegexp()} - if (next === 61) return this.finishOp(tt.assign, 2) - return this.finishOp(tt.slash, 1) - } - - pp$7.readToken_mult_modulo_exp = function(code) { // '%*' - var next = this.input.charCodeAt(this.pos + 1) - var size = 1 - var tokentype = code === 42 ? tt.star : tt.modulo - - // exponentiation operator ** and **= - if (this.options.ecmaVersion >= 7 && next === 42) { - ++size - tokentype = tt.starstar - next = this.input.charCodeAt(this.pos + 2) - } - - if (next === 61) return this.finishOp(tt.assign, size + 1) - return this.finishOp(tokentype, size) - } - - pp$7.readToken_pipe_amp = function(code) { // '|&' - var next = this.input.charCodeAt(this.pos + 1) - if (next === code) return this.finishOp(code === 124 ? tt.logicalOR : tt.logicalAND, 2) - if (next === 61) return this.finishOp(tt.assign, 2) - return this.finishOp(code === 124 ? tt.bitwiseOR : tt.bitwiseAND, 1) - } - - pp$7.readToken_caret = function() { // '^' - var next = this.input.charCodeAt(this.pos + 1) - if (next === 61) return this.finishOp(tt.assign, 2) - return this.finishOp(tt.bitwiseXOR, 1) - } - - pp$7.readToken_plus_min = function(code) { // '+-' - var next = this.input.charCodeAt(this.pos + 1) - if (next === code) { - if (next == 45 && this.input.charCodeAt(this.pos + 2) == 62 && - lineBreak.test(this.input.slice(this.lastTokEnd, this.pos))) { - // A `-->` line comment - this.skipLineComment(3) - this.skipSpace() - return this.nextToken() - } - return this.finishOp(tt.incDec, 2) + } + break + default: + if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) { + ++this$1.pos + } else { + break loop + } } - if (next === 61) return this.finishOp(tt.assign, 2) - return this.finishOp(tt.plusMin, 1) } - - pp$7.readToken_lt_gt = function(code) { // '<>' - var next = this.input.charCodeAt(this.pos + 1) - var size = 1 - if (next === code) { - size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2 - if (this.input.charCodeAt(this.pos + size) === 61) return this.finishOp(tt.assign, size + 1) - return this.finishOp(tt.bitShift, size) - } - if (next == 33 && code == 60 && this.input.charCodeAt(this.pos + 2) == 45 && - this.input.charCodeAt(this.pos + 3) == 45) { - if (this.inModule) this.unexpected() - // `` line comment + this.skipLineComment(3) this.skipSpace() return this.nextToken() } - if (next === 61) size = 2 - return this.finishOp(tt.relational, size) - } + return this.finishOp(tt.incDec, 2) + } + if (next === 61) return this.finishOp(tt.assign, 2) + return this.finishOp(tt.plusMin, 1) +} + +pp$7.readToken_lt_gt = function(code) { // '<>' + var next = this.input.charCodeAt(this.pos + 1) + var size = 1 + if (next === code) { + size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2 + if (this.input.charCodeAt(this.pos + size) === 61) return this.finishOp(tt.assign, size + 1) + return this.finishOp(tt.bitShift, size) + } + if (next == 33 && code == 60 && this.input.charCodeAt(this.pos + 2) == 45 && + this.input.charCodeAt(this.pos + 3) == 45) { + if (this.inModule) this.unexpected() + // ` @@ -163,6 +149,11 @@ target.bundle = function(argsArray) { All commands run synchronously, unless otherwise stated. +All commands accept standard bash globbing characters (`*`, `?`, etc.), +compatible with the [node glob module](https://github.com/isaacs/node-glob). + +For less-commonly used commands and features, please check out our [wiki +page](https://github.com/shelljs/shelljs/wiki). ### cd([dir]) @@ -220,17 +211,21 @@ Available options: + `-f`: force (default behavior) + `-n`: no-clobber -+ `-r, -R`: recursive ++ `-u`: only copy if source is newer than dest ++ `-r`, `-R`: recursive ++ `-L`: follow symlinks ++ `-P`: don't follow symlinks Examples: ```javascript cp('file1', 'dir1'); +cp('-R', 'path/to/dir/', '~/newCopy/'); cp('-Rf', '/tmp/*', '/usr/local/*', '/home/tmp'); cp('-Rf', ['/tmp/*', '/usr/local/*'], '/home/tmp'); // same as above ``` -Copies files. The wildcard `*` is accepted. +Copies files. ### rm([options,] file [, file ...]) @@ -248,7 +243,7 @@ rm('some_file.txt', 'another_file.txt'); rm(['some_file.txt', 'another_file.txt']); // same as above ``` -Removes files. The wildcard `*` is accepted. +Removes files. ### mv([options ,] source [, source ...], dest') @@ -266,7 +261,7 @@ mv('file1', 'file2', 'dir/'); mv(['file1', 'file2'], 'dir/'); // same as above ``` -Moves files. The wildcard `*` is accepted. +Moves files. ### mkdir([options,] dir [, dir ...]) @@ -320,10 +315,44 @@ var str = cat(['file1', 'file2']); // same as above Returns a string containing the given file, or a concatenated string containing the files if more than one file is given (a new line character is -introduced between each file). Wildcard `*` accepted. +introduced between each file). + + +### head([{'-n': \},] file [, file ...]) +### head([{'-n': \},] file_array) +Available options: + ++ `-n `: Show the first `` lines of the files + +Examples: + +```javascript +var str = head({'-n': 1}, 'file*.txt'); +var str = head('file1', 'file2'); +var str = head(['file1', 'file2']); // same as above +``` + +Read the start of a file. + + +### tail([{'-n': \},] file [, file ...]) +### tail([{'-n': \},] file_array) +Available options: + ++ `-n `: Show the last `` lines of the files + +Examples: + +```javascript +var str = tail({'-n': 1}, 'file*.txt'); +var str = tail('file1', 'file2'); +var str = tail(['file1', 'file2']); // same as above +``` + +Read the end of a file. -### 'string'.to(file) +### ShellString.prototype.to(file) Examples: @@ -331,11 +360,12 @@ Examples: cat('input.txt').to('output.txt'); ``` -Analogous to the redirection operator `>` in Unix, but works with JavaScript strings (such as -those returned by `cat`, `grep`, etc). _Like Unix redirections, `to()` will overwrite any existing file!_ +Analogous to the redirection operator `>` in Unix, but works with +ShellStrings (such as those returned by `cat`, `grep`, etc). _Like Unix +redirections, `to()` will overwrite any existing file!_ -### 'string'.toEnd(file) +### ShellString.prototype.toEnd(file) Examples: @@ -343,8 +373,8 @@ Examples: cat('input.txt').toEnd('output.txt'); ``` -Analogous to the redirect-and-append operator `>>` in Unix, but works with JavaScript strings (such as -those returned by `cat`, `grep`, etc). +Analogous to the redirect-and-append operator `>>` in Unix, but works with +ShellStrings (such as those returned by `cat`, `grep`, etc). ### sed([options,] search_regex, replacement, file [, file ...]) @@ -364,11 +394,48 @@ Reads an input string from `files` and performs a JavaScript `replace()` on the using the given search regex and replacement string or function. Returns the new string after replacement. +### sort([options,] file [, file ...]) +### sort([options,] file_array) +Available options: + ++ `-r`: Reverse the result of comparisons ++ `-n`: Compare according to numerical value + +Examples: + +```javascript +sort('foo.txt', 'bar.txt'); +sort('-r', 'foo.txt'); +``` + +Return the contents of the files, sorted line-by-line. Sorting multiple +files mixes their content, just like unix sort does. + + +### uniq([options,] [input, [output]]) +Available options: + ++ `-i`: Ignore case while comparing ++ `-c`: Prefix lines by the number of occurrences ++ `-d`: Only print duplicate lines, one for each group of identical lines + +Examples: + +```javascript +uniq('foo.txt'); +uniq('-i', 'foo.txt'); +uniq('-cd', 'foo.txt', 'bar.txt'); +``` + +Filter adjacent matching lines from input + + ### grep([options,] regex_filter, file [, file ...]) ### grep([options,] regex_filter, file_array) Available options: + `-v`: Inverse the sense of the regex and print the lines not matching the criteria. ++ `-l`: Print only filenames of matching files Examples: @@ -378,7 +445,7 @@ grep('GLOBAL_VARIABLE', '*.js'); ``` Reads input string from given files and returns a string containing all lines of the -file that match the given `regex_filter`. Wildcard `*` accepted. +file that match the given `regex_filter`. ### which(command) @@ -394,7 +461,10 @@ Searches for `command` in the system's PATH. On Windows, this uses the Returns string containing the absolute path to the command. -### echo(string [, string ...]) +### echo([options,] string [, string ...]) +Available options: + ++ `-e`: interpret backslash escapes (default) Examples: @@ -517,9 +587,13 @@ exec('some_long_running_process', function(code, stdout, stderr) { ``` Executes the given `command` _synchronously_, unless otherwise specified. When in synchronous -mode returns the object `{ code:..., stdout:... , stderr:... }`, containing the program's -`stdout`, `stderr`, and its exit `code`. Otherwise returns the child process object, -and the `callback` gets the arguments `(code, stdout, stderr)`. +mode, this returns a ShellString (compatible with ShellJS v0.6.x, which returns an object +of the form `{ code:..., stdout:... , stderr:... }`). Otherwise, this returns the child process +object, and the `callback` gets the arguments `(code, stdout, stderr)`. + +Not seeing the behavior you want? `exec()` runs everything through `sh` +by default (or `cmd.exe` on Windows), which differs from `bash`. If you +need bash-specific behavior, try out the `{shell: 'path/to/bash'}` option. **Note:** For long-lived processes, it's best to run `exec()` asynchronously as the current synchronous implementation uses a lot of CPU. This should be getting @@ -553,7 +627,8 @@ Notable exceptions: + There is no "quiet" option since default behavior is to run silent. -### touch([options,] file) +### touch([options,] file [, file ...]) +### touch([options,] file_array) Available options: + `-a`: Change only the access time @@ -580,6 +655,7 @@ Available options: + `+/-e`: exit upon error (`config.fatal`) + `+/-v`: verbose: show all commands (`config.verbose`) ++ `+/-f`: disable filename expansion (globbing) Examples: @@ -607,14 +683,45 @@ Follows Python's [tempfile algorithm](http://docs.python.org/library/tempfile.ht ### error() -Tests if error occurred in the last command. Returns `null` if no error occurred, -otherwise returns string explaining the error +Tests if error occurred in the last command. Returns a truthy value if an +error returned and a falsy value otherwise. +**Note**: do not rely on the +return value to be an error message. If you need the last error message, use +the `.stderr` attribute from the last command's return value instead. + + +### ShellString(str) + +Examples: + +```javascript +var foo = ShellString('hello world'); +``` + +Turns a regular string into a string-like object similar to what each +command returns. This has special methods, like `.to()` and `.toEnd()` + + +### Pipes + +Examples: + +```javascript +grep('foo', 'file1.txt', 'file2.txt').sed(/o/g, 'a').to('output.txt'); +echo('files with o\'s in the name:\n' + ls().grep('o')); +cat('test.js').exec('node'); // pipe to exec() call +``` + +Commands can send their output to another command in a pipe-like fashion. +`sed`, `grep`, `cat`, `exec`, `to`, and `toEnd` can appear on the right-hand +side of a pipe. Pipes can be chained. ## Configuration ### config.silent + Example: ```javascript @@ -629,19 +736,22 @@ Suppresses all command output if `true`, except for `echo()` calls. Default is `false`. ### config.fatal + Example: ```javascript require('shelljs/global'); config.fatal = true; // or set('-e'); -cp('this_file_does_not_exist', '/dev/null'); // dies here +cp('this_file_does_not_exist', '/dev/null'); // throws Error here /* more commands... */ ``` -If `true` the script will die on errors. Default is `false`. This is -analogous to Bash's `set -e` +If `true` the script will throw a Javascript error when any shell.js +command encounters an error. Default is `false`. This is analogous to +Bash's `set -e` ### config.verbose + Example: ```javascript @@ -656,3 +766,19 @@ Will print each command as follows: cd dir/ ls subdir/ ``` + +### config.globOptions + +Example: + +```javascript +config.globOptions = {nodir: true}; +``` + +Use this value for calls to `glob.sync()` instead of the default options. + +## Team + +| [![Nate Fischer](https://avatars.githubusercontent.com/u/5801521?s=130)](https://github.com/nfischer) | [![Ari Porad](https://avatars1.githubusercontent.com/u/1817508?v=3&s=130)](http://github.com/ariporad) | +|:---:|:---:| +| [Nate Fischer](https://github.com/nfischer) | [Ari Porad](http://github.com/ariporad) | diff --git a/tools/eslint/node_modules/shelljs/bin/shjs b/tools/eslint/node_modules/shelljs/bin/shjs index aae3bc64ce2b68..75ca58b9d9ac3c 100755 --- a/tools/eslint/node_modules/shelljs/bin/shjs +++ b/tools/eslint/node_modules/shelljs/bin/shjs @@ -32,24 +32,8 @@ for (var i = 0, l = args.length; i < l; i++) { } } -if (scriptName.match(/\.coffee$/)) { - // - // CoffeeScript - // - if (which('coffee')) { - exec('coffee "' + scriptName + '" ' + args.join(' '), function(code) { - process.exit(code); - }); - } else { - console.log('ShellJS: CoffeeScript interpreter not found'); - console.log(); - process.exit(1); - } -} else { - // - // JavaScript - // - exec('node "' + scriptName + '" ' + args.join(' '), function(code) { - process.exit(code); - }); -} +var path = require('path'); +var extensions = require('interpret').extensions; +var rechoir = require('rechoir'); +rechoir.prepare(extensions, scriptName); +require(require.resolve(path.resolve(process.cwd(), scriptName))); diff --git a/tools/eslint/node_modules/shelljs/global.js b/tools/eslint/node_modules/shelljs/global.js index 97f0033cc15303..b232e66d5e9cbc 100644 --- a/tools/eslint/node_modules/shelljs/global.js +++ b/tools/eslint/node_modules/shelljs/global.js @@ -1,3 +1,12 @@ +/* eslint no-extend-native: 0 */ var shell = require('./shell.js'); -for (var cmd in shell) +var common = require('./src/common'); +Object.keys(shell).forEach(function (cmd) { global[cmd] = shell[cmd]; +}); + +var _to = require('./src/to'); +String.prototype.to = common.wrap('to', _to); + +var _toEnd = require('./src/toEnd'); +String.prototype.toEnd = common.wrap('toEnd', _toEnd); diff --git a/tools/eslint/node_modules/shelljs/package.json b/tools/eslint/node_modules/shelljs/package.json index 5dc19b8f524e00..b6cfe9545d9ac0 100644 --- a/tools/eslint/node_modules/shelljs/package.json +++ b/tools/eslint/node_modules/shelljs/package.json @@ -2,53 +2,49 @@ "_args": [ [ { - "raw": "shelljs@^0.6.0", + "raw": "shelljs@^0.7.5", "scope": null, "escapedName": "shelljs", "name": "shelljs", - "rawSpec": "^0.6.0", - "spec": ">=0.6.0 <0.7.0", + "rawSpec": "^0.7.5", + "spec": ">=0.7.5 <0.8.0", "type": "range" }, "/Users/trott/io.js/tools/node_modules/eslint" ] ], - "_from": "shelljs@>=0.6.0 <0.7.0", - "_id": "shelljs@0.6.1", + "_from": "shelljs@>=0.7.5 <0.8.0", + "_id": "shelljs@0.7.5", "_inCache": true, "_location": "/shelljs", - "_nodeVersion": "6.0.0", + "_nodeVersion": "6.7.0", "_npmOperationalInternal": { - "host": "packages-16-east.internal.npmjs.com", - "tmp": "tmp/shelljs-0.6.1.tgz_1470519555022_0.9348916830495" + "host": "packages-18-east.internal.npmjs.com", + "tmp": "tmp/shelljs-0.7.5.tgz_1477547417527_0.3151172921061516" }, "_npmUser": { "name": "nfischer", "email": "ntfschr@gmail.com" }, - "_npmVersion": "3.5.2", + "_npmVersion": "3.10.8", "_phantomChildren": {}, "_requested": { - "raw": "shelljs@^0.6.0", + "raw": "shelljs@^0.7.5", "scope": null, "escapedName": "shelljs", "name": "shelljs", - "rawSpec": "^0.6.0", - "spec": ">=0.6.0 <0.7.0", + "rawSpec": "^0.7.5", + "spec": ">=0.7.5 <0.8.0", "type": "range" }, "_requiredBy": [ "/eslint" ], - "_resolved": "https://registry.npmjs.org/shelljs/-/shelljs-0.6.1.tgz", - "_shasum": "ec6211bed1920442088fe0f70b2837232ed2c8a8", + "_resolved": "https://registry.npmjs.org/shelljs/-/shelljs-0.7.5.tgz", + "_shasum": "2eef7a50a21e1ccf37da00df767ec69e30ad0675", "_shrinkwrap": null, - "_spec": "shelljs@^0.6.0", + "_spec": "shelljs@^0.7.5", "_where": "/Users/trott/io.js/tools/node_modules/eslint", - "author": { - "name": "Artur Adib", - "email": "arturadib@gmail.com" - }, "bin": { "shjs": "./bin/shjs" }, @@ -63,26 +59,39 @@ }, { "name": "Nate Fischer", - "email": "ntfschr@gmail.com" + "email": "ntfschr@gmail.com", + "url": "https://github.com/nfischer" } ], - "dependencies": {}, + "dependencies": { + "glob": "^7.0.0", + "interpret": "^1.0.0", + "rechoir": "^0.6.2" + }, "description": "Portable Unix shell commands for Node.js", "devDependencies": { "coffee-script": "^1.10.0", - "jshint": "~2.1.11" + "eslint": "^2.0.0", + "eslint-config-airbnb-base": "^3.0.0", + "eslint-plugin-import": "^1.11.1", + "shelljs-changelog": "^0.2.0", + "shelljs-release": "^0.2.0", + "travis-check-changes": "^0.2.0" }, "directories": {}, "dist": { - "shasum": "ec6211bed1920442088fe0f70b2837232ed2c8a8", - "tarball": "https://registry.npmjs.org/shelljs/-/shelljs-0.6.1.tgz" + "shasum": "2eef7a50a21e1ccf37da00df767ec69e30ad0675", + "tarball": "https://registry.npmjs.org/shelljs/-/shelljs-0.7.5.tgz" }, "engines": { - "node": ">=0.10.0" + "iojs": "*", + "node": ">=0.11.0" }, - "gitHead": "a5b9e2a64ffdf9f837d6ceb15d7f42221875542b", + "gitHead": "1a15022f2747d322d771dd7ae0c00840e469a52a", "homepage": "http://github.com/shelljs/shelljs", "keywords": [ + "shelljs", + "bash", "unix", "shell", "makefile", @@ -114,7 +123,15 @@ "url": "git://github.com/shelljs/shelljs.git" }, "scripts": { + "after-travis": "travis-check-changes", + "changelog": "shelljs-changelog", + "gendocs": "node scripts/generate-docs", + "lint": "eslint .", + "posttest": "npm run lint", + "release:major": "shelljs-release major", + "release:minor": "shelljs-release minor", + "release:patch": "shelljs-release patch", "test": "node scripts/run-tests" }, - "version": "0.6.1" + "version": "0.7.5" } diff --git a/tools/eslint/node_modules/shelljs/plugin.js b/tools/eslint/node_modules/shelljs/plugin.js new file mode 100644 index 00000000000000..f879ab320e666a --- /dev/null +++ b/tools/eslint/node_modules/shelljs/plugin.js @@ -0,0 +1,16 @@ +// Various utilties exposed to plugins + +require('./shell'); // Create the ShellJS instance (mandatory) + +var common = require('./src/common'); + +var exportedAttributes = [ + 'error', // For signaling errors from within commands + 'parseOptions', // For custom option parsing + 'readFromPipe', // For commands with the .canReceivePipe attribute + 'register', // For registering plugins +]; + +exportedAttributes.forEach(function (attr) { + exports[attr] = common[attr]; +}); diff --git a/tools/eslint/node_modules/shelljs/scripts/generate-docs.js b/tools/eslint/node_modules/shelljs/scripts/generate-docs.js index 3a31a91abd2a13..f777c8ad263612 100755 --- a/tools/eslint/node_modules/shelljs/scripts/generate-docs.js +++ b/tools/eslint/node_modules/shelljs/scripts/generate-docs.js @@ -1,5 +1,5 @@ #!/usr/bin/env node -/* globals cat, cd, echo, grep, sed */ +/* globals cat, cd, echo, grep, sed, ShellString */ require('../global'); echo('Appending docs to README.md'); @@ -7,18 +7,19 @@ echo('Appending docs to README.md'); cd(__dirname + '/..'); // Extract docs from shell.js -var docs = grep('//@', 'shell.js'); +var docs = grep('^//@', 'shell.js'); -docs = docs.replace(/\/\/\@include (.+)/g, function(match, path) { - var file = path.match('.js$') ? path : path+'.js'; - return grep('//@', file); +// Now extract docs from the appropriate src/*.js files +docs = docs.replace(/\/\/@include (.+)/g, function (match, path) { + var file = path.match('.js$') ? path : path + '.js'; + return grep('^//@', file); }); // Remove '//@' -docs = docs.replace(/\/\/\@ ?/g, ''); +docs = docs.replace(/\/\/@ ?/g, ''); // Wipe out the old docs -cat('README.md').replace(/## Command reference(.|\n)*/, '## Command reference').to('README.md'); +ShellString(cat('README.md').replace(/## Command reference(.|\n)*\n## Team/, '## Command reference\n## Team')).to('README.md'); // Append new docs to README sed('-i', /## Command reference/, '## Command reference\n\n' + docs, 'README.md'); diff --git a/tools/eslint/node_modules/shelljs/scripts/run-tests.js b/tools/eslint/node_modules/shelljs/scripts/run-tests.js index e8e7ff2f879a82..99205623f9ed6b 100755 --- a/tools/eslint/node_modules/shelljs/scripts/run-tests.js +++ b/tools/eslint/node_modules/shelljs/scripts/run-tests.js @@ -1,55 +1,29 @@ #!/usr/bin/env node -/* globals cd, echo, exec, exit, ls, pwd, test */ +/* globals cd, echo, exec, exit, ls */ require('../global'); -var common = require('../src/common'); var failed = false; -// -// Lint -// -var JSHINT_BIN = 'node_modules/jshint/bin/jshint'; -cd(__dirname + '/..'); - -if (!test('-f', JSHINT_BIN)) { - echo('JSHint not found. Run `npm install` in the root dir first.'); - exit(1); -} - -var jsfiles = common.expand([pwd() + '/*.js', - pwd() + '/scripts/*.js', - pwd() + '/src/*.js', - pwd() + '/test/*.js' - ]).join(' '); -if (exec('node ' + pwd() + '/' + JSHINT_BIN + ' ' + jsfiles).code !== 0) { - failed = true; - echo('*** JSHINT FAILED! (return code != 0)'); - echo(); -} else { - echo('All JSHint tests passed'); - echo(); -} - // // Unit tests // cd(__dirname + '/../test'); -ls('*.js').forEach(function(file) { +ls('*.js').forEach(function (file) { echo('Running test:', file); - if (exec('node ' + file).code !== 123) { // 123 avoids false positives (e.g. premature exit) + if (exec(JSON.stringify(process.execPath) + ' ' + file).code !== 123) { // 123 avoids false positives (e.g. premature exit) failed = true; echo('*** TEST FAILED! (missing exit code "123")'); echo(); } }); +echo(); + if (failed) { - echo(); echo('*******************************************************'); echo('WARNING: Some tests did not pass!'); echo('*******************************************************'); exit(1); } else { - echo(); echo('All tests passed.'); } diff --git a/tools/eslint/node_modules/shelljs/shell.js b/tools/eslint/node_modules/shelljs/shell.js index 93aff709a3931f..9e49ef5e799cdb 100644 --- a/tools/eslint/node_modules/shelljs/shell.js +++ b/tools/eslint/node_modules/shelljs/shell.js @@ -8,86 +8,95 @@ var common = require('./src/common'); - //@ //@ All commands run synchronously, unless otherwise stated. +//@ All commands accept standard bash globbing characters (`*`, `?`, etc.), +//@ compatible with the [node glob module](https://github.com/isaacs/node-glob). +//@ +//@ For less-commonly used commands and features, please check out our [wiki +//@ page](https://github.com/shelljs/shelljs/wiki). //@ +// Boilerplate +// ----------- +// Copy the code block below here & replace variables with appropiate values +// ``` +// //@include ./src/fileName +// var functionName = require('./src/fileName'); +// exports.nameOfCommand = common.wrap(nameOfCommand, functionName, {globStart: firstIndexToExpand}); +// ``` +// +// The //@include includes the docs for that command +// +// firstIndexToExpand should usually be 1 (so, put {globStart: 1}) +// Increase this value if the command takes arguments that shouldn't be expanded +// with wildcards, such as with the regexes for sed & grep + //@include ./src/cd -var _cd = require('./src/cd'); -exports.cd = common.wrap('cd', _cd); +require('./src/cd'); //@include ./src/pwd -var _pwd = require('./src/pwd'); -exports.pwd = common.wrap('pwd', _pwd); +require('./src/pwd'); //@include ./src/ls -var _ls = require('./src/ls'); -exports.ls = common.wrap('ls', _ls); +require('./src/ls'); //@include ./src/find -var _find = require('./src/find'); -exports.find = common.wrap('find', _find); +require('./src/find'); //@include ./src/cp -var _cp = require('./src/cp'); -exports.cp = common.wrap('cp', _cp); +require('./src/cp'); //@include ./src/rm -var _rm = require('./src/rm'); -exports.rm = common.wrap('rm', _rm); +require('./src/rm'); //@include ./src/mv -var _mv = require('./src/mv'); -exports.mv = common.wrap('mv', _mv); +require('./src/mv'); //@include ./src/mkdir -var _mkdir = require('./src/mkdir'); -exports.mkdir = common.wrap('mkdir', _mkdir); +require('./src/mkdir'); //@include ./src/test -var _test = require('./src/test'); -exports.test = common.wrap('test', _test); +require('./src/test'); //@include ./src/cat -var _cat = require('./src/cat'); -exports.cat = common.wrap('cat', _cat); +require('./src/cat'); + +//@include ./src/head +require('./src/head'); + +//@include ./src/tail +require('./src/tail'); //@include ./src/to -var _to = require('./src/to'); -String.prototype.to = common.wrap('to', _to); +require('./src/to'); //@include ./src/toEnd -var _toEnd = require('./src/toEnd'); -String.prototype.toEnd = common.wrap('toEnd', _toEnd); +require('./src/toEnd'); //@include ./src/sed -var _sed = require('./src/sed'); -exports.sed = common.wrap('sed', _sed); +require('./src/sed'); + +//@include ./src/sort +require('./src/sort'); + +//@include ./src/uniq +require('./src/uniq'); //@include ./src/grep -var _grep = require('./src/grep'); -exports.grep = common.wrap('grep', _grep); +require('./src/grep'); //@include ./src/which -var _which = require('./src/which'); -exports.which = common.wrap('which', _which); +require('./src/which'); //@include ./src/echo -var _echo = require('./src/echo'); -exports.echo = _echo; // don't common.wrap() as it could parse '-options' +require('./src/echo'); //@include ./src/dirs -var _dirs = require('./src/dirs').dirs; -exports.dirs = common.wrap("dirs", _dirs); -var _pushd = require('./src/dirs').pushd; -exports.pushd = common.wrap('pushd', _pushd); -var _popd = require('./src/dirs').popd; -exports.popd = common.wrap("popd", _popd); +require('./src/dirs'); //@include ./src/ln -var _ln = require('./src/ln'); -exports.ln = common.wrap('ln', _ln); +require('./src/ln'); //@ //@ ### exit(code) @@ -100,20 +109,16 @@ exports.exit = process.exit; exports.env = process.env; //@include ./src/exec -var _exec = require('./src/exec'); -exports.exec = common.wrap('exec', _exec, {notUnix:true}); +require('./src/exec'); //@include ./src/chmod -var _chmod = require('./src/chmod'); -exports.chmod = common.wrap('chmod', _chmod); +require('./src/chmod'); //@include ./src/touch -var _touch = require('./src/touch'); -exports.touch = common.wrap('touch', _touch); +require('./src/touch'); //@include ./src/set -var _set = require('./src/set'); -exports.set = common.wrap('set', _set); +require('./src/set'); //@ @@ -121,15 +126,29 @@ exports.set = common.wrap('set', _set); //@ //@include ./src/tempdir -var _tempDir = require('./src/tempdir'); -exports.tempdir = common.wrap('tempdir', _tempDir); - +require('./src/tempdir'); //@include ./src/error -var _error = require('./src/error'); -exports.error = _error; +exports.error = require('./src/error'); + +//@include ./src/common +exports.ShellString = common.ShellString; +//@ +//@ ### Pipes +//@ +//@ Examples: +//@ +//@ ```javascript +//@ grep('foo', 'file1.txt', 'file2.txt').sed(/o/g, 'a').to('output.txt'); +//@ echo('files with o\'s in the name:\n' + ls().grep('o')); +//@ cat('test.js').exec('node'); // pipe to exec() call +//@ ``` +//@ +//@ Commands can send their output to another command in a pipe-like fashion. +//@ `sed`, `grep`, `cat`, `exec`, `to`, and `toEnd` can appear on the right-hand +//@ side of a pipe. Pipes can be chained. //@ //@ ## Configuration @@ -139,6 +158,7 @@ exports.config = common.config; //@ //@ ### config.silent +//@ //@ Example: //@ //@ ```javascript @@ -154,20 +174,23 @@ exports.config = common.config; //@ //@ ### config.fatal +//@ //@ Example: //@ //@ ```javascript //@ require('shelljs/global'); //@ config.fatal = true; // or set('-e'); -//@ cp('this_file_does_not_exist', '/dev/null'); // dies here +//@ cp('this_file_does_not_exist', '/dev/null'); // throws Error here //@ /* more commands... */ //@ ``` //@ -//@ If `true` the script will die on errors. Default is `false`. This is -//@ analogous to Bash's `set -e` +//@ If `true` the script will throw a Javascript error when any shell.js +//@ command encounters an error. Default is `false`. This is analogous to +//@ Bash's `set -e` //@ //@ ### config.verbose +//@ //@ Example: //@ //@ ```javascript @@ -182,3 +205,14 @@ exports.config = common.config; //@ cd dir/ //@ ls subdir/ //@ ``` + +//@ +//@ ### config.globOptions +//@ +//@ Example: +//@ +//@ ```javascript +//@ config.globOptions = {nodir: true}; +//@ ``` +//@ +//@ Use this value for calls to `glob.sync()` instead of the default options. diff --git a/tools/eslint/node_modules/shelljs/src/cat.js b/tools/eslint/node_modules/shelljs/src/cat.js index 5840b4ea77b590..a74a25c8424d16 100644 --- a/tools/eslint/node_modules/shelljs/src/cat.js +++ b/tools/eslint/node_modules/shelljs/src/cat.js @@ -1,6 +1,10 @@ var common = require('./common'); var fs = require('fs'); +common.register('cat', _cat, { + canReceivePipe: true, +}); + //@ //@ ### cat(file [, file ...]) //@ ### cat(file_array) @@ -15,26 +19,22 @@ var fs = require('fs'); //@ //@ Returns a string containing the given file, or a concatenated string //@ containing the files if more than one file is given (a new line character is -//@ introduced between each file). Wildcard `*` accepted. +//@ introduced between each file). function _cat(options, files) { - var cat = ''; - - if (!files) - common.error('no paths given'); + var cat = common.readFromPipe(); - if (typeof files === 'string') - files = [].slice.call(arguments, 1); - // if it's array leave it as it is + if (!files && !cat) common.error('no paths given'); - files = common.expand(files); + files = [].slice.call(arguments, 1); - files.forEach(function(file) { - if (!fs.existsSync(file)) + files.forEach(function (file) { + if (!fs.existsSync(file)) { common.error('no such file or directory: ' + file); + } cat += fs.readFileSync(file, 'utf8'); }); - return common.ShellString(cat); + return cat; } module.exports = _cat; diff --git a/tools/eslint/node_modules/shelljs/src/cd.js b/tools/eslint/node_modules/shelljs/src/cd.js index b7b9931b8f41df..634ed835cb0925 100644 --- a/tools/eslint/node_modules/shelljs/src/cd.js +++ b/tools/eslint/node_modules/shelljs/src/cd.js @@ -1,28 +1,38 @@ var fs = require('fs'); var common = require('./common'); +common.register('cd', _cd, {}); + //@ //@ ### cd([dir]) //@ Changes to directory `dir` for the duration of the script. Changes to home //@ directory if no argument is supplied. function _cd(options, dir) { - if (!dir) - dir = common.getUserHome(); + if (!dir) dir = common.getUserHome(); if (dir === '-') { - if (!common.state.previousDir) + if (!process.env.OLDPWD) { common.error('could not find previous directory'); - else - dir = common.state.previousDir; + } else { + dir = process.env.OLDPWD; + } } - if (!fs.existsSync(dir)) - common.error('no such file or directory: ' + dir); - - if (!fs.statSync(dir).isDirectory()) - common.error('not a directory: ' + dir); - - common.state.previousDir = process.cwd(); - process.chdir(dir); + try { + var curDir = process.cwd(); + process.chdir(dir); + process.env.OLDPWD = curDir; + } catch (e) { + // something went wrong, let's figure out the error + var err; + try { + fs.statSync(dir); // if this succeeds, it must be some sort of file + err = 'not a directory: ' + dir; + } catch (e2) { + err = 'no such file or directory: ' + dir; + } + if (err) common.error(err); + } + return ''; } module.exports = _cd; diff --git a/tools/eslint/node_modules/shelljs/src/chmod.js b/tools/eslint/node_modules/shelljs/src/chmod.js index 6c6de10ce12e49..a1afd90e75684f 100644 --- a/tools/eslint/node_modules/shelljs/src/chmod.js +++ b/tools/eslint/node_modules/shelljs/src/chmod.js @@ -4,30 +4,32 @@ var path = require('path'); var PERMS = (function (base) { return { - OTHER_EXEC : base.EXEC, - OTHER_WRITE : base.WRITE, - OTHER_READ : base.READ, + OTHER_EXEC: base.EXEC, + OTHER_WRITE: base.WRITE, + OTHER_READ: base.READ, - GROUP_EXEC : base.EXEC << 3, - GROUP_WRITE : base.WRITE << 3, - GROUP_READ : base.READ << 3, + GROUP_EXEC: base.EXEC << 3, + GROUP_WRITE: base.WRITE << 3, + GROUP_READ: base.READ << 3, - OWNER_EXEC : base.EXEC << 6, - OWNER_WRITE : base.WRITE << 6, - OWNER_READ : base.READ << 6, + OWNER_EXEC: base.EXEC << 6, + OWNER_WRITE: base.WRITE << 6, + OWNER_READ: base.READ << 6, - // Literal octal numbers are apparently not allowed in "strict" javascript. Using parseInt is - // the preferred way, else a jshint warning is thrown. - STICKY : parseInt('01000', 8), - SETGID : parseInt('02000', 8), - SETUID : parseInt('04000', 8), + // Literal octal numbers are apparently not allowed in "strict" javascript. + STICKY: parseInt('01000', 8), + SETGID: parseInt('02000', 8), + SETUID: parseInt('04000', 8), - TYPE_MASK : parseInt('0770000', 8) + TYPE_MASK: parseInt('0770000', 8) }; -})({ - EXEC : 1, - WRITE : 2, - READ : 4 +}({ + EXEC: 1, + WRITE: 2, + READ: 4 +})); + +common.register('chmod', _chmod, { }); //@ @@ -62,11 +64,8 @@ function _chmod(options, mode, filePattern) { // Special case where the specified file permissions started with - to subtract perms, which // get picked up by the option parser as command flags. // If we are down by one argument and options starts with -, shift everything over. - filePattern = mode; - mode = options; - options = ''; - } - else { + [].unshift.call(arguments, ''); + } else { common.error('You must specify a file.'); } } @@ -77,15 +76,14 @@ function _chmod(options, mode, filePattern) { 'v': 'verbose' }); - if (typeof filePattern === 'string') { - filePattern = [ filePattern ]; - } + filePattern = [].slice.call(arguments, 2); var files; + // TODO: replace this with a call to common.expand() if (options.recursive) { files = []; - common.expand(filePattern).forEach(function addFile(expandedFile) { + filePattern.forEach(function addFile(expandedFile) { var stat = fs.lstatSync(expandedFile); if (!stat.isSymbolicLink()) { @@ -98,9 +96,8 @@ function _chmod(options, mode, filePattern) { } } }); - } - else { - files = common.expand(filePattern); + } else { + files = filePattern; } files.forEach(function innerChmod(file) { @@ -124,7 +121,6 @@ function _chmod(options, mode, filePattern) { if (isNaN(parseInt(mode, 8))) { // parse options mode.split(',').forEach(function (symbolicMode) { - /*jshint regexdash:true */ var pattern = /([ugoa]*)([=\+-])([rwxXst]*)/i; var matches = pattern.exec(symbolicMode); @@ -133,19 +129,20 @@ function _chmod(options, mode, filePattern) { var operator = matches[2]; var change = matches[3]; - var changeOwner = applyTo.indexOf('u') != -1 || applyTo === 'a' || applyTo === ''; - var changeGroup = applyTo.indexOf('g') != -1 || applyTo === 'a' || applyTo === ''; - var changeOther = applyTo.indexOf('o') != -1 || applyTo === 'a' || applyTo === ''; + var changeOwner = applyTo.indexOf('u') !== -1 || applyTo === 'a' || applyTo === ''; + var changeGroup = applyTo.indexOf('g') !== -1 || applyTo === 'a' || applyTo === ''; + var changeOther = applyTo.indexOf('o') !== -1 || applyTo === 'a' || applyTo === ''; - var changeRead = change.indexOf('r') != -1; - var changeWrite = change.indexOf('w') != -1; - var changeExec = change.indexOf('x') != -1; - var changeExecDir = change.indexOf('X') != -1; - var changeSticky = change.indexOf('t') != -1; - var changeSetuid = change.indexOf('s') != -1; + var changeRead = change.indexOf('r') !== -1; + var changeWrite = change.indexOf('w') !== -1; + var changeExec = change.indexOf('x') !== -1; + var changeExecDir = change.indexOf('X') !== -1; + var changeSticky = change.indexOf('t') !== -1; + var changeSetuid = change.indexOf('s') !== -1; - if (changeExecDir && isDir) + if (changeExecDir && isDir) { changeExec = true; + } var mask = 0; if (changeOwner) { @@ -175,35 +172,37 @@ function _chmod(options, mode, filePattern) { case '=': newPerms = type + mask; - // According to POSIX, when using = to explicitly set the permissions, setuid and setgid can never be cleared. + // According to POSIX, when using = to explicitly set the + // permissions, setuid and setgid can never be cleared. if (fs.statSync(file).isDirectory()) { newPerms |= (PERMS.SETUID + PERMS.SETGID) & perms; } break; + default: + common.error('Could not recognize operator: `' + operator + '`'); } if (options.verbose) { console.log(file + ' -> ' + newPerms.toString(8)); } - if (perms != newPerms) { + if (perms !== newPerms) { if (!options.verbose && options.changes) { console.log(file + ' -> ' + newPerms.toString(8)); } fs.chmodSync(file, newPerms); perms = newPerms; // for the next round of changes! } - } - else { + } else { common.error('Invalid symbolic mode change: ' + symbolicMode); } }); - } - else { + } else { // they gave us a full number newPerms = type + parseInt(mode, 8); - // POSIX rules are that setuid and setgid can only be added using numeric form, but not cleared. + // POSIX rules are that setuid and setgid can only be added using numeric + // form, but not cleared. if (fs.statSync(file).isDirectory()) { newPerms |= (PERMS.SETUID + PERMS.SETGID) & perms; } @@ -211,5 +210,6 @@ function _chmod(options, mode, filePattern) { fs.chmodSync(file, newPerms); } }); + return ''; } module.exports = _chmod; diff --git a/tools/eslint/node_modules/shelljs/src/common.js b/tools/eslint/node_modules/shelljs/src/common.js index 33198bd8a0a265..8211feff4e4d29 100644 --- a/tools/eslint/node_modules/shelljs/src/common.js +++ b/tools/eslint/node_modules/shelljs/src/common.js @@ -1,68 +1,132 @@ +// Ignore warning about 'new String()' +/* eslint no-new-wrappers: 0 */ +'use strict'; + var os = require('os'); var fs = require('fs'); -var _ls = require('./ls'); +var glob = require('glob'); +var shell = require('..'); + +var shellMethods = Object.create(shell); // Module globals var config = { silent: false, fatal: false, verbose: false, + noglob: false, + globOptions: {}, + maxdepth: 255 }; exports.config = config; var state = { error: null, + errorCode: 0, currentCmd: 'shell.js', - previousDir: null, tempDir: null }; exports.state = state; +delete process.env.OLDPWD; // initially, there's no previous directory + var platform = os.type().match(/^Win/) ? 'win' : 'unix'; exports.platform = platform; +// This is populated by calls to commonl.wrap() +var pipeMethods = []; + function log() { - if (!config.silent) + if (!config.silent) { console.error.apply(console, arguments); + } } exports.log = log; -// Shows error message. Throws unless _continue or config.fatal are true -function error(msg, _continue) { - if (state.error === null) - state.error = ''; - var log_entry = state.currentCmd + ': ' + msg; - if (state.error === '') - state.error = log_entry; - else - state.error += '\n' + log_entry; +// Shows error message. Throws if config.fatal is true +function error(msg, _code, options) { + // Validate input + if (typeof msg !== 'string') throw new Error('msg must be a string'); + + var DEFAULT_OPTIONS = { + continue: false, + code: 1, + prefix: state.currentCmd + ': ', + silent: false, + }; + + if (typeof _code === 'number' && typeof options === 'object') { + options.code = _code; + } else if (typeof _code === 'object') { // no 'code' + options = _code; + } else if (typeof _code === 'number') { // no 'options' + options = { code: _code }; + } else if (typeof _code !== 'number') { // only 'msg' + options = {}; + } + options = objectAssign({}, DEFAULT_OPTIONS, options); + + if (!state.errorCode) state.errorCode = options.code; - if (msg.length > 0) - log(log_entry); + var logEntry = options.prefix + msg; + state.error = state.error ? state.error + '\n' : ''; + state.error += logEntry; - if (config.fatal) - process.exit(1); + // Throw an error, or log the entry + if (config.fatal) throw new Error(logEntry); + if (msg.length > 0 && !options.silent) log(logEntry); - if (!_continue) - throw ''; + if (!options.continue) { + throw { + msg: 'earlyExit', + retValue: (new ShellString('', state.error, state.errorCode)) + }; + } } exports.error = error; -// In the future, when Proxies are default, we can add methods like `.to()` to primitive strings. -// For now, this is a dummy function to bookmark places we need such strings -function ShellString(str) { - return str; +//@ +//@ ### ShellString(str) +//@ +//@ Examples: +//@ +//@ ```javascript +//@ var foo = ShellString('hello world'); +//@ ``` +//@ +//@ Turns a regular string into a string-like object similar to what each +//@ command returns. This has special methods, like `.to()` and `.toEnd()` +function ShellString(stdout, stderr, code) { + var that; + if (stdout instanceof Array) { + that = stdout; + that.stdout = stdout.join('\n'); + if (stdout.length > 0) that.stdout += '\n'; + } else { + that = new String(stdout); + that.stdout = stdout; + } + that.stderr = stderr; + that.code = code; + // A list of all commands that can appear on the right-hand side of a pipe + // (populated by calls to common.wrap()) + pipeMethods.forEach(function (cmd) { + that[cmd] = shellMethods[cmd].bind(that); + }); + return that; } + exports.ShellString = ShellString; // Return the home directory in a platform-agnostic way, with consideration for // older versions of node function getUserHome() { var result; - if (os.homedir) + if (os.homedir) { result = os.homedir(); // node 3+ - else + } else { result = process.env[(process.platform === 'win32') ? 'USERPROFILE' : 'HOME']; + } return result; } exports.getUserHome = getUserHome; @@ -72,49 +136,50 @@ exports.getUserHome = getUserHome; // Returns {'reference': 'string-value', 'bob': false} when passed two dictionaries of the form: // parseOptions({'-r': 'string-value'}, {'r':'reference', 'b':'bob'}); function parseOptions(opt, map) { - if (!map) - error('parseOptions() internal error: no map given'); + if (!map) error('parseOptions() internal error: no map given'); // All options are false by default var options = {}; - for (var letter in map) { - if (map[letter][0] !== '!') + Object.keys(map).forEach(function (letter) { + if (map[letter][0] !== '!') { options[map[letter]] = false; - } + } + }); - if (!opt) - return options; // defaults + if (!opt) return options; // defaults var optionName; if (typeof opt === 'string') { - if (opt[0] !== '-') + if (opt[0] !== '-') { return options; + } // e.g. chars = ['R', 'f'] var chars = opt.slice(1).split(''); - chars.forEach(function(c) { + chars.forEach(function (c) { if (c in map) { optionName = map[c]; - if (optionName[0] === '!') - options[optionName.slice(1, optionName.length-1)] = false; - else + if (optionName[0] === '!') { + options[optionName.slice(1)] = false; + } else { options[optionName] = true; + } } else { - error('option not recognized: '+c); + error('option not recognized: ' + c); } }); } else if (typeof opt === 'object') { - for (var key in opt) { + Object.keys(opt).forEach(function (key) { // key is a string of the form '-r', '-d', etc. var c = key[1]; if (c in map) { optionName = map[c]; options[optionName] = opt[key]; // assign the given value } else { - error('option not recognized: '+c); + error('option not recognized: ' + c); } - } + }); } else { error('options must be strings or key-value pairs'); } @@ -127,29 +192,18 @@ exports.parseOptions = parseOptions; // expand(['file*.js']) = ['file1.js', 'file2.js', ...] // (if the files 'file1.js', 'file2.js', etc, exist in the current dir) function expand(list) { + if (!Array.isArray(list)) { + throw new TypeError('must be an array'); + } var expanded = []; - list.forEach(function(listEl) { - // Wildcard present on directory names ? - if(listEl.search(/\*[^\/]*\//) > -1 || listEl.search(/\*\*[^\/]*\//) > -1) { - var match = listEl.match(/^([^*]+\/|)(.*)/); - var root = match[1]; - var rest = match[2]; - var restRegex = rest.replace(/\*\*/g, ".*").replace(/\*/g, "[^\\/]*"); - restRegex = new RegExp(restRegex); - - _ls('-R', root).filter(function (e) { - return restRegex.test(e); - }).forEach(function(file) { - expanded.push(file); - }); - } - // Wildcard present on file names ? - else if (listEl.search(/\*/) > -1) { - _ls('', listEl).forEach(function(file) { - expanded.push(file); - }); - } else { + list.forEach(function (listEl) { + // Don't expand non-strings + if (typeof listEl !== 'string') { expanded.push(listEl); + } else { + var ret = glob.sync(listEl, config.globOptions); + // if glob fails, interpret the string literally + expanded = expanded.concat(ret.length > 0 ? ret : [listEl]); } }); return expanded; @@ -161,7 +215,7 @@ exports.expand = expand; function unlinkSync(file) { try { fs.unlinkSync(file); - } catch(e) { + } catch (e) { // Try to override file permission if (e.code === 'EPERM') { fs.chmodSync(file, '0666'); @@ -176,78 +230,133 @@ exports.unlinkSync = unlinkSync; // e.g. 'shelljs_a5f185d0443ca...' function randomFileName() { function randomHash(count) { - if (count === 1) - return parseInt(16*Math.random(), 10).toString(16); - else { - var hash = ''; - for (var i=0; i= common.config.maxdepth) { + // Max depth has been reached, end copy. + return; + } + opts.depth++; + + // Create the directory where all our junk is moving to; read the mode of the + // source directory and mirror it try { + var checkDir = fs.statSync(sourceDir); fs.mkdirSync(destDir, checkDir.mode); } catch (e) { - //if the directory already exists, that's okay + // if the directory already exists, that's okay if (e.code !== 'EEXIST') throw e; } var files = fs.readdirSync(sourceDir); for (var i = 0; i < files.length; i++) { - var srcFile = sourceDir + "/" + files[i]; - var destFile = destDir + "/" + files[i]; + var srcFile = sourceDir + '/' + files[i]; + var destFile = destDir + '/' + files[i]; var srcFileStat = fs.lstatSync(srcFile); + var symlinkFull; + if (opts.followsymlink) { + if (cpcheckcycle(sourceDir, srcFile)) { + // Cycle link found. + console.error('Cycle link found.'); + symlinkFull = fs.readlinkSync(srcFile); + fs.symlinkSync(symlinkFull, destFile, os.platform() === 'win32' ? 'junction' : null); + continue; + } + } if (srcFileStat.isDirectory()) { /* recursion this thing right on back. */ cpdirSyncRecursive(srcFile, destFile, opts); - } else if (srcFileStat.isSymbolicLink()) { - var symlinkFull = fs.readlinkSync(srcFile); - fs.symlinkSync(symlinkFull, destFile, os.platform() === "win32" ? "junction" : null); + } else if (srcFileStat.isSymbolicLink() && !opts.followsymlink) { + symlinkFull = fs.readlinkSync(srcFile); + try { + fs.lstatSync(destFile); + common.unlinkSync(destFile); // re-link it + } catch (e) { + // it doesn't exist, so no work needs to be done + } + fs.symlinkSync(symlinkFull, destFile, os.platform() === 'win32' ? 'junction' : null); + } else if (srcFileStat.isSymbolicLink() && opts.followsymlink) { + srcFileStat = fs.statSync(srcFile); + if (srcFileStat.isDirectory()) { + cpdirSyncRecursive(srcFile, destFile, opts); + } else { + copyFileSync(srcFile, destFile, opts); + } } else { /* At this point, we've hit a file actually worth copying... so copy it on over. */ if (fs.existsSync(destFile) && opts.no_force) { common.log('skipping existing file: ' + files[i]); } else { - copyFileSync(srcFile, destFile); + copyFileSync(srcFile, destFile, opts); } } - } // for files } // cpdirSyncRecursive +function cpcheckcycle(sourceDir, srcFile) { + var srcFileStat = fs.lstatSync(srcFile); + if (srcFileStat.isSymbolicLink()) { + // Do cycle check. For example: + // $ mkdir -p 1/2/3/4 + // $ cd 1/2/3/4 + // $ ln -s ../../3 link + // $ cd ../../../.. + // $ cp -RL 1 copy + var cyclecheck = fs.statSync(srcFile); + if (cyclecheck.isDirectory()) { + var sourcerealpath = fs.realpathSync(sourceDir); + var symlinkrealpath = fs.realpathSync(srcFile); + var re = new RegExp(symlinkrealpath); + if (re.test(sourcerealpath)) { + return true; + } + } + } + return false; +} //@ //@ ### cp([options,] source [, source ...], dest) @@ -94,117 +183,92 @@ function cpdirSyncRecursive(sourceDir, destDir, opts) { //@ //@ + `-f`: force (default behavior) //@ + `-n`: no-clobber -//@ + `-r, -R`: recursive +//@ + `-u`: only copy if source is newer than dest +//@ + `-r`, `-R`: recursive +//@ + `-L`: follow symlinks +//@ + `-P`: don't follow symlinks //@ //@ Examples: //@ //@ ```javascript //@ cp('file1', 'dir1'); +//@ cp('-R', 'path/to/dir/', '~/newCopy/'); //@ cp('-Rf', '/tmp/*', '/usr/local/*', '/home/tmp'); //@ cp('-Rf', ['/tmp/*', '/usr/local/*'], '/home/tmp'); // same as above //@ ``` //@ -//@ Copies files. The wildcard `*` is accepted. +//@ Copies files. function _cp(options, sources, dest) { - options = common.parseOptions(options, { - 'f': '!no_force', - 'n': 'no_force', - 'R': 'recursive', - 'r': 'recursive' - }); + // If we're missing -R, it actually implies -L (unless -P is explicit) + if (options.followsymlink) { + options.noFollowsymlink = false; + } + if (!options.recursive && !options.noFollowsymlink) { + options.followsymlink = true; + } // Get sources, dest if (arguments.length < 3) { common.error('missing and/or '); - } else if (arguments.length > 3) { + } else { sources = [].slice.call(arguments, 1, arguments.length - 1); dest = arguments[arguments.length - 1]; - } else if (typeof sources === 'string') { - sources = [sources]; - } else if ('length' in sources) { - sources = sources; // no-op for array - } else { - common.error('invalid arguments'); } - var exists = fs.existsSync(dest), - stats = exists && fs.statSync(dest); + var destExists = fs.existsSync(dest); + var destStat = destExists && fs.statSync(dest); // Dest is not existing dir, but multiple sources given - if ((!exists || !stats.isDirectory()) && sources.length > 1) + if ((!destExists || !destStat.isDirectory()) && sources.length > 1) { common.error('dest is not a directory (too many sources)'); - - // Dest is an existing file, but no -f given - if (exists && stats.isFile() && options.no_force) - common.error('dest file already exists: ' + dest); - - if (options.recursive) { - // Recursive allows the shortcut syntax "sourcedir/" for "sourcedir/*" - // (see Github issue #15) - sources.forEach(function(src, i) { - if (src[src.length - 1] === '/') { - sources[i] += '*'; - // If src is a directory and dest doesn't exist, 'cp -r src dest' should copy src/* into dest - } else if (fs.statSync(src).isDirectory() && !exists) { - sources[i] += '/*'; - } - }); - - // Create dest - try { - fs.mkdirSync(dest, parseInt('0777', 8)); - } catch (e) { - // like Unix's cp, keep going even if we can't create dest dir - } } - sources = common.expand(sources); + // Dest is an existing file, but -n is given + if (destExists && destStat.isFile() && options.no_force) { + return new common.ShellString('', '', 0); + } - sources.forEach(function(src) { + sources.forEach(function (src) { if (!fs.existsSync(src)) { - common.error('no such file or directory: '+src, true); + common.error('no such file or directory: ' + src, { continue: true }); return; // skip file } - - // If here, src exists - if (fs.statSync(src).isDirectory()) { + var srcStat = fs.statSync(src); + if (!options.noFollowsymlink && srcStat.isDirectory()) { if (!options.recursive) { // Non-Recursive - common.log(src + ' is a directory (not copied)'); + common.error("omitting directory '" + src + "'", { continue: true }); } else { // Recursive // 'cp /a/source dest' should create 'source' in 'dest' - var newDest = path.join(dest, path.basename(src)), - checkDir = fs.statSync(src); + var newDest = (destStat && destStat.isDirectory()) ? + path.join(dest, path.basename(src)) : + dest; + try { - fs.mkdirSync(newDest, checkDir.mode); + fs.statSync(path.dirname(dest)); + cpdirSyncRecursive(src, newDest, { no_force: options.no_force, followsymlink: options.followsymlink }); } catch (e) { - //if the directory already exists, that's okay - if (e.code !== 'EEXIST') { - common.error('dest file no such file or directory: ' + newDest, true); - throw e; - } + common.error("cannot create directory '" + dest + "': No such file or directory"); } - - cpdirSyncRecursive(src, newDest, {no_force: options.no_force}); } - return; // done with dir - } + } else { + // If here, src is a file - // If here, src is a file + // When copying to '/path/dir': + // thisDest = '/path/dir/file1' + var thisDest = dest; + if (destStat && destStat.isDirectory()) { + thisDest = path.normalize(dest + '/' + path.basename(src)); + } - // When copying to '/path/dir': - // thisDest = '/path/dir/file1' - var thisDest = dest; - if (fs.existsSync(dest) && fs.statSync(dest).isDirectory()) - thisDest = path.normalize(dest + '/' + path.basename(src)); + if (fs.existsSync(thisDest) && options.no_force) { + return; // skip file + } - if (fs.existsSync(thisDest) && options.no_force) { - common.error('dest file already exists: ' + thisDest, true); - return; // skip file + copyFileSync(src, thisDest, options); } - - copyFileSync(src, thisDest); }); // forEach(src) + return new common.ShellString('', common.state.error, common.state.errorCode); } module.exports = _cp; diff --git a/tools/eslint/node_modules/shelljs/src/dirs.js b/tools/eslint/node_modules/shelljs/src/dirs.js index 58fae8b3c6fae3..cf5fe02f50c593 100644 --- a/tools/eslint/node_modules/shelljs/src/dirs.js +++ b/tools/eslint/node_modules/shelljs/src/dirs.js @@ -2,6 +2,16 @@ var common = require('./common'); var _cd = require('./cd'); var path = require('path'); +common.register('dirs', _dirs, { + wrapOutput: false, +}); +common.register('pushd', _pushd, { + wrapOutput: false, +}); +common.register('popd', _popd, { + wrapOutput: false, +}); + // Pushd/popd/dirs internals var _dirStack = []; @@ -13,9 +23,8 @@ function _parseStackIndex(index) { if (_isStackIndex(index)) { if (Math.abs(index) < _dirStack.length + 1) { // +1 for pwd return (/^-/).test(index) ? Number(index) - 1 : Number(index); - } else { - common.error(index + ': directory stack index out of range'); } + common.error(index + ': directory stack index out of range'); } else { common.error(index + ': invalid number'); } @@ -54,7 +63,7 @@ function _pushd(options, dir) { } options = common.parseOptions(options, { - 'n' : 'no-cd' + 'n': 'no-cd' }); var dirs = _actualDirStack(); @@ -120,7 +129,7 @@ function _popd(options, index) { } options = common.parseOptions(options, { - 'n' : 'no-cd' + 'n': 'no-cd' }); if (!_dirStack.length) { @@ -163,10 +172,10 @@ function _dirs(options, index) { } options = common.parseOptions(options, { - 'c' : 'clear' + 'c': 'clear' }); - if (options['clear']) { + if (options.clear) { _dirStack = []; return _dirStack; } diff --git a/tools/eslint/node_modules/shelljs/src/echo.js b/tools/eslint/node_modules/shelljs/src/echo.js index b574adc5c38465..2b0e7d9198186f 100644 --- a/tools/eslint/node_modules/shelljs/src/echo.js +++ b/tools/eslint/node_modules/shelljs/src/echo.js @@ -1,7 +1,14 @@ var common = require('./common'); +common.register('echo', _echo, { + allowGlobbing: false, +}); + +//@ +//@ ### echo([options,] string [, string ...]) +//@ Available options: //@ -//@ ### echo(string [, string ...]) +//@ + `-e`: interpret backslash escapes (default) //@ //@ Examples: //@ @@ -12,9 +19,16 @@ var common = require('./common'); //@ //@ Prints string to stdout, and returns string with additional utility methods //@ like `.to()`. -function _echo() { - var messages = [].slice.call(arguments, 0); +function _echo(opts, messages) { + // allow strings starting with '-', see issue #20 + messages = [].slice.call(arguments, opts ? 0 : 1); + + if (messages[0] === '-e') { + // ignore -e + messages.shift(); + } + console.log.apply(console, messages); - return common.ShellString(messages.join(' ')); + return messages.join(' '); } module.exports = _echo; diff --git a/tools/eslint/node_modules/shelljs/src/error.js b/tools/eslint/node_modules/shelljs/src/error.js index 112563db80311e..507c86ddd7131e 100644 --- a/tools/eslint/node_modules/shelljs/src/error.js +++ b/tools/eslint/node_modules/shelljs/src/error.js @@ -2,8 +2,12 @@ var common = require('./common'); //@ //@ ### error() -//@ Tests if error occurred in the last command. Returns `null` if no error occurred, -//@ otherwise returns string explaining the error +//@ Tests if error occurred in the last command. Returns a truthy value if an +//@ error returned and a falsy value otherwise. +//@ +//@ **Note**: do not rely on the +//@ return value to be an error message. If you need the last error message, use +//@ the `.stderr` attribute from the last command's return value instead. function error() { return common.state.error; } diff --git a/tools/eslint/node_modules/shelljs/src/exec.js b/tools/eslint/node_modules/shelljs/src/exec.js index 4174adbd32d317..f6875b1e5fc4ae 100644 --- a/tools/eslint/node_modules/shelljs/src/exec.js +++ b/tools/eslint/node_modules/shelljs/src/exec.js @@ -5,85 +5,95 @@ var path = require('path'); var fs = require('fs'); var child = require('child_process'); -var DEFAULT_MAXBUFFER_SIZE = 20*1024*1024; +var DEFAULT_MAXBUFFER_SIZE = 20 * 1024 * 1024; + +common.register('exec', _exec, { + unix: false, + canReceivePipe: true, + wrapOutput: false, +}); // Hack to run child_process.exec() synchronously (sync avoids callback hell) // Uses a custom wait loop that checks for a flag file, created when the child process is done. // (Can't do a wait loop that checks for internal Node variables/messages as // Node is single-threaded; callbacks and other internal state changes are done in the // event loop). -function execSync(cmd, opts) { +function execSync(cmd, opts, pipe) { var tempDir = _tempDir(); - var stdoutFile = path.resolve(tempDir+'/'+common.randomFileName()), - stderrFile = path.resolve(tempDir+'/'+common.randomFileName()), - codeFile = path.resolve(tempDir+'/'+common.randomFileName()), - scriptFile = path.resolve(tempDir+'/'+common.randomFileName()), - sleepFile = path.resolve(tempDir+'/'+common.randomFileName()); + var stdoutFile = path.resolve(tempDir + '/' + common.randomFileName()); + var stderrFile = path.resolve(tempDir + '/' + common.randomFileName()); + var codeFile = path.resolve(tempDir + '/' + common.randomFileName()); + var scriptFile = path.resolve(tempDir + '/' + common.randomFileName()); + var sleepFile = path.resolve(tempDir + '/' + common.randomFileName()); opts = common.extend({ silent: common.config.silent, - cwd: _pwd(), + cwd: _pwd().toString(), env: process.env, maxBuffer: DEFAULT_MAXBUFFER_SIZE }, opts); - var previousStdoutContent = '', - previousStderrContent = ''; + var previousStdoutContent = ''; + var previousStderrContent = ''; // Echoes stdout and stderr changes from running process, if not silent function updateStream(streamFile) { - if (opts.silent || !fs.existsSync(streamFile)) + if (opts.silent || !fs.existsSync(streamFile)) { return; + } - var previousStreamContent, - proc_stream; + var previousStreamContent; + var procStream; if (streamFile === stdoutFile) { previousStreamContent = previousStdoutContent; - proc_stream = process.stdout; + procStream = process.stdout; } else { // assume stderr previousStreamContent = previousStderrContent; - proc_stream = process.stderr; + procStream = process.stderr; } var streamContent = fs.readFileSync(streamFile, 'utf8'); // No changes since last time? - if (streamContent.length <= previousStreamContent.length) + if (streamContent.length <= previousStreamContent.length) { return; + } - proc_stream.write(streamContent.substr(previousStreamContent.length)); + procStream.write(streamContent.substr(previousStreamContent.length)); previousStreamContent = streamContent; } - function escape(str) { - return (str+'').replace(/([\\"'])/g, "\\$1").replace(/\0/g, "\\0"); - } - if (fs.existsSync(scriptFile)) common.unlinkSync(scriptFile); if (fs.existsSync(stdoutFile)) common.unlinkSync(stdoutFile); if (fs.existsSync(stderrFile)) common.unlinkSync(stderrFile); if (fs.existsSync(codeFile)) common.unlinkSync(codeFile); - var execCommand = '"'+process.execPath+'" '+scriptFile; + var execCommand = JSON.stringify(process.execPath) + ' ' + JSON.stringify(scriptFile); var script; + opts.cwd = path.resolve(opts.cwd); + var optString = JSON.stringify(opts); + if (typeof child.execSync === 'function') { script = [ "var child = require('child_process')", " , fs = require('fs');", - "var childProcess = child.exec('"+escape(cmd)+"', {env: process.env, maxBuffer: "+opts.maxBuffer+"}, function(err) {", - " fs.writeFileSync('"+escape(codeFile)+"', err ? err.code.toString() : '0');", - "});", - "var stdoutStream = fs.createWriteStream('"+escape(stdoutFile)+"');", - "var stderrStream = fs.createWriteStream('"+escape(stderrFile)+"');", - "childProcess.stdout.pipe(stdoutStream, {end: false});", - "childProcess.stderr.pipe(stderrStream, {end: false});", - "childProcess.stdout.pipe(process.stdout);", - "childProcess.stderr.pipe(process.stderr);", - "var stdoutEnded = false, stderrEnded = false;", - "function tryClosingStdout(){ if(stdoutEnded){ stdoutStream.end(); } }", - "function tryClosingStderr(){ if(stderrEnded){ stderrStream.end(); } }", - "childProcess.stdout.on('end', function(){ stdoutEnded = true; tryClosingStdout(); });", - "childProcess.stderr.on('end', function(){ stderrEnded = true; tryClosingStderr(); });" - ].join('\n'); + 'var childProcess = child.exec(' + JSON.stringify(cmd) + ', ' + optString + ', function(err) {', + ' fs.writeFileSync(' + JSON.stringify(codeFile) + ", err ? err.code.toString() : '0');", + '});', + 'var stdoutStream = fs.createWriteStream(' + JSON.stringify(stdoutFile) + ');', + 'var stderrStream = fs.createWriteStream(' + JSON.stringify(stderrFile) + ');', + 'childProcess.stdout.pipe(stdoutStream, {end: false});', + 'childProcess.stderr.pipe(stderrStream, {end: false});', + 'childProcess.stdout.pipe(process.stdout);', + 'childProcess.stderr.pipe(process.stderr);' + ].join('\n') + + (pipe ? '\nchildProcess.stdin.end(' + JSON.stringify(pipe) + ');\n' : '\n') + + [ + 'var stdoutEnded = false, stderrEnded = false;', + 'function tryClosingStdout(){ if(stdoutEnded){ stdoutStream.end(); } }', + 'function tryClosingStderr(){ if(stderrEnded){ stderrStream.end(); } }', + "childProcess.stdout.on('end', function(){ stdoutEnded = true; tryClosingStdout(); });", + "childProcess.stderr.on('end', function(){ stderrEnded = true; tryClosingStderr(); });" + ].join('\n'); fs.writeFileSync(scriptFile, script); @@ -94,17 +104,27 @@ function execSync(cmd, opts) { } // Welcome to the future - child.execSync(execCommand, opts); + try { + child.execSync(execCommand, opts); + } catch (e) { + // Clean up immediately if we have an exception + try { common.unlinkSync(scriptFile); } catch (e2) {} + try { common.unlinkSync(stdoutFile); } catch (e2) {} + try { common.unlinkSync(stderrFile); } catch (e2) {} + try { common.unlinkSync(codeFile); } catch (e2) {} + throw e; + } } else { - cmd += ' > '+stdoutFile+' 2> '+stderrFile; // works on both win/unix + cmd += ' > ' + stdoutFile + ' 2> ' + stderrFile; // works on both win/unix script = [ "var child = require('child_process')", " , fs = require('fs');", - "var childProcess = child.exec('"+escape(cmd)+"', {env: process.env, maxBuffer: "+opts.maxBuffer+"}, function(err) {", - " fs.writeFileSync('"+escape(codeFile)+"', err ? err.code.toString() : '0');", - "});" - ].join('\n'); + 'var childProcess = child.exec(' + JSON.stringify(cmd) + ', ' + optString + ', function(err) {', + ' fs.writeFileSync(' + JSON.stringify(codeFile) + ", err ? err.code.toString() : '0');", + '});' + ].join('\n') + + (pipe ? '\nchildProcess.stdin.end(' + JSON.stringify(pipe) + ');\n' : '\n'); fs.writeFileSync(scriptFile, script); @@ -117,6 +137,7 @@ function execSync(cmd, opts) { while (!fs.existsSync(codeFile)) { updateStream(stdoutFile); fs.writeFileSync(sleepFile, 'a'); } while (!fs.existsSync(stdoutFile)) { updateStream(stdoutFile); fs.writeFileSync(sleepFile, 'a'); } while (!fs.existsSync(stderrFile)) { updateStream(stderrFile); fs.writeFileSync(sleepFile, 'a'); } + try { common.unlinkSync(sleepFile); } catch (e) {} } // At this point codeFile exists, but it's not necessarily flushed yet. @@ -130,53 +151,46 @@ function execSync(cmd, opts) { var stderr = fs.readFileSync(stderrFile, 'utf8'); // No biggie if we can't erase the files now -- they're in a temp dir anyway - try { common.unlinkSync(scriptFile); } catch(e) {} - try { common.unlinkSync(stdoutFile); } catch(e) {} - try { common.unlinkSync(stderrFile); } catch(e) {} - try { common.unlinkSync(codeFile); } catch(e) {} - try { common.unlinkSync(sleepFile); } catch(e) {} - - // some shell return codes are defined as errors, per http://tldp.org/LDP/abs/html/exitcodes.html - if (code === 1 || code === 2 || code >= 126) { - common.error('', true); // unix/shell doesn't really give an error message after non-zero exit codes + try { common.unlinkSync(scriptFile); } catch (e) {} + try { common.unlinkSync(stdoutFile); } catch (e) {} + try { common.unlinkSync(stderrFile); } catch (e) {} + try { common.unlinkSync(codeFile); } catch (e) {} + + if (code !== 0) { + common.error('', code, { continue: true }); } - // True if successful, false if not - var obj = { - code: code, - output: stdout, // deprecated - stdout: stdout, - stderr: stderr - }; + var obj = common.ShellString(stdout, stderr, code); return obj; } // execSync() // Wrapper around exec() to enable echoing output to console in real time -function execAsync(cmd, opts, callback) { +function execAsync(cmd, opts, pipe, callback) { var stdout = ''; var stderr = ''; opts = common.extend({ silent: common.config.silent, - cwd: _pwd(), + cwd: _pwd().toString(), env: process.env, maxBuffer: DEFAULT_MAXBUFFER_SIZE }, opts); - var c = child.exec(cmd, opts, function(err) { - if (callback) + var c = child.exec(cmd, opts, function (err) { + if (callback) { callback(err ? err.code : 0, stdout, stderr); + } }); - c.stdout.on('data', function(data) { + if (pipe) c.stdin.end(pipe); + + c.stdout.on('data', function (data) { stdout += data; - if (!opts.silent) - process.stdout.write(data); + if (!opts.silent) process.stdout.write(data); }); - c.stderr.on('data', function(data) { + c.stderr.on('data', function (data) { stderr += data; - if (!opts.silent) - process.stderr.write(data); + if (!opts.silent) process.stderr.write(data); }); return c; @@ -210,16 +224,22 @@ function execAsync(cmd, opts, callback) { //@ ``` //@ //@ Executes the given `command` _synchronously_, unless otherwise specified. When in synchronous -//@ mode returns the object `{ code:..., stdout:... , stderr:... }`, containing the program's -//@ `stdout`, `stderr`, and its exit `code`. Otherwise returns the child process object, -//@ and the `callback` gets the arguments `(code, stdout, stderr)`. +//@ mode, this returns a ShellString (compatible with ShellJS v0.6.x, which returns an object +//@ of the form `{ code:..., stdout:... , stderr:... }`). Otherwise, this returns the child process +//@ object, and the `callback` gets the arguments `(code, stdout, stderr)`. +//@ +//@ Not seeing the behavior you want? `exec()` runs everything through `sh` +//@ by default (or `cmd.exe` on Windows), which differs from `bash`. If you +//@ need bash-specific behavior, try out the `{shell: 'path/to/bash'}` option. //@ //@ **Note:** For long-lived processes, it's best to run `exec()` asynchronously as //@ the current synchronous implementation uses a lot of CPU. This should be getting //@ fixed soon. function _exec(command, options, callback) { - if (!command) - common.error('must specify command'); + options = options || {}; + if (!command) common.error('must specify command'); + + var pipe = common.readFromPipe(); // Callback is defined instead of options. if (typeof options === 'function') { @@ -238,10 +258,11 @@ function _exec(command, options, callback) { }, options); try { - if (options.async) - return execAsync(command, options, callback); - else - return execSync(command, options); + if (options.async) { + return execAsync(command, options, pipe, callback); + } else { + return execSync(command, options, pipe); + } } catch (e) { common.error('internal error'); } diff --git a/tools/eslint/node_modules/shelljs/src/find.js b/tools/eslint/node_modules/shelljs/src/find.js index c96fb2f7ad51e7..f96a51e7830a62 100644 --- a/tools/eslint/node_modules/shelljs/src/find.js +++ b/tools/eslint/node_modules/shelljs/src/find.js @@ -1,7 +1,10 @@ var fs = require('fs'); +var path = require('path'); var common = require('./common'); var _ls = require('./ls'); +common.register('find', _find, {}); + //@ //@ ### find(path [, path ...]) //@ ### find(path_array) @@ -18,30 +21,30 @@ var _ls = require('./ls'); //@ The main difference from `ls('-R', path)` is that the resulting file names //@ include the base directories, e.g. `lib/resources/file1` instead of just `file1`. function _find(options, paths) { - if (!paths) + if (!paths) { common.error('no path specified'); - else if (typeof paths === 'object') - paths = paths; // assume array - else if (typeof paths === 'string') + } else if (typeof paths === 'string') { paths = [].slice.call(arguments, 1); + } var list = []; function pushFile(file) { - if (common.platform === 'win') + if (common.platform === 'win') { file = file.replace(/\\/g, '/'); + } list.push(file); } // why not simply do ls('-R', paths)? because the output wouldn't give the base dirs // to get the base dir in the output, we need instead ls('-R', 'dir/*') for every directory - paths.forEach(function(file) { + paths.forEach(function (file) { pushFile(file); if (fs.statSync(file).isDirectory()) { - _ls('-RA', file+'/*').forEach(function(subfile) { - pushFile(subfile); + _ls({ recursive: true, all: true }, file).forEach(function (subfile) { + pushFile(path.join(file, subfile)); }); } }); diff --git a/tools/eslint/node_modules/shelljs/src/grep.js b/tools/eslint/node_modules/shelljs/src/grep.js index 78008ce19e6d2f..30842bcb859441 100644 --- a/tools/eslint/node_modules/shelljs/src/grep.js +++ b/tools/eslint/node_modules/shelljs/src/grep.js @@ -1,12 +1,22 @@ var common = require('./common'); var fs = require('fs'); +common.register('grep', _grep, { + globStart: 2, // don't glob-expand the regex + canReceivePipe: true, + cmdOptions: { + 'v': 'inverse', + 'l': 'nameOnly', + }, +}); + //@ //@ ### grep([options,] regex_filter, file [, file ...]) //@ ### grep([options,] regex_filter, file_array) //@ Available options: //@ //@ + `-v`: Inverse the sense of the regex and print the lines not matching the criteria. +//@ + `-l`: Print only filenames of matching files //@ //@ Examples: //@ @@ -16,37 +26,42 @@ var fs = require('fs'); //@ ``` //@ //@ Reads input string from given files and returns a string containing all lines of the -//@ file that match the given `regex_filter`. Wildcard `*` accepted. +//@ file that match the given `regex_filter`. function _grep(options, regex, files) { - options = common.parseOptions(options, { - 'v': 'inverse' - }); + // Check if this is coming from a pipe + var pipe = common.readFromPipe(); - if (!files) - common.error('no paths given'); + if (!files && !pipe) common.error('no paths given', 2); - if (typeof files === 'string') - files = [].slice.call(arguments, 2); - // if it's array leave it as it is + files = [].slice.call(arguments, 2); - files = common.expand(files); + if (pipe) { + files.unshift('-'); + } - var grep = ''; - files.forEach(function(file) { - if (!fs.existsSync(file)) { - common.error('no such file or directory: ' + file, true); + var grep = []; + files.forEach(function (file) { + if (!fs.existsSync(file) && file !== '-') { + common.error('no such file or directory: ' + file, 2, { continue: true }); return; } - var contents = fs.readFileSync(file, 'utf8'), - lines = contents.split(/\r*\n/); - lines.forEach(function(line) { - var matched = line.match(regex); - if ((options.inverse && !matched) || (!options.inverse && matched)) - grep += line + '\n'; - }); + var contents = file === '-' ? pipe : fs.readFileSync(file, 'utf8'); + var lines = contents.split(/\r*\n/); + if (options.nameOnly) { + if (contents.match(regex)) { + grep.push(file); + } + } else { + lines.forEach(function (line) { + var matched = line.match(regex); + if ((options.inverse && !matched) || (!options.inverse && matched)) { + grep.push(line); + } + }); + } }); - return common.ShellString(grep); + return grep.join('\n') + '\n'; } module.exports = _grep; diff --git a/tools/eslint/node_modules/shelljs/src/head.js b/tools/eslint/node_modules/shelljs/src/head.js new file mode 100644 index 00000000000000..13d5829775e8b2 --- /dev/null +++ b/tools/eslint/node_modules/shelljs/src/head.js @@ -0,0 +1,104 @@ +var common = require('./common'); +var fs = require('fs'); + +common.register('head', _head, { + canReceivePipe: true, + cmdOptions: { + 'n': 'numLines', + }, +}); + +// This reads n or more lines, or the entire file, whichever is less. +function readSomeLines(file, numLines) { + var BUF_LENGTH = 64 * 1024; + var buf = new Buffer(BUF_LENGTH); + var bytesRead = BUF_LENGTH; + var pos = 0; + var fdr = null; + + try { + fdr = fs.openSync(file, 'r'); + } catch (e) { + common.error('cannot read file: ' + file); + } + + var numLinesRead = 0; + var ret = ''; + while (bytesRead === BUF_LENGTH && numLinesRead < numLines) { + bytesRead = fs.readSync(fdr, buf, 0, BUF_LENGTH, pos); + var bufStr = buf.toString('utf8', 0, bytesRead); + numLinesRead += bufStr.split('\n').length - 1; + ret += bufStr; + pos += bytesRead; + } + + fs.closeSync(fdr); + return ret; +} +//@ +//@ ### head([{'-n': \},] file [, file ...]) +//@ ### head([{'-n': \},] file_array) +//@ Available options: +//@ +//@ + `-n `: Show the first `` lines of the files +//@ +//@ Examples: +//@ +//@ ```javascript +//@ var str = head({'-n': 1}, 'file*.txt'); +//@ var str = head('file1', 'file2'); +//@ var str = head(['file1', 'file2']); // same as above +//@ ``` +//@ +//@ Read the start of a file. +function _head(options, files) { + var head = []; + var pipe = common.readFromPipe(); + + if (!files && !pipe) common.error('no paths given'); + + var idx = 1; + if (options.numLines === true) { + idx = 2; + options.numLines = Number(arguments[1]); + } else if (options.numLines === false) { + options.numLines = 10; + } + files = [].slice.call(arguments, idx); + + if (pipe) { + files.unshift('-'); + } + + var shouldAppendNewline = false; + files.forEach(function (file) { + if (!fs.existsSync(file) && file !== '-') { + common.error('no such file or directory: ' + file, { continue: true }); + return; + } + + var contents; + if (file === '-') { + contents = pipe; + } else if (options.numLines < 0) { + contents = fs.readFileSync(file, 'utf8'); + } else { + contents = readSomeLines(file, options.numLines); + } + + var lines = contents.split('\n'); + var hasTrailingNewline = (lines[lines.length - 1] === ''); + if (hasTrailingNewline) { + lines.pop(); + } + shouldAppendNewline = (hasTrailingNewline || options.numLines < lines.length); + + head = head.concat(lines.slice(0, options.numLines)); + }); + + if (shouldAppendNewline) { + head.push(''); // to add a trailing newline once we join + } + return head.join('\n'); +} +module.exports = _head; diff --git a/tools/eslint/node_modules/shelljs/src/ln.js b/tools/eslint/node_modules/shelljs/src/ln.js index 878fda13e23d45..7393d9fcdca7d8 100644 --- a/tools/eslint/node_modules/shelljs/src/ln.js +++ b/tools/eslint/node_modules/shelljs/src/ln.js @@ -2,6 +2,13 @@ var fs = require('fs'); var path = require('path'); var common = require('./common'); +common.register('ln', _ln, { + cmdOptions: { + 's': 'symlink', + 'f': 'force', + }, +}); + //@ //@ ### ln([options,] source, dest) //@ Available options: @@ -18,11 +25,6 @@ var common = require('./common'); //@ //@ Links source to dest. Use -f to force the link, should dest already exist. function _ln(options, source, dest) { - options = common.parseOptions(options, { - 's': 'symlink', - 'f': 'force' - }); - if (!source || !dest) { common.error('Missing and/or '); } @@ -34,7 +36,7 @@ function _ln(options, source, dest) { if (fs.existsSync(dest)) { if (!options.force) { - common.error('Destination file exists', true); + common.error('Destination file exists', { continue: true }); } fs.unlinkSync(dest); @@ -45,19 +47,19 @@ function _ln(options, source, dest) { var linkType = isWindows ? 'file' : null; var resolvedSourcePath = isAbsolute ? sourcePath : path.resolve(process.cwd(), path.dirname(dest), source); if (!fs.existsSync(resolvedSourcePath)) { - common.error('Source file does not exist', true); + common.error('Source file does not exist', { continue: true }); } else if (isWindows && fs.statSync(resolvedSourcePath).isDirectory()) { - linkType = 'junction'; + linkType = 'junction'; } try { - fs.symlinkSync(linkType === 'junction' ? resolvedSourcePath: source, dest, linkType); + fs.symlinkSync(linkType === 'junction' ? resolvedSourcePath : source, dest, linkType); } catch (err) { common.error(err.message); } } else { if (!fs.existsSync(source)) { - common.error('Source file does not exist', true); + common.error('Source file does not exist', { continue: true }); } try { fs.linkSync(source, dest); @@ -65,5 +67,6 @@ function _ln(options, source, dest) { common.error(err.message); } } + return ''; } module.exports = _ln; diff --git a/tools/eslint/node_modules/shelljs/src/ls.js b/tools/eslint/node_modules/shelljs/src/ls.js index 6a54b3a8d8426a..7f25056cd34d7a 100644 --- a/tools/eslint/node_modules/shelljs/src/ls.js +++ b/tools/eslint/node_modules/shelljs/src/ls.js @@ -1,8 +1,19 @@ var path = require('path'); var fs = require('fs'); var common = require('./common'); -var _cd = require('./cd'); -var _pwd = require('./pwd'); +var glob = require('glob'); + +var globPatternRecursive = path.sep + '**' + path.sep + '*'; + +common.register('ls', _ls, { + cmdOptions: { + 'R': 'recursive', + 'A': 'all', + 'a': 'all_deprecated', + 'd': 'directory', + 'l': 'long', + }, +}); //@ //@ ### ls([options,] [path, ...]) @@ -28,14 +39,6 @@ var _pwd = require('./pwd'); //@ //@ Returns array of files in the given path, or in current directory if no path provided. function _ls(options, paths) { - options = common.parseOptions(options, { - 'R': 'recursive', - 'A': 'all', - 'a': 'all_deprecated', - 'd': 'directory', - 'l': 'long' - }); - if (options.all_deprecated) { // We won't support the -a option as it's hard to image why it's useful // (it includes '.' and '..' in addition to '.*' files) @@ -44,125 +47,75 @@ function _ls(options, paths) { options.all = true; } - if (!paths) + if (!paths) { paths = ['.']; - else if (typeof paths === 'object') - paths = paths; // assume array - else if (typeof paths === 'string') + } else { paths = [].slice.call(arguments, 1); + } var list = []; - // Conditionally pushes file to list - returns true if pushed, false otherwise - // (e.g. prevents hidden files to be included unless explicitly told so) - function pushFile(file, query) { - var name = file.name || file; - // hidden file? - if (path.basename(name)[0] === '.') { - // not explicitly asking for hidden files? - if (!options.all && !(path.basename(query)[0] === '.' && path.basename(query).length > 1)) - return false; + function pushFile(abs, relName, stat) { + if (process.platform === 'win32') { + relName = relName.replace(/\\/g, '/'); } - - if (common.platform === 'win') - name = name.replace(/\\/g, '/'); - - if (file.name) { - file.name = name; + if (options.long) { + stat = stat || fs.lstatSync(abs); + list.push(addLsAttributes(relName, stat)); } else { - file = name; + // list.push(path.relative(rel || '.', file)); + list.push(relName); } - list.push(file); - return true; } - paths.forEach(function(p) { - if (fs.existsSync(p)) { - var stats = ls_stat(p); - // Simple file? - if (stats.isFile()) { - if (options.long) { - pushFile(stats, p); - } else { - pushFile(p, p); - } - return; // continue - } + paths.forEach(function (p) { + var stat; - // Simple dir? - if (options.directory) { - pushFile(p, p); - return; - } else if (stats.isDirectory()) { - // Iterate over p contents - fs.readdirSync(p).forEach(function(file) { - var orig_file = file; - if (options.long) - file = ls_stat(path.join(p, file)); - if (!pushFile(file, p)) - return; + try { + stat = fs.lstatSync(p); + } catch (e) { + common.error('no such file or directory: ' + p, 2, { continue: true }); + return; + } - // Recursive? - if (options.recursive) { - var oldDir = _pwd(); - _cd('', p); - if (fs.statSync(orig_file).isDirectory()) - list = list.concat(_ls('-R'+(options.all?'A':''), orig_file+'/*')); - _cd('', oldDir); + // If the stat succeeded + if (stat.isDirectory() && !options.directory) { + if (options.recursive) { + // use glob, because it's simple + glob.sync(p + globPatternRecursive, { dot: options.all }) + .forEach(function (item) { + pushFile(item, path.relative(p, item)); + }); + } else if (options.all) { + // use fs.readdirSync, because it's fast + fs.readdirSync(p).forEach(function (item) { + pushFile(path.join(p, item), item); + }); + } else { + // use fs.readdirSync and then filter out secret files + fs.readdirSync(p).forEach(function (item) { + if (item[0] !== '.') { + pushFile(path.join(p, item), item); } }); - return; // continue } + } else { + pushFile(p, p, stat); } - - // p does not exist - possible wildcard present - - var basename = path.basename(p); - var dirname = path.dirname(p); - // Wildcard present on an existing dir? (e.g. '/tmp/*.js') - if (basename.search(/\*/) > -1 && fs.existsSync(dirname) && fs.statSync(dirname).isDirectory) { - // Escape special regular expression chars - var regexp = basename.replace(/(\^|\$|\(|\)|<|>|\[|\]|\{|\}|\.|\+|\?)/g, '\\$1'); - // Translates wildcard into regex - regexp = '^' + regexp.replace(/\*/g, '.*') + '$'; - // Iterate over directory contents - fs.readdirSync(dirname).forEach(function(file) { - if (file.match(new RegExp(regexp))) { - var file_path = path.join(dirname, file); - file_path = options.long ? ls_stat(file_path) : file_path; - if (file_path.name) - file_path.name = path.normalize(file_path.name); - else - file_path = path.normalize(file_path); - if (!pushFile(file_path, basename)) - return; - - // Recursive? - if (options.recursive) { - var pp = dirname + '/' + file; - if (fs.lstatSync(pp).isDirectory()) - list = list.concat(_ls('-R'+(options.all?'A':''), pp+'/*')); - } // recursive - } // if file matches - }); // forEach - return; - } - - common.error('no such file or directory: ' + p, true); }); + // Add methods, to make this more compatible with ShellStrings return list; } -module.exports = _ls; - -function ls_stat(path) { - var stats = fs.statSync(path); +function addLsAttributes(pathName, stats) { // Note: this object will contain more information than .toString() returns - stats.name = path; - stats.toString = function() { + stats.name = pathName; + stats.toString = function () { // Return a string resembling unix's `ls -l` format return [this.mode, this.nlink, this.uid, this.gid, this.size, this.mtime, this.name].join(' '); }; return stats; } + +module.exports = _ls; diff --git a/tools/eslint/node_modules/shelljs/src/mkdir.js b/tools/eslint/node_modules/shelljs/src/mkdir.js index 8b4fd99075053a..f211bc89b3fbaf 100644 --- a/tools/eslint/node_modules/shelljs/src/mkdir.js +++ b/tools/eslint/node_modules/shelljs/src/mkdir.js @@ -2,10 +2,23 @@ var common = require('./common'); var fs = require('fs'); var path = require('path'); +common.register('mkdir', _mkdir, { + cmdOptions: { + 'p': 'fullpath', + }, +}); + // Recursively creates 'dir' function mkdirSyncRecursive(dir) { var baseDir = path.dirname(dir); + // Prevents some potential problems arising from malformed UNCs or + // insufficient permissions. + /* istanbul ignore next */ + if (baseDir === dir) { + common.error('dirname() failed: [' + dir + ']'); + } + // Base dir exists, no recursion necessary if (fs.existsSync(baseDir)) { fs.mkdirSync(dir, parseInt('0777', 8)); @@ -35,34 +48,45 @@ function mkdirSyncRecursive(dir) { //@ //@ Creates directories. function _mkdir(options, dirs) { - options = common.parseOptions(options, { - 'p': 'fullpath' - }); - if (!dirs) - common.error('no paths given'); + if (!dirs) common.error('no paths given'); - if (typeof dirs === 'string') + if (typeof dirs === 'string') { dirs = [].slice.call(arguments, 1); + } // if it's array leave it as it is - dirs.forEach(function(dir) { - if (fs.existsSync(dir)) { - if (!options.fullpath) - common.error('path already exists: ' + dir, true); + dirs.forEach(function (dir) { + try { + fs.lstatSync(dir); + if (!options.fullpath) { + common.error('path already exists: ' + dir, { continue: true }); + } return; // skip dir + } catch (e) { + // do nothing } // Base dir does not exist, and no -p option given var baseDir = path.dirname(dir); if (!fs.existsSync(baseDir) && !options.fullpath) { - common.error('no such file or directory: ' + baseDir, true); + common.error('no such file or directory: ' + baseDir, { continue: true }); return; // skip dir } - if (options.fullpath) - mkdirSyncRecursive(dir); - else - fs.mkdirSync(dir, parseInt('0777', 8)); + try { + if (options.fullpath) { + mkdirSyncRecursive(dir); + } else { + fs.mkdirSync(dir, parseInt('0777', 8)); + } + } catch (e) { + if (e.code === 'EACCES') { + common.error('cannot create directory ' + dir + ': Permission denied'); + } else { + throw e; + } + } }); + return ''; } // mkdir module.exports = _mkdir; diff --git a/tools/eslint/node_modules/shelljs/src/mv.js b/tools/eslint/node_modules/shelljs/src/mv.js index 69cc03fe1ebe2b..c09bbbc76903c6 100644 --- a/tools/eslint/node_modules/shelljs/src/mv.js +++ b/tools/eslint/node_modules/shelljs/src/mv.js @@ -1,6 +1,15 @@ var fs = require('fs'); var path = require('path'); var common = require('./common'); +var cp = require('./cp'); +var rm = require('./rm'); + +common.register('mv', _mv, { + cmdOptions: { + 'f': '!no_force', + 'n': 'no_force', + }, +}); //@ //@ ### mv([options ,] source [, source ...], dest') @@ -18,13 +27,8 @@ var common = require('./common'); //@ mv(['file1', 'file2'], 'dir/'); // same as above //@ ``` //@ -//@ Moves files. The wildcard `*` is accepted. +//@ Moves files. function _mv(options, sources, dest) { - options = common.parseOptions(options, { - 'f': '!no_force', - 'n': 'no_force' - }); - // Get sources, dest if (arguments.length < 3) { common.error('missing and/or '); @@ -33,28 +37,26 @@ function _mv(options, sources, dest) { dest = arguments[arguments.length - 1]; } else if (typeof sources === 'string') { sources = [sources]; - } else if ('length' in sources) { - sources = sources; // no-op for array } else { common.error('invalid arguments'); } - sources = common.expand(sources); - - var exists = fs.existsSync(dest), - stats = exists && fs.statSync(dest); + var exists = fs.existsSync(dest); + var stats = exists && fs.statSync(dest); // Dest is not existing dir, but multiple sources given - if ((!exists || !stats.isDirectory()) && sources.length > 1) + if ((!exists || !stats.isDirectory()) && sources.length > 1) { common.error('dest is not a directory (too many sources)'); + } // Dest is an existing file, but no -f given - if (exists && stats.isFile() && options.no_force) + if (exists && stats.isFile() && options.no_force) { common.error('dest file already exists: ' + dest); + } - sources.forEach(function(src) { + sources.forEach(function (src) { if (!fs.existsSync(src)) { - common.error('no such file or directory: '+src, true); + common.error('no such file or directory: ' + src, { continue: true }); return; // skip file } @@ -63,20 +65,31 @@ function _mv(options, sources, dest) { // When copying to '/path/dir': // thisDest = '/path/dir/file1' var thisDest = dest; - if (fs.existsSync(dest) && fs.statSync(dest).isDirectory()) + if (fs.existsSync(dest) && fs.statSync(dest).isDirectory()) { thisDest = path.normalize(dest + '/' + path.basename(src)); + } if (fs.existsSync(thisDest) && options.no_force) { - common.error('dest file already exists: ' + thisDest, true); + common.error('dest file already exists: ' + thisDest, { continue: true }); return; // skip file } if (path.resolve(src) === path.dirname(path.resolve(thisDest))) { - common.error('cannot move to self: '+src, true); + common.error('cannot move to self: ' + src, { continue: true }); return; // skip file } - fs.renameSync(src, thisDest); + try { + fs.renameSync(src, thisDest); + } catch (e) { + if (e.code === 'EXDEV') { // external partition + // if either of these fails, the appropriate error message will bubble + // up to the top level automatically + cp('-r', src, thisDest); + rm('-rf', src); + } + } }); // forEach(src) + return ''; } // mv module.exports = _mv; diff --git a/tools/eslint/node_modules/shelljs/src/popd.js b/tools/eslint/node_modules/shelljs/src/popd.js index 11ea24fa464a04..d9eac3f56d1303 100644 --- a/tools/eslint/node_modules/shelljs/src/popd.js +++ b/tools/eslint/node_modules/shelljs/src/popd.js @@ -1 +1 @@ -// see dirs.js \ No newline at end of file +// see dirs.js diff --git a/tools/eslint/node_modules/shelljs/src/pushd.js b/tools/eslint/node_modules/shelljs/src/pushd.js index 11ea24fa464a04..d9eac3f56d1303 100644 --- a/tools/eslint/node_modules/shelljs/src/pushd.js +++ b/tools/eslint/node_modules/shelljs/src/pushd.js @@ -1 +1 @@ -// see dirs.js \ No newline at end of file +// see dirs.js diff --git a/tools/eslint/node_modules/shelljs/src/pwd.js b/tools/eslint/node_modules/shelljs/src/pwd.js index 26cefe0a0454d0..38618518b549f6 100644 --- a/tools/eslint/node_modules/shelljs/src/pwd.js +++ b/tools/eslint/node_modules/shelljs/src/pwd.js @@ -1,11 +1,15 @@ var path = require('path'); var common = require('./common'); +common.register('pwd', _pwd, { + allowGlobbing: false, +}); + //@ //@ ### pwd() //@ Returns the current directory. function _pwd() { var pwd = path.resolve(process.cwd()); - return common.ShellString(pwd); + return pwd; } module.exports = _pwd; diff --git a/tools/eslint/node_modules/shelljs/src/rm.js b/tools/eslint/node_modules/shelljs/src/rm.js index cf2e95b6d816bc..d6e484a085cfee 100644 --- a/tools/eslint/node_modules/shelljs/src/rm.js +++ b/tools/eslint/node_modules/shelljs/src/rm.js @@ -1,6 +1,14 @@ var common = require('./common'); var fs = require('fs'); +common.register('rm', _rm, { + cmdOptions: { + 'f': 'force', + 'r': 'recursive', + 'R': 'recursive', + }, +}); + // Recursively removes 'dir' // Adapted from https://github.com/ryanmcgrath/wrench-js // @@ -15,32 +23,21 @@ function rmdirSyncRecursive(dir, force) { files = fs.readdirSync(dir); // Loop through and delete everything in the sub-tree after checking it - for(var i = 0; i < files.length; i++) { - var file = dir + "/" + files[i], - currFile = fs.lstatSync(file); + for (var i = 0; i < files.length; i++) { + var file = dir + '/' + files[i]; + var currFile = fs.lstatSync(file); - if(currFile.isDirectory()) { // Recursive function back to the beginning + if (currFile.isDirectory()) { // Recursive function back to the beginning rmdirSyncRecursive(file, force); - } - - else if(currFile.isSymbolicLink()) { // Unlink symlinks + } else { // Assume it's a file - perhaps a try/catch belongs here? if (force || isWriteable(file)) { try { common.unlinkSync(file); } catch (e) { - common.error('could not remove file (code '+e.code+'): ' + file, true); + common.error('could not remove file (code ' + e.code + '): ' + file, { continue: true }); } } } - - else // Assume it's a file - perhaps a try/catch belongs here? - if (force || isWriteable(file)) { - try { - common.unlinkSync(file); - } catch (e) { - common.error('could not remove file (code '+e.code+'): ' + file, true); - } - } } // Now that we know everything in the sub-tree has been deleted, we can delete the main directory. @@ -53,13 +50,13 @@ function rmdirSyncRecursive(dir, force) { while (true) { try { result = fs.rmdirSync(dir); - if (fs.existsSync(dir)) throw { code: "EAGAIN" }; + if (fs.existsSync(dir)) throw { code: 'EAGAIN' }; break; - } catch(er) { + } catch (er) { // In addition to error codes, also check if the directory still exists and loop again if true - if (process.platform === "win32" && (er.code === "ENOTEMPTY" || er.code === "EBUSY" || er.code === "EPERM" || er.code === "EAGAIN")) { + if (process.platform === 'win32' && (er.code === 'ENOTEMPTY' || er.code === 'EBUSY' || er.code === 'EPERM' || er.code === 'EAGAIN')) { if (Date.now() - start > 1000) throw er; - } else if (er.code === "ENOENT") { + } else if (er.code === 'ENOENT') { // Directory did not exist, deletion was successful break; } else { @@ -67,8 +64,8 @@ function rmdirSyncRecursive(dir, force) { } } } - } catch(e) { - common.error('could not remove directory (code '+e.code+'): ' + dir, true); + } catch (e) { + common.error('could not remove directory (code ' + e.code + '): ' + dir, { continue: true }); } return result; @@ -81,7 +78,7 @@ function isWriteable(file) { try { var __fd = fs.openSync(file, 'a'); fs.closeSync(__fd); - } catch(e) { + } catch (e) { writePermission = false; } @@ -104,53 +101,45 @@ function isWriteable(file) { //@ rm(['some_file.txt', 'another_file.txt']); // same as above //@ ``` //@ -//@ Removes files. The wildcard `*` is accepted. +//@ Removes files. function _rm(options, files) { - options = common.parseOptions(options, { - 'f': 'force', - 'r': 'recursive', - 'R': 'recursive' - }); - if (!files) - common.error('no paths given'); - - if (typeof files === 'string') - files = [].slice.call(arguments, 1); - // if it's array leave it as it is + if (!files) common.error('no paths given'); - files = common.expand(files); + // Convert to array + files = [].slice.call(arguments, 1); - files.forEach(function(file) { - if (!fs.existsSync(file)) { + files.forEach(function (file) { + var stats; + try { + stats = fs.lstatSync(file); // test for existence + } catch (e) { // Path does not exist, no force flag given - if (!options.force) - common.error('no such file or directory: '+file, true); - + if (!options.force) { + common.error('no such file or directory: ' + file, { continue: true }); + } return; // skip file } // If here, path exists - - var stats = fs.lstatSync(file); if (stats.isFile() || stats.isSymbolicLink()) { - // Do not check for file writing permissions if (options.force) { common.unlinkSync(file); return; } - if (isWriteable(file)) + if (isWriteable(file)) { common.unlinkSync(file); - else - common.error('permission denied: '+file, true); + } else { + common.error('permission denied: ' + file, { continue: true }); + } return; } // simple file // Path is an existing directory, but no -r flag given if (stats.isDirectory() && !options.recursive) { - common.error('path is a directory', true); + common.error('path is a directory', { continue: true }); return; // skip path } @@ -159,5 +148,6 @@ function _rm(options, files) { rmdirSyncRecursive(file, options.force); } }); // forEach(file) + return ''; } // rm module.exports = _rm; diff --git a/tools/eslint/node_modules/shelljs/src/sed.js b/tools/eslint/node_modules/shelljs/src/sed.js index baa385ba1167d4..590ba74ffca2f7 100644 --- a/tools/eslint/node_modules/shelljs/src/sed.js +++ b/tools/eslint/node_modules/shelljs/src/sed.js @@ -1,6 +1,14 @@ var common = require('./common'); var fs = require('fs'); +common.register('sed', _sed, { + globStart: 3, // don't glob-expand regexes + canReceivePipe: true, + cmdOptions: { + 'i': 'inplace', + }, +}); + //@ //@ ### sed([options,] search_regex, replacement, file [, file ...]) //@ ### sed([options,] search_regex, replacement, file_array) @@ -18,47 +26,52 @@ var fs = require('fs'); //@ Reads an input string from `files` and performs a JavaScript `replace()` on the input //@ using the given search regex and replacement string or function. Returns the new string after replacement. function _sed(options, regex, replacement, files) { - options = common.parseOptions(options, { - 'i': 'inplace' - }); + // Check if this is coming from a pipe + var pipe = common.readFromPipe(); - if (typeof replacement === 'string' || typeof replacement === 'function') - replacement = replacement; // no-op - else if (typeof replacement === 'number') - replacement = replacement.toString(); // fallback - else - common.error('invalid replacement string'); + if (typeof replacement !== 'string' && typeof replacement !== 'function') { + if (typeof replacement === 'number') { + replacement = replacement.toString(); // fallback + } else { + common.error('invalid replacement string'); + } + } // Convert all search strings to RegExp - if (typeof regex === 'string') + if (typeof regex === 'string') { regex = RegExp(regex); + } - if (!files) + if (!files && !pipe) { common.error('no files given'); + } - if (typeof files === 'string') - files = [].slice.call(arguments, 3); - // if it's array leave it as it is + files = [].slice.call(arguments, 3); - files = common.expand(files); + if (pipe) { + files.unshift('-'); + } var sed = []; - files.forEach(function(file) { - if (!fs.existsSync(file)) { - common.error('no such file or directory: ' + file, true); + files.forEach(function (file) { + if (!fs.existsSync(file) && file !== '-') { + common.error('no such file or directory: ' + file, 2, { continue: true }); return; } - var result = fs.readFileSync(file, 'utf8').split('\n').map(function (line) { + var contents = file === '-' ? pipe : fs.readFileSync(file, 'utf8'); + var lines = contents.split(/\r*\n/); + var result = lines.map(function (line) { return line.replace(regex, replacement); }).join('\n'); sed.push(result); - if (options.inplace) + if (options.inplace) { fs.writeFileSync(file, result, 'utf8'); + } }); - return common.ShellString(sed.join('\n')); + return sed.join('\n'); } module.exports = _sed; diff --git a/tools/eslint/node_modules/shelljs/src/set.js b/tools/eslint/node_modules/shelljs/src/set.js index 19e26d979d3f4b..3402cd6609b06f 100644 --- a/tools/eslint/node_modules/shelljs/src/set.js +++ b/tools/eslint/node_modules/shelljs/src/set.js @@ -1,11 +1,17 @@ var common = require('./common'); +common.register('set', _set, { + allowGlobbing: false, + wrapOutput: false, +}); + //@ //@ ### set(options) //@ Available options: //@ //@ + `+/-e`: exit upon error (`config.fatal`) //@ + `+/-v`: verbose: show all commands (`config.verbose`) +//@ + `+/-f`: disable filename expansion (globbing) //@ //@ Examples: //@ @@ -18,8 +24,7 @@ var common = require('./common'); function _set(options) { if (!options) { var args = [].slice.call(arguments, 0); - if (args.length < 2) - common.error('must provide an argument'); + if (args.length < 2) common.error('must provide an argument'); options = args[1]; } var negate = (options[0] === '+'); @@ -28,22 +33,23 @@ function _set(options) { } options = common.parseOptions(options, { 'e': 'fatal', - 'v': 'verbose' + 'v': 'verbose', + 'f': 'noglob' }); - var key; if (negate) { - for (key in options) + Object.keys(options).forEach(function (key) { options[key] = !options[key]; + }); } - for (key in options) { + Object.keys(options).forEach(function (key) { // Only change the global config if `negate` is false and the option is true // or if `negate` is true and the option is false (aka negate !== option) if (negate !== options[key]) { common.config[key] = options[key]; } - } + }); return; } module.exports = _set; diff --git a/tools/eslint/node_modules/shelljs/src/sort.js b/tools/eslint/node_modules/shelljs/src/sort.js new file mode 100644 index 00000000000000..041b037725121c --- /dev/null +++ b/tools/eslint/node_modules/shelljs/src/sort.js @@ -0,0 +1,91 @@ +var common = require('./common'); +var fs = require('fs'); + +common.register('sort', _sort, { + canReceivePipe: true, + cmdOptions: { + 'r': 'reverse', + 'n': 'numerical', + }, +}); + +// parse out the number prefix of a line +function parseNumber(str) { + var match = str.match(/^\s*(\d*)\s*(.*)$/); + return { num: Number(match[1]), value: match[2] }; +} + +// compare two strings case-insensitively, but examine case for strings that are +// case-insensitive equivalent +function unixCmp(a, b) { + var aLower = a.toLowerCase(); + var bLower = b.toLowerCase(); + return (aLower === bLower ? + -1 * a.localeCompare(b) : // unix sort treats case opposite how javascript does + aLower.localeCompare(bLower)); +} + +// compare two strings in the fashion that unix sort's -n option works +function numericalCmp(a, b) { + var objA = parseNumber(a); + var objB = parseNumber(b); + if (objA.hasOwnProperty('num') && objB.hasOwnProperty('num')) { + return ((objA.num !== objB.num) ? + (objA.num - objB.num) : + unixCmp(objA.value, objB.value)); + } else { + return unixCmp(objA.value, objB.value); + } +} + +//@ +//@ ### sort([options,] file [, file ...]) +//@ ### sort([options,] file_array) +//@ Available options: +//@ +//@ + `-r`: Reverse the result of comparisons +//@ + `-n`: Compare according to numerical value +//@ +//@ Examples: +//@ +//@ ```javascript +//@ sort('foo.txt', 'bar.txt'); +//@ sort('-r', 'foo.txt'); +//@ ``` +//@ +//@ Return the contents of the files, sorted line-by-line. Sorting multiple +//@ files mixes their content, just like unix sort does. +function _sort(options, files) { + // Check if this is coming from a pipe + var pipe = common.readFromPipe(); + + if (!files && !pipe) common.error('no files given'); + + files = [].slice.call(arguments, 1); + + if (pipe) { + files.unshift('-'); + } + + var lines = []; + files.forEach(function (file) { + if (!fs.existsSync(file) && file !== '-') { + // exit upon any sort of error + common.error('no such file or directory: ' + file); + } + + var contents = file === '-' ? pipe : fs.readFileSync(file, 'utf8'); + lines = lines.concat(contents.trimRight().split(/\r*\n/)); + }); + + var sorted; + sorted = lines.sort(options.numerical ? numericalCmp : unixCmp); + + if (options.reverse) { + sorted = sorted.reverse(); + } + + return sorted.join('\n') + '\n'; +} + +module.exports = _sort; diff --git a/tools/eslint/node_modules/shelljs/src/tail.js b/tools/eslint/node_modules/shelljs/src/tail.js new file mode 100644 index 00000000000000..7ece654b1ea3a0 --- /dev/null +++ b/tools/eslint/node_modules/shelljs/src/tail.js @@ -0,0 +1,72 @@ +var common = require('./common'); +var fs = require('fs'); + +common.register('tail', _tail, { + canReceivePipe: true, + cmdOptions: { + 'n': 'numLines', + }, +}); + +//@ +//@ ### tail([{'-n': \},] file [, file ...]) +//@ ### tail([{'-n': \},] file_array) +//@ Available options: +//@ +//@ + `-n `: Show the last `` lines of the files +//@ +//@ Examples: +//@ +//@ ```javascript +//@ var str = tail({'-n': 1}, 'file*.txt'); +//@ var str = tail('file1', 'file2'); +//@ var str = tail(['file1', 'file2']); // same as above +//@ ``` +//@ +//@ Read the end of a file. +function _tail(options, files) { + var tail = []; + var pipe = common.readFromPipe(); + + if (!files && !pipe) common.error('no paths given'); + + var idx = 1; + if (options.numLines === true) { + idx = 2; + options.numLines = Number(arguments[1]); + } else if (options.numLines === false) { + options.numLines = 10; + } + options.numLines = -1 * Math.abs(options.numLines); + files = [].slice.call(arguments, idx); + + if (pipe) { + files.unshift('-'); + } + + var shouldAppendNewline = false; + files.forEach(function (file) { + if (!fs.existsSync(file) && file !== '-') { + common.error('no such file or directory: ' + file, { continue: true }); + return; + } + + var contents = file === '-' ? pipe : fs.readFileSync(file, 'utf8'); + + var lines = contents.split('\n'); + if (lines[lines.length - 1] === '') { + lines.pop(); + shouldAppendNewline = true; + } else { + shouldAppendNewline = false; + } + + tail = tail.concat(lines.slice(options.numLines)); + }); + + if (shouldAppendNewline) { + tail.push(''); // to add a trailing newline once we join + } + return tail.join('\n'); +} +module.exports = _tail; diff --git a/tools/eslint/node_modules/shelljs/src/tempdir.js b/tools/eslint/node_modules/shelljs/src/tempdir.js index 79b949f0d4f15b..cfd56b3792e427 100644 --- a/tools/eslint/node_modules/shelljs/src/tempdir.js +++ b/tools/eslint/node_modules/shelljs/src/tempdir.js @@ -2,15 +2,18 @@ var common = require('./common'); var os = require('os'); var fs = require('fs'); +common.register('tempdir', _tempDir, { + allowGlobbing: false, + wrapOutput: false, +}); + // Returns false if 'dir' is not a writeable directory, 'dir' otherwise function writeableDir(dir) { - if (!dir || !fs.existsSync(dir)) - return false; + if (!dir || !fs.existsSync(dir)) return false; - if (!fs.statSync(dir).isDirectory()) - return false; + if (!fs.statSync(dir).isDirectory()) return false; - var testFile = dir+'/'+common.randomFileName(); + var testFile = dir + '/' + common.randomFileName(); try { fs.writeFileSync(testFile, ' '); common.unlinkSync(testFile); @@ -34,15 +37,14 @@ function writeableDir(dir) { //@ Follows Python's [tempfile algorithm](http://docs.python.org/library/tempfile.html#tempfile.tempdir). function _tempDir() { var state = common.state; - if (state.tempDir) - return state.tempDir; // from cache + if (state.tempDir) return state.tempDir; // from cache state.tempDir = writeableDir(os.tmpdir && os.tmpdir()) || // node 0.10+ writeableDir(os.tmpDir && os.tmpDir()) || // node 0.8+ - writeableDir(process.env['TMPDIR']) || - writeableDir(process.env['TEMP']) || - writeableDir(process.env['TMP']) || - writeableDir(process.env['Wimp$ScrapDir']) || // RiscOS + writeableDir(process.env.TMPDIR) || + writeableDir(process.env.TEMP) || + writeableDir(process.env.TMP) || + writeableDir(process.env.Wimp$ScrapDir) || // RiscOS writeableDir('C:\\TEMP') || // Windows writeableDir('C:\\TMP') || // Windows writeableDir('\\TEMP') || // Windows diff --git a/tools/eslint/node_modules/shelljs/src/test.js b/tools/eslint/node_modules/shelljs/src/test.js index 068a1ce06ef4c9..3fb38aec43992d 100644 --- a/tools/eslint/node_modules/shelljs/src/test.js +++ b/tools/eslint/node_modules/shelljs/src/test.js @@ -1,6 +1,22 @@ var common = require('./common'); var fs = require('fs'); +common.register('test', _test, { + cmdOptions: { + 'b': 'block', + 'c': 'character', + 'd': 'directory', + 'e': 'exists', + 'f': 'file', + 'L': 'link', + 'p': 'pipe', + 'S': 'socket', + }, + wrapOutput: false, + allowGlobbing: false, +}); + + //@ //@ ### test(expression) //@ Available expression primaries: @@ -23,63 +39,43 @@ var fs = require('fs'); //@ //@ Evaluates expression using the available primaries and returns corresponding value. function _test(options, path) { - if (!path) - common.error('no path given'); - - // hack - only works with unary primaries - options = common.parseOptions(options, { - 'b': 'block', - 'c': 'character', - 'd': 'directory', - 'e': 'exists', - 'f': 'file', - 'L': 'link', - 'p': 'pipe', - 'S': 'socket' - }); + if (!path) common.error('no path given'); var canInterpret = false; - for (var key in options) + Object.keys(options).forEach(function (key) { if (options[key] === true) { canInterpret = true; - break; } + }); - if (!canInterpret) - common.error('could not interpret expression'); + if (!canInterpret) common.error('could not interpret expression'); if (options.link) { try { return fs.lstatSync(path).isSymbolicLink(); - } catch(e) { + } catch (e) { return false; } } - if (!fs.existsSync(path)) - return false; + if (!fs.existsSync(path)) return false; - if (options.exists) - return true; + if (options.exists) return true; var stats = fs.statSync(path); - if (options.block) - return stats.isBlockDevice(); + if (options.block) return stats.isBlockDevice(); + + if (options.character) return stats.isCharacterDevice(); - if (options.character) - return stats.isCharacterDevice(); + if (options.directory) return stats.isDirectory(); - if (options.directory) - return stats.isDirectory(); + if (options.file) return stats.isFile(); - if (options.file) - return stats.isFile(); + if (options.pipe) return stats.isFIFO(); - if (options.pipe) - return stats.isFIFO(); + if (options.socket) return stats.isSocket(); - if (options.socket) - return stats.isSocket(); + return false; // fallback } // test module.exports = _test; diff --git a/tools/eslint/node_modules/shelljs/src/to.js b/tools/eslint/node_modules/shelljs/src/to.js index 65d6d54af90837..99f194e687b460 100644 --- a/tools/eslint/node_modules/shelljs/src/to.js +++ b/tools/eslint/node_modules/shelljs/src/to.js @@ -2,8 +2,13 @@ var common = require('./common'); var fs = require('fs'); var path = require('path'); +common.register('to', _to, { + pipeOnly: true, + wrapOutput: false, +}); + //@ -//@ ### 'string'.to(file) +//@ ### ShellString.prototype.to(file) //@ //@ Examples: //@ @@ -11,20 +16,21 @@ var path = require('path'); //@ cat('input.txt').to('output.txt'); //@ ``` //@ -//@ Analogous to the redirection operator `>` in Unix, but works with JavaScript strings (such as -//@ those returned by `cat`, `grep`, etc). _Like Unix redirections, `to()` will overwrite any existing file!_ +//@ Analogous to the redirection operator `>` in Unix, but works with +//@ ShellStrings (such as those returned by `cat`, `grep`, etc). _Like Unix +//@ redirections, `to()` will overwrite any existing file!_ function _to(options, file) { - if (!file) - common.error('wrong arguments'); + if (!file) common.error('wrong arguments'); - if (!fs.existsSync( path.dirname(file) )) - common.error('no such file or directory: ' + path.dirname(file)); + if (!fs.existsSync(path.dirname(file))) { + common.error('no such file or directory: ' + path.dirname(file)); + } try { - fs.writeFileSync(file, this.toString(), 'utf8'); + fs.writeFileSync(file, this.stdout || this.toString(), 'utf8'); return this; - } catch(e) { - common.error('could not write to file (code '+e.code+'): '+file, true); + } catch (e) { + common.error('could not write to file (code ' + e.code + '): ' + file, { continue: true }); } } module.exports = _to; diff --git a/tools/eslint/node_modules/shelljs/src/toEnd.js b/tools/eslint/node_modules/shelljs/src/toEnd.js index bf29a6526d0f97..cf91c9401c4ced 100644 --- a/tools/eslint/node_modules/shelljs/src/toEnd.js +++ b/tools/eslint/node_modules/shelljs/src/toEnd.js @@ -2,8 +2,13 @@ var common = require('./common'); var fs = require('fs'); var path = require('path'); +common.register('toEnd', _toEnd, { + pipeOnly: true, + wrapOutput: false, +}); + //@ -//@ ### 'string'.toEnd(file) +//@ ### ShellString.prototype.toEnd(file) //@ //@ Examples: //@ @@ -11,20 +16,20 @@ var path = require('path'); //@ cat('input.txt').toEnd('output.txt'); //@ ``` //@ -//@ Analogous to the redirect-and-append operator `>>` in Unix, but works with JavaScript strings (such as -//@ those returned by `cat`, `grep`, etc). +//@ Analogous to the redirect-and-append operator `>>` in Unix, but works with +//@ ShellStrings (such as those returned by `cat`, `grep`, etc). function _toEnd(options, file) { - if (!file) - common.error('wrong arguments'); + if (!file) common.error('wrong arguments'); - if (!fs.existsSync( path.dirname(file) )) - common.error('no such file or directory: ' + path.dirname(file)); + if (!fs.existsSync(path.dirname(file))) { + common.error('no such file or directory: ' + path.dirname(file)); + } try { - fs.appendFileSync(file, this.toString(), 'utf8'); + fs.appendFileSync(file, this.stdout || this.toString(), 'utf8'); return this; - } catch(e) { - common.error('could not append to file (code '+e.code+'): '+file, true); + } catch (e) { + common.error('could not append to file (code ' + e.code + '): ' + file, { continue: true }); } } module.exports = _toEnd; diff --git a/tools/eslint/node_modules/shelljs/src/touch.js b/tools/eslint/node_modules/shelljs/src/touch.js index bbc2c1968654ab..b672b2d25528b4 100644 --- a/tools/eslint/node_modules/shelljs/src/touch.js +++ b/tools/eslint/node_modules/shelljs/src/touch.js @@ -1,8 +1,19 @@ var common = require('./common'); var fs = require('fs'); +common.register('touch', _touch, { + cmdOptions: { + 'a': 'atime_only', + 'c': 'no_create', + 'd': 'date', + 'm': 'mtime_only', + 'r': 'reference', + }, +}); + //@ -//@ ### touch([options,] file) +//@ ### touch([options,] file [, file ...]) +//@ ### touch([options,] file_array) //@ Available options: //@ //@ + `-a`: Change only the access time @@ -23,28 +34,18 @@ var fs = require('fs'); //@ A FILE argument that does not exist is created empty, unless -c is supplied. //@ This is a partial implementation of *[touch(1)](http://linux.die.net/man/1/touch)*. function _touch(opts, files) { - opts = common.parseOptions(opts, { - 'a': 'atime_only', - 'c': 'no_create', - 'd': 'date', - 'm': 'mtime_only', - 'r': 'reference', - }); - if (!files) { - common.error('no paths given'); - } - - if (Array.isArray(files)) { - files.forEach(function(f) { - touchFile(opts, f); - }); + common.error('no files given'); } else if (typeof files === 'string') { - touchFile(opts, files); + files = [].slice.call(arguments, 1); } else { common.error('file arg should be a string file path or an Array of string file paths'); } + files.forEach(function (f) { + touchFile(opts, f); + }); + return ''; } function touchFile(opts, file) { diff --git a/tools/eslint/node_modules/shelljs/src/uniq.js b/tools/eslint/node_modules/shelljs/src/uniq.js new file mode 100644 index 00000000000000..8f5da00285a3a5 --- /dev/null +++ b/tools/eslint/node_modules/shelljs/src/uniq.js @@ -0,0 +1,80 @@ +var common = require('./common'); +var fs = require('fs'); + +// add c spaces to the left of str +function lpad(c, str) { + var res = '' + str; + if (res.length < c) { + res = Array((c - res.length) + 1).join(' ') + res; + } + return res; +} + +common.register('uniq', _uniq, { + canReceivePipe: true, + cmdOptions: { + 'i': 'ignoreCase', + 'c': 'count', + 'd': 'duplicates', + }, +}); + +//@ +//@ ### uniq([options,] [input, [output]]) +//@ Available options: +//@ +//@ + `-i`: Ignore case while comparing +//@ + `-c`: Prefix lines by the number of occurrences +//@ + `-d`: Only print duplicate lines, one for each group of identical lines +//@ +//@ Examples: +//@ +//@ ```javascript +//@ uniq('foo.txt'); +//@ uniq('-i', 'foo.txt'); +//@ uniq('-cd', 'foo.txt', 'bar.txt'); +//@ ``` +//@ +//@ Filter adjacent matching lines from input +function _uniq(options, input, output) { + // Check if this is coming from a pipe + var pipe = common.readFromPipe(); + + if (!input && !pipe) common.error('no input given'); + + var lines = (input ? fs.readFileSync(input, 'utf8') : pipe). + trimRight(). + split(/\r*\n/); + + var compare = function (a, b) { + return options.ignoreCase ? + a.toLocaleLowerCase().localeCompare(b.toLocaleLowerCase()) : + a.localeCompare(b); + }; + var uniqed = lines.reduceRight(function (res, e) { + // Perform uniq -c on the input + if (res.length === 0) { + return [{ count: 1, ln: e }]; + } else if (compare(res[0].ln, e) === 0) { + return [{ count: res[0].count + 1, ln: e }].concat(res.slice(1)); + } else { + return [{ count: 1, ln: e }].concat(res); + } + }, []).filter(function (obj) { + // Do we want only duplicated objects? + return options.duplicates ? obj.count > 1 : true; + }).map(function (obj) { + // Are we tracking the counts of each line? + return (options.count ? (lpad(7, obj.count) + ' ') : '') + obj.ln; + }).join('\n') + '\n'; + + if (output) { + (new common.ShellString(uniqed)).to(output); + // if uniq writes to output, nothing is passed to the next command in the pipeline (if any) + return ''; + } else { + return uniqed; + } +} + +module.exports = _uniq; diff --git a/tools/eslint/node_modules/shelljs/src/which.js b/tools/eslint/node_modules/shelljs/src/which.js index d17634ee941d96..ef5d185eb0e462 100644 --- a/tools/eslint/node_modules/shelljs/src/which.js +++ b/tools/eslint/node_modules/shelljs/src/which.js @@ -2,23 +2,27 @@ var common = require('./common'); var fs = require('fs'); var path = require('path'); +common.register('which', _which, { + allowGlobbing: false, +}); + // XP's system default value for PATHEXT system variable, just in case it's not // set on Windows. var XP_DEFAULT_PATHEXT = '.com;.exe;.bat;.cmd;.vbs;.vbe;.js;.jse;.wsf;.wsh'; // Cross-platform method for splitting environment PATH variables function splitPath(p) { - if (!p) - return []; + if (!p) return []; - if (common.platform === 'win') + if (common.platform === 'win') { return p.split(';'); - else + } else { return p.split(':'); + } } -function checkPath(path) { - return fs.existsSync(path) && !fs.statSync(path).isDirectory(); +function checkPath(pathName) { + return fs.existsSync(pathName) && !fs.statSync(pathName).isDirectory(); } //@ @@ -34,19 +38,17 @@ function checkPath(path) { //@ `PATHEXT` variable to append the extension if it's not already executable. //@ Returns string containing the absolute path to the command. function _which(options, cmd) { - if (!cmd) - common.error('must specify command'); + if (!cmd) common.error('must specify command'); - var pathEnv = process.env.path || process.env.Path || process.env.PATH, - pathArray = splitPath(pathEnv), - where = null; + var pathEnv = process.env.path || process.env.Path || process.env.PATH; + var pathArray = splitPath(pathEnv); + var where = null; // No relative/absolute paths provided? if (cmd.search(/\//) === -1) { // Search for command in PATH - pathArray.forEach(function(dir) { - if (where) - return; // already found it + pathArray.forEach(function (dir) { + if (where) return; // already found it var attempt = path.resolve(dir, cmd); @@ -88,11 +90,10 @@ function _which(options, cmd) { } // Command not found anywhere? - if (!checkPath(cmd) && !where) - return null; + if (!checkPath(cmd) && !where) return null; where = where || path.resolve(cmd); - return common.ShellString(where); + return where; } module.exports = _which; diff --git a/tools/eslint/node_modules/string-width/package.json b/tools/eslint/node_modules/string-width/package.json index 6fc310fca4230d..b0e9dfdea93cf7 100644 --- a/tools/eslint/node_modules/string-width/package.json +++ b/tools/eslint/node_modules/string-width/package.json @@ -38,8 +38,7 @@ "type": "range" }, "_requiredBy": [ - "/inquirer", - "/table" + "/inquirer" ], "_resolved": "https://registry.npmjs.org/string-width/-/string-width-1.0.2.tgz", "_shasum": "118bdf5b8cdc51a2a7e70d211e07e2b0b9b107d3", diff --git a/tools/eslint/node_modules/strip-ansi/package.json b/tools/eslint/node_modules/strip-ansi/package.json index dced2726e06f26..323a21ebb41a8c 100644 --- a/tools/eslint/node_modules/strip-ansi/package.json +++ b/tools/eslint/node_modules/strip-ansi/package.json @@ -40,7 +40,8 @@ "_requiredBy": [ "/chalk", "/inquirer", - "/string-width" + "/string-width", + "/table/string-width" ], "_resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", "_shasum": "6a385fb8853d952d5ff05d0e8aaf94278dc63dcf", diff --git a/tools/eslint/node_modules/strip-json-comments/cli.js b/tools/eslint/node_modules/strip-json-comments/cli.js deleted file mode 100755 index aec5aa20e4a073..00000000000000 --- a/tools/eslint/node_modules/strip-json-comments/cli.js +++ /dev/null @@ -1,41 +0,0 @@ -#!/usr/bin/env node -'use strict'; -var fs = require('fs'); -var strip = require('./strip-json-comments'); -var input = process.argv[2]; - - -function getStdin(cb) { - var ret = ''; - - process.stdin.setEncoding('utf8'); - - process.stdin.on('data', function (data) { - ret += data; - }); - - process.stdin.on('end', function () { - cb(ret); - }); -} - -if (process.argv.indexOf('-h') !== -1 || process.argv.indexOf('--help') !== -1) { - console.log('strip-json-comments input-file > output-file'); - console.log('or'); - console.log('strip-json-comments < input-file > output-file'); - return; -} - -if (process.argv.indexOf('-v') !== -1 || process.argv.indexOf('--version') !== -1) { - console.log(require('./package').version); - return; -} - -if (input) { - process.stdout.write(strip(fs.readFileSync(input, 'utf8'))); - return; -} - -getStdin(function (data) { - process.stdout.write(strip(data)); -}); diff --git a/tools/eslint/node_modules/strip-json-comments/index.js b/tools/eslint/node_modules/strip-json-comments/index.js new file mode 100644 index 00000000000000..4e6576e6d3c388 --- /dev/null +++ b/tools/eslint/node_modules/strip-json-comments/index.js @@ -0,0 +1,70 @@ +'use strict'; +var singleComment = 1; +var multiComment = 2; + +function stripWithoutWhitespace() { + return ''; +} + +function stripWithWhitespace(str, start, end) { + return str.slice(start, end).replace(/\S/g, ' '); +} + +module.exports = function (str, opts) { + opts = opts || {}; + + var currentChar; + var nextChar; + var insideString = false; + var insideComment = false; + var offset = 0; + var ret = ''; + var strip = opts.whitespace === false ? stripWithoutWhitespace : stripWithWhitespace; + + for (var i = 0; i < str.length; i++) { + currentChar = str[i]; + nextChar = str[i + 1]; + + if (!insideComment && currentChar === '"') { + var escaped = str[i - 1] === '\\' && str[i - 2] !== '\\'; + if (!escaped) { + insideString = !insideString; + } + } + + if (insideString) { + continue; + } + + if (!insideComment && currentChar + nextChar === '//') { + ret += str.slice(offset, i); + offset = i; + insideComment = singleComment; + i++; + } else if (insideComment === singleComment && currentChar + nextChar === '\r\n') { + i++; + insideComment = false; + ret += strip(str, offset, i); + offset = i; + continue; + } else if (insideComment === singleComment && currentChar === '\n') { + insideComment = false; + ret += strip(str, offset, i); + offset = i; + } else if (!insideComment && currentChar + nextChar === '/*') { + ret += str.slice(offset, i); + offset = i; + insideComment = multiComment; + i++; + continue; + } else if (insideComment === multiComment && currentChar + nextChar === '*/') { + i++; + insideComment = false; + ret += strip(str, offset, i + 1); + offset = i + 1; + continue; + } + } + + return ret + (insideComment ? strip(str.substr(offset)) : str.substr(offset)); +}; diff --git a/tools/eslint/node_modules/strip-json-comments/package.json b/tools/eslint/node_modules/strip-json-comments/package.json index de43cb650fbdcb..6bbd9d717fbf7b 100644 --- a/tools/eslint/node_modules/strip-json-comments/package.json +++ b/tools/eslint/node_modules/strip-json-comments/package.json @@ -2,75 +2,76 @@ "_args": [ [ { - "raw": "strip-json-comments@~1.0.1", + "raw": "strip-json-comments@~2.0.1", "scope": null, "escapedName": "strip-json-comments", "name": "strip-json-comments", - "rawSpec": "~1.0.1", - "spec": ">=1.0.1 <1.1.0", + "rawSpec": "~2.0.1", + "spec": ">=2.0.1 <2.1.0", "type": "range" }, "/Users/trott/io.js/tools/node_modules/eslint" ] ], - "_from": "strip-json-comments@>=1.0.1 <1.1.0", - "_id": "strip-json-comments@1.0.4", + "_from": "strip-json-comments@>=2.0.1 <2.1.0", + "_id": "strip-json-comments@2.0.1", "_inCache": true, "_location": "/strip-json-comments", - "_nodeVersion": "0.12.5", + "_nodeVersion": "4.2.4", + "_npmOperationalInternal": { + "host": "packages-9-west.internal.npmjs.com", + "tmp": "tmp/strip-json-comments-2.0.1.tgz_1455006605207_0.8280157081317157" + }, "_npmUser": { "name": "sindresorhus", "email": "sindresorhus@gmail.com" }, - "_npmVersion": "2.11.2", + "_npmVersion": "3.7.2", "_phantomChildren": {}, "_requested": { - "raw": "strip-json-comments@~1.0.1", + "raw": "strip-json-comments@~2.0.1", "scope": null, "escapedName": "strip-json-comments", "name": "strip-json-comments", - "rawSpec": "~1.0.1", - "spec": ">=1.0.1 <1.1.0", + "rawSpec": "~2.0.1", + "spec": ">=2.0.1 <2.1.0", "type": "range" }, "_requiredBy": [ "/eslint" ], - "_resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-1.0.4.tgz", - "_shasum": "1e15fbcac97d3ee99bf2d73b4c656b082bbafb91", + "_resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", + "_shasum": "3c531942e908c2697c0ec344858c286c7ca0a60a", "_shrinkwrap": null, - "_spec": "strip-json-comments@~1.0.1", + "_spec": "strip-json-comments@~2.0.1", "_where": "/Users/trott/io.js/tools/node_modules/eslint", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "sindresorhus.com" }, - "bin": { - "strip-json-comments": "cli.js" - }, "bugs": { "url": "https://github.com/sindresorhus/strip-json-comments/issues" }, "dependencies": {}, "description": "Strip comments from JSON. Lets you use comments in your JSON files!", "devDependencies": { - "mocha": "*" + "ava": "*", + "xo": "*" }, "directories": {}, "dist": { - "shasum": "1e15fbcac97d3ee99bf2d73b4c656b082bbafb91", - "tarball": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-1.0.4.tgz" + "shasum": "3c531942e908c2697c0ec344858c286c7ca0a60a", + "tarball": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz" }, "engines": { - "node": ">=0.8.0" + "node": ">=0.10.0" }, "files": [ - "cli.js", - "strip-json-comments.js" + "index.js" ], - "gitHead": "f58348696368583cc5bb18525fe31eacc9bd00e1", - "homepage": "https://github.com/sindresorhus/strip-json-comments", + "gitHead": "1aef99eaa70d07981156e8aaa722e750c3b4eaf9", + "homepage": "https://github.com/sindresorhus/strip-json-comments#readme", "keywords": [ "json", "strip", @@ -86,12 +87,9 @@ "settings", "util", "env", - "environment", - "cli", - "bin" + "environment" ], "license": "MIT", - "main": "strip-json-comments", "maintainers": [ { "name": "sindresorhus", @@ -106,7 +104,7 @@ "url": "git+https://github.com/sindresorhus/strip-json-comments.git" }, "scripts": { - "test": "mocha --ui tdd" + "test": "xo && ava" }, - "version": "1.0.4" + "version": "2.0.1" } diff --git a/tools/eslint/node_modules/strip-json-comments/readme.md b/tools/eslint/node_modules/strip-json-comments/readme.md index 63ce165b23809f..0ee58dfe3a2e9b 100644 --- a/tools/eslint/node_modules/strip-json-comments/readme.md +++ b/tools/eslint/node_modules/strip-json-comments/readme.md @@ -11,34 +11,23 @@ This is now possible: } ``` -It will remove single-line comments `//` and multi-line comments `/**/`. +It will replace single-line comments `//` and multi-line comments `/**/` with whitespace. This allows JSON error positions to remain as close as possible to the original source. Also available as a [gulp](https://github.com/sindresorhus/gulp-strip-json-comments)/[grunt](https://github.com/sindresorhus/grunt-strip-json-comments)/[broccoli](https://github.com/sindresorhus/broccoli-strip-json-comments) plugin. -- - -*There's also [`json-comments`](https://npmjs.org/package/json-comments), but it's only for Node.js, inefficient, bloated as it also minifies, and comes with a `require` hook, which is :(* - ## Install -```sh -$ npm install --save strip-json-comments -``` - -```sh -$ bower install --save strip-json-comments ``` - -```sh -$ component install sindresorhus/strip-json-comments +$ npm install --save strip-json-comments ``` ## Usage ```js -var json = '{/*rainbows*/"unicorn":"cake"}'; +const json = '{/*rainbows*/"unicorn":"cake"}'; + JSON.parse(stripJsonComments(json)); //=> {unicorn: 'cake'} ``` @@ -46,7 +35,7 @@ JSON.parse(stripJsonComments(json)); ## API -### stripJsonComments(input) +### stripJsonComments(input, [options]) #### input @@ -54,25 +43,20 @@ Type: `string` Accepts a string with JSON and returns a string without comments. +#### options -## CLI +##### whitespace -```sh -$ npm install --global strip-json-comments -``` +Type: `boolean` +Default: `true` -```sh -$ strip-json-comments --help - -strip-json-comments input-file > output-file -# or -strip-json-comments < input-file > output-file -``` +Replace comments with whitespace instead of stripping them entirely. ## Related -- [`strip-css-comments`](https://github.com/sindresorhus/strip-css-comments) +- [strip-json-comments-cli](https://github.com/sindresorhus/strip-json-comments-cli) - CLI for this module +- [strip-css-comments](https://github.com/sindresorhus/strip-css-comments) - Strip comments from CSS ## License diff --git a/tools/eslint/node_modules/strip-json-comments/strip-json-comments.js b/tools/eslint/node_modules/strip-json-comments/strip-json-comments.js deleted file mode 100644 index eb77ce7456b8e5..00000000000000 --- a/tools/eslint/node_modules/strip-json-comments/strip-json-comments.js +++ /dev/null @@ -1,73 +0,0 @@ -/*! - strip-json-comments - Strip comments from JSON. Lets you use comments in your JSON files! - https://github.com/sindresorhus/strip-json-comments - by Sindre Sorhus - MIT License -*/ -(function () { - 'use strict'; - - var singleComment = 1; - var multiComment = 2; - - function stripJsonComments(str) { - var currentChar; - var nextChar; - var insideString = false; - var insideComment = false; - var ret = ''; - - for (var i = 0; i < str.length; i++) { - currentChar = str[i]; - nextChar = str[i + 1]; - - if (!insideComment && currentChar === '"') { - var escaped = str[i - 1] === '\\' && str[i - 2] !== '\\'; - if (!insideComment && !escaped && currentChar === '"') { - insideString = !insideString; - } - } - - if (insideString) { - ret += currentChar; - continue; - } - - if (!insideComment && currentChar + nextChar === '//') { - insideComment = singleComment; - i++; - } else if (insideComment === singleComment && currentChar + nextChar === '\r\n') { - insideComment = false; - i++; - ret += currentChar; - ret += nextChar; - continue; - } else if (insideComment === singleComment && currentChar === '\n') { - insideComment = false; - } else if (!insideComment && currentChar + nextChar === '/*') { - insideComment = multiComment; - i++; - continue; - } else if (insideComment === multiComment && currentChar + nextChar === '*/') { - insideComment = false; - i++; - continue; - } - - if (insideComment) { - continue; - } - - ret += currentChar; - } - - return ret; - } - - if (typeof module !== 'undefined' && module.exports) { - module.exports = stripJsonComments; - } else { - window.stripJsonComments = stripJsonComments; - } -})(); diff --git a/tools/eslint/node_modules/table/dist/alignString.js.map b/tools/eslint/node_modules/table/dist/alignString.js.map deleted file mode 100644 index 9d6e8b84e39b13..00000000000000 --- a/tools/eslint/node_modules/table/dist/alignString.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["alignString.js"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;AACA;;;;;;AAEA,IAAI,oBAAJ;IACI,kBADJ;IAEI,mBAFJ;IAGI,mBAHJ;;AAKA,aAAa,CACT,MADS,EAET,OAFS,EAGT,QAHS,CAAb;;;;;;;AAWA,YAAY,mBAAC,OAAD,EAAU,KAAV,EAAoB;AAC5B,WAAO,UAAU,sBAAS,GAAT,EAAc,KAAd,CAAjB;AACH,CAFD;;;;;;;AASA,aAAa,oBAAC,OAAD,EAAU,KAAV,EAAoB;AAC7B,WAAO,sBAAS,GAAT,EAAc,KAAd,IAAuB,OAA9B;AACH,CAFD;;;;;;;AASA,cAAc,qBAAC,OAAD,EAAU,KAAV,EAAoB;AAC9B,QAAI,kBAAJ;;AAEA,gBAAY,QAAQ,CAApB;;AAEA,QAAI,YAAY,CAAZ,KAAkB,CAAtB,EAAyB;AACrB,eAAO,sBAAS,GAAT,EAAc,SAAd,IAA2B,OAA3B,GAAqC,sBAAS,GAAT,EAAc,SAAd,CAA5C;AACH,KAFD,MAEO;AACH,oBAAY,qBAAQ,SAAR,CAAZ;;AAEA,eAAO,sBAAS,GAAT,EAAc,SAAd,IAA2B,OAA3B,GAAqC,sBAAS,GAAT,EAAc,YAAY,CAA1B,CAA5C;AACH;AACJ,CAZD;;;;;;;;;;;;kBAuBe,UAAC,OAAD,EAAU,cAAV,EAA0B,SAA1B,EAAwC;AACnD,QAAI,uBAAJ;QACI,qBADJ;;AAGA,QAAI,CAAC,wBAAW,OAAX,CAAL,EAA0B;AACtB,cAAM,IAAI,KAAJ,CAAU,2CAAV,CAAN;AACH;;AAED,QAAI,CAAC,wBAAW,cAAX,CAAL,EAAiC;AAC7B,cAAM,IAAI,KAAJ,CAAU,mDAAV,CAAN;AACH;;AAED,mBAAe,2BAAY,OAAZ,CAAf;;AAEA,QAAI,eAAe,cAAnB,EAAmC;;;AAG/B,cAAM,IAAI,KAAJ,CAAU,2EAAV,CAAN;AACH;;AAED,QAAI,CAAC,wBAAW,SAAX,CAAL,EAA4B;AACxB,cAAM,IAAI,KAAJ,CAAU,6CAAV,CAAN;AACH;;AAED,QAAI,WAAW,OAAX,CAAmB,SAAnB,MAAkC,CAAC,CAAvC,EAA0C;AACtC,cAAM,IAAI,KAAJ,CAAU,4FAAV,CAAN;AACH;;AAED,QAAI,iBAAiB,CAArB,EAAwB;AACpB,eAAO,sBAAS,GAAT,EAAc,cAAd,CAAP;AACH;;AAED,qBAAiB,iBAAiB,YAAlC;;AAEA,QAAI,cAAc,MAAlB,EAA0B;AACtB,eAAO,UAAU,OAAV,EAAmB,cAAnB,CAAP;AACH;;AAED,QAAI,cAAc,OAAlB,EAA2B;AACvB,eAAO,WAAW,OAAX,EAAoB,cAApB,CAAP;AACH;;AAED,WAAO,YAAY,OAAZ,EAAqB,cAArB,CAAP;AACH,C","file":"alignString.js","sourcesContent":["import _ from 'lodash';\nimport stringWidth from 'string-width';\n\nlet alignCenter,\n alignLeft,\n alignRight,\n alignments;\n\nalignments = [\n 'left',\n 'right',\n 'center'\n];\n\n/**\n * @param {string} subject\n * @param {number} width\n * @returns {string}\n */\nalignLeft = (subject, width) => {\n return subject + _.repeat(' ', width);\n};\n\n/**\n * @param {string} subject\n * @param {number} width\n * @returns {string}\n */\nalignRight = (subject, width) => {\n return _.repeat(' ', width) + subject;\n};\n\n/**\n * @param {string} subject\n * @param {number} width\n * @returns {string}\n */\nalignCenter = (subject, width) => {\n let halfWidth;\n\n halfWidth = width / 2;\n\n if (halfWidth % 2 === 0) {\n return _.repeat(' ', halfWidth) + subject + _.repeat(' ', halfWidth);\n } else {\n halfWidth = _.floor(halfWidth);\n\n return _.repeat(' ', halfWidth) + subject + _.repeat(' ', halfWidth + 1);\n }\n};\n\n/**\n * Pads a string to the left and/or right to position the subject\n * text in a desired alignment within a container.\n *\n * @param {string} subject\n * @param {number} containerWidth\n * @param {string} alignment One of the valid options (left, right, center).\n * @returns {string}\n */\nexport default (subject, containerWidth, alignment) => {\n let availableWidth,\n subjectWidth;\n\n if (!_.isString(subject)) {\n throw new Error('Subject parameter value must be a string.');\n }\n\n if (!_.isNumber(containerWidth)) {\n throw new Error('Container width parameter value must be a number.');\n }\n\n subjectWidth = stringWidth(subject);\n\n if (subjectWidth > containerWidth) {\n // console.log('subjectWidth', subjectWidth, 'containerWidth', containerWidth, 'subject', subject);\n\n throw new Error('Subject parameter value width cannot be greater than the container width.');\n }\n\n if (!_.isString(alignment)) {\n throw new Error('Alignment parameter value must be a string.');\n }\n\n if (alignments.indexOf(alignment) === -1) {\n throw new Error('Alignment parameter value must be a known alignment parameter value (left, right, center).');\n }\n\n if (subjectWidth === 0) {\n return _.repeat(' ', containerWidth);\n }\n\n availableWidth = containerWidth - subjectWidth;\n\n if (alignment === 'left') {\n return alignLeft(subject, availableWidth);\n }\n\n if (alignment === 'right') {\n return alignRight(subject, availableWidth);\n }\n\n return alignCenter(subject, availableWidth);\n};\n"]} \ No newline at end of file diff --git a/tools/eslint/node_modules/table/dist/alignTableData.js.map b/tools/eslint/node_modules/table/dist/alignTableData.js.map deleted file mode 100644 index 45aea74993674f..00000000000000 --- a/tools/eslint/node_modules/table/dist/alignTableData.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["alignTableData.js"],"names":[],"mappings":";;;;;;;;;;AACA;;;;AACA;;;;;;;;;;;;kBAOe,UAAC,IAAD,EAAO,MAAP,EAAkB;AAC7B,WAAO,mBAAM,IAAN,EAAY,UAAC,KAAD,EAAW;AAC1B,eAAO,mBAAM,KAAN,EAAa,UAAC,KAAD,EAAQ,MAAR,EAAmB;AACnC,gBAAI,eAAJ;;AAEA,qBAAS,OAAO,OAAP,CAAe,MAAf,CAAT;;AAEA,gBAAI,2BAAY,KAAZ,MAAuB,OAAO,KAAlC,EAAyC;AACrC,uBAAO,KAAP;AACH,aAFD,MAEO;AACH,uBAAO,2BAAY,KAAZ,EAAmB,OAAO,KAA1B,EAAiC,OAAO,SAAxC,CAAP;AACH;AACJ,SAVM,CAAP;AAWH,KAZM,CAAP;AAaH,C","file":"alignTableData.js","sourcesContent":["import _ from 'lodash';\nimport alignString from './alignString';\nimport stringWidth from 'string-width';\n\n/**\n * @param {table~row[]} rows\n * @param {Object} config\n * @return {table~row[]}\n */\nexport default (rows, config) => {\n return _.map(rows, (cells) => {\n return _.map(cells, (value, index1) => {\n let column;\n\n column = config.columns[index1];\n\n if (stringWidth(value) === column.width) {\n return value;\n } else {\n return alignString(value, column.width, column.alignment);\n }\n });\n });\n};\n"]} \ No newline at end of file diff --git a/tools/eslint/node_modules/table/dist/calculateCellHeight.js b/tools/eslint/node_modules/table/dist/calculateCellHeight.js index f90110adb11d51..b5ec6998d58d0e 100644 --- a/tools/eslint/node_modules/table/dist/calculateCellHeight.js +++ b/tools/eslint/node_modules/table/dist/calculateCellHeight.js @@ -25,7 +25,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * @returns {number} */ exports.default = function (value, columnWidth) { - let useWrapWord = arguments.length <= 2 || arguments[2] === undefined ? false : arguments[2]; + let useWrapWord = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; if (!_lodash2.default.isString(value)) { throw new Error('Value must be a string.'); diff --git a/tools/eslint/node_modules/table/dist/calculateCellHeight.js.map b/tools/eslint/node_modules/table/dist/calculateCellHeight.js.map deleted file mode 100644 index 184fdbf02cd47c..00000000000000 --- a/tools/eslint/node_modules/table/dist/calculateCellHeight.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["calculateCellHeight.js"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AACA;;;;AACA;;;;;;;;;;;;;kBAQe,UAAC,KAAD,EAAQ,WAAR,EAA6C;AAAA,QAAxB,WAAwB,yDAAV,KAAU;;AACxD,QAAI,CAAC,wBAAW,KAAX,CAAL,EAAwB;AACpB,cAAM,IAAI,KAAJ,CAAU,yBAAV,CAAN;AACH;;AAED,QAAI,CAAC,yBAAY,WAAZ,CAAL,EAA+B;AAC3B,cAAM,IAAI,KAAJ,CAAU,kCAAV,CAAN;AACH;;AAED,QAAI,cAAc,CAAlB,EAAqB;AACjB,cAAM,IAAI,KAAJ,CAAU,sCAAV,CAAN;AACH;;AAED,QAAI,WAAJ,EAAiB;AACb,eAAO,wBAAS,KAAT,EAAgB,WAAhB,EAA6B,MAApC;AACH;;AAED,WAAO,oBAAO,2BAAY,KAAZ,IAAqB,WAA5B,CAAP;AACH,C","file":"calculateCellHeight.js","sourcesContent":["import _ from 'lodash';\nimport stringWidth from 'string-width';\nimport wrapWord from './wrapWord';\n\n/**\n * @param {string} value\n * @param {number} columnWidth\n * @param {boolean} useWrapWord\n * @returns {number}\n */\nexport default (value, columnWidth, useWrapWord = false) => {\n if (!_.isString(value)) {\n throw new Error('Value must be a string.');\n }\n\n if (!_.isInteger(columnWidth)) {\n throw new Error('Column width must be an integer.');\n }\n\n if (columnWidth < 1) {\n throw new Error('Column width must be greater than 0.');\n }\n\n if (useWrapWord) {\n return wrapWord(value, columnWidth).length;\n }\n\n return _.ceil(stringWidth(value) / columnWidth);\n};\n"]} \ No newline at end of file diff --git a/tools/eslint/node_modules/table/dist/calculateCellWidthIndex.js.map b/tools/eslint/node_modules/table/dist/calculateCellWidthIndex.js.map deleted file mode 100644 index 112a04e8ee6c35..00000000000000 --- a/tools/eslint/node_modules/table/dist/calculateCellWidthIndex.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["calculateCellWidthIndex.js"],"names":[],"mappings":";;;;;;;;;;AACA;;;;;;;;;;;;;kBAQe,UAAC,KAAD,EAAW;AACtB,WAAO,mBAAM,KAAN,EAAa,UAAC,KAAD,EAAW;AAC3B,eAAO,2BAAY,KAAZ,CAAP;AACH,KAFM,CAAP;AAGH,C","file":"calculateCellWidthIndex.js","sourcesContent":["import _ from 'lodash';\nimport stringWidth from 'string-width';\n\n/**\n * Calculates width of each cell contents.\n *\n * @param {string[]} cells\n * @return {number[]}\n */\nexport default (cells) => {\n return _.map(cells, (value) => {\n return stringWidth(value);\n });\n};\n"]} \ No newline at end of file diff --git a/tools/eslint/node_modules/table/dist/calculateMaximumColumnWidthIndex.js.map b/tools/eslint/node_modules/table/dist/calculateMaximumColumnWidthIndex.js.map deleted file mode 100644 index ea1e5e9ce49b3e..00000000000000 --- a/tools/eslint/node_modules/table/dist/calculateMaximumColumnWidthIndex.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["calculateMaximumColumnWidthIndex.js"],"names":[],"mappings":";;;;;;;;;;;;;;AACA;;;;;;;;;;;;;kBAQe,UAAC,IAAD,EAAU;AACrB,QAAI,gBAAJ;;AAEA,QAAI,CAAC,KAAK,CAAL,CAAL,EAAc;AACV,cAAM,IAAI,KAAJ,CAAU,qCAAV,CAAN;AACH;;AAED,cAAU,oBAAO,MAAM,KAAK,CAAL,EAAQ,MAAd,CAAP,EAA8B,CAA9B,CAAV;;AAEA,2BAAU,IAAV,EAAgB,UAAC,GAAD,EAAS;AACrB,YAAI,yBAAJ;;AAEA,2BAAmB,uCAAwB,GAAxB,CAAnB;;AAEA,+BAAU,gBAAV,EAA4B,UAAC,UAAD,EAAa,MAAb,EAAwB;AAChD,gBAAI,QAAQ,MAAR,IAAkB,UAAtB,EAAkC;AAC9B,wBAAQ,MAAR,IAAkB,UAAlB;AACH;AACJ,SAJD;AAKH,KAVD;;AAYA,WAAO,OAAP;AACH,C","file":"calculateMaximumColumnWidthIndex.js","sourcesContent":["import _ from 'lodash';\nimport calculateCellWidthIndex from './calculateCellWidthIndex';\n\n/**\n * Produces an array of values that describe the largest value length (width) in every column.\n *\n * @param {Array[]} rows\n * @return {number[]}\n */\nexport default (rows) => {\n let columns;\n\n if (!rows[0]) {\n throw new Error('Dataset must have at least one row.');\n }\n\n columns = _.fill(Array(rows[0].length), 0);\n\n _.forEach(rows, (row) => {\n let columnWidthIndex;\n\n columnWidthIndex = calculateCellWidthIndex(row);\n\n _.forEach(columnWidthIndex, (valueWidth, index0) => {\n if (columns[index0] < valueWidth) {\n columns[index0] = valueWidth;\n }\n });\n });\n\n return columns;\n};\n"]} \ No newline at end of file diff --git a/tools/eslint/node_modules/table/dist/calculateRowHeightIndex.js.map b/tools/eslint/node_modules/table/dist/calculateRowHeightIndex.js.map deleted file mode 100644 index 9816a50a9a99a9..00000000000000 --- a/tools/eslint/node_modules/table/dist/calculateRowHeightIndex.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["calculateRowHeightIndex.js"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AACA;;;;;;;;;;;;;;kBASe,UAAC,IAAD,EAAO,MAAP,EAAkB;AAC7B,QAAI,qBAAJ;QACI,mBADJ;;AAGA,iBAAa,KAAK,CAAL,EAAQ,MAArB;;AAEA,mBAAe,EAAf;;AAEA,2BAAU,IAAV,EAAgB,UAAC,KAAD,EAAW;AACvB,YAAI,wBAAJ;;AAEA,0BAAkB,oBAAO,MAAM,UAAN,CAAP,EAA0B,CAA1B,CAAlB;;AAEA,+BAAU,KAAV,EAAiB,UAAC,KAAD,EAAQ,MAAR,EAAmB;AAChC,gBAAI,CAAC,wBAAW,OAAO,OAAP,CAAe,MAAf,EAAuB,KAAlC,CAAL,EAA+C;AAC3C,sBAAM,IAAI,KAAJ,CAAU,uCAAV,CAAN;AACH;;AAED,gBAAI,CAAC,yBAAY,OAAO,OAAP,CAAe,MAAf,EAAuB,QAAnC,CAAL,EAAmD;AAC/C,sBAAM,IAAI,KAAJ,CAAU,2CAAV,CAAN;AACH;;AAED,4BAAgB,MAAhB,IAA0B,mCAAoB,KAApB,EAA2B,OAAO,OAAP,CAAe,MAAf,EAAuB,KAAlD,EAAyD,OAAO,OAAP,CAAe,MAAf,EAAuB,QAAhF,CAA1B;AACH,SAVD;;AAYA,qBAAa,IAAb,CAAkB,mBAAM,eAAN,CAAlB;AACH,KAlBD;;AAoBA,WAAO,YAAP;AACH,C","file":"calculateRowHeightIndex.js","sourcesContent":["import _ from 'lodash';\nimport calculateCellHeight from './calculateCellHeight';\n\n/**\n * Calculates the vertical row span index.\n *\n * @param {Array[]} rows\n * @param {Object} config\n * @return {number[]}\n */\nexport default (rows, config) => {\n let rowSpanIndex,\n tableWidth;\n\n tableWidth = rows[0].length;\n\n rowSpanIndex = [];\n\n _.forEach(rows, (cells) => {\n let cellHeightIndex;\n\n cellHeightIndex = _.fill(Array(tableWidth), 1);\n\n _.forEach(cells, (value, index1) => {\n if (!_.isNumber(config.columns[index1].width)) {\n throw new Error('column[index].width must be a number.');\n }\n\n if (!_.isBoolean(config.columns[index1].wrapWord)) {\n throw new Error('column[index].wrapWord must be a boolean.');\n }\n\n cellHeightIndex[index1] = calculateCellHeight(value, config.columns[index1].width, config.columns[index1].wrapWord);\n });\n\n rowSpanIndex.push(_.max(cellHeightIndex));\n });\n\n return rowSpanIndex;\n};\n"]} \ No newline at end of file diff --git a/tools/eslint/node_modules/table/dist/createStream.js b/tools/eslint/node_modules/table/dist/createStream.js index 1175ec66538da7..f9c3df5035be45 100644 --- a/tools/eslint/node_modules/table/dist/createStream.js +++ b/tools/eslint/node_modules/table/dist/createStream.js @@ -123,7 +123,7 @@ const append = (row, columnWidthIndex, config) => { */ exports.default = function () { - let userConfig = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; + let userConfig = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; const config = (0, _makeStreamConfig2.default)(userConfig); diff --git a/tools/eslint/node_modules/table/dist/createStream.js.map b/tools/eslint/node_modules/table/dist/createStream.js.map deleted file mode 100644 index b3a2563cda052a..00000000000000 --- a/tools/eslint/node_modules/table/dist/createStream.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["createStream.js"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA;;;;AACA;;;;AACA;;AAOA;;;;AACA;;;;AACA;;;;AACA;;;;AACA;;;;AACA;;;;;;AAEA,IAAI,eAAJ;IACI,eADJ;IAEI,oBAFJ;;;;;;;;AAUA,SAAS,gBAAC,GAAD,EAAM,gBAAN,EAAwB,MAAxB,EAAmC;AACxC,QAAI,aAAJ;QACI,eADJ;QAEI,aAFJ;;AAIA,WAAO,YAAY,CAAC,GAAD,CAAZ,EAAmB,MAAnB,CAAP;;AAEA,WAAO,mBAAM,IAAN,EAAY,UAAC,UAAD,EAAgB;AAC/B,eAAO,uBAAQ,UAAR,EAAoB,OAAO,MAA3B,CAAP;AACH,KAFM,EAEJ,IAFI,CAEC,EAFD,CAAP;;AAIA,aAAS,EAAT;AACA,cAAU,+BAAc,gBAAd,EAAgC,OAAO,MAAvC,CAAV;AACA,cAAU,IAAV;AACA,cAAU,kCAAiB,gBAAjB,EAAmC,OAAO,MAA1C,CAAV;;AAEA,aAAS,uBAAU,MAAV,CAAT;;AAEA,YAAQ,MAAR,CAAe,KAAf,CAAqB,MAArB;AACH,CAnBD;;;;;;;;AA2BA,SAAS,gBAAC,GAAD,EAAM,gBAAN,EAAwB,MAAxB,EAAmC;AACxC,QAAI,aAAJ;QACI,eADJ;QAEI,aAFJ;;AAIA,WAAO,YAAY,CAAC,GAAD,CAAZ,EAAmB,MAAnB,CAAP;;;;AAIA,WAAO,mBAAM,IAAN,EAAY,UAAC,UAAD,EAAgB;AAC/B,eAAO,uBAAQ,UAAR,EAAoB,OAAO,MAA3B,CAAP;AACH,KAFM,EAEJ,IAFI,CAEC,EAFD,CAAP;;AAIA,aAAS,UAAT;AACA,cAAU,gCAAe,gBAAf,EAAiC,OAAO,MAAxC,CAAV;AACA,cAAU,IAAV;AACA,cAAU,kCAAiB,gBAAjB,EAAmC,OAAO,MAA1C,CAAV;;AAEA,aAAS,uBAAU,MAAV,CAAT;;AAEA,YAAQ,MAAR,CAAe,KAAf,CAAqB,MAArB;AACH,CArBD;;;;;;;AA4BA,cAAc,qBAAC,IAAD,EAAO,MAAP,EAAkB;AAC5B,QAAI,uBAAJ;QACI,aADJ;;AAGA,WAAO,kCAAmB,IAAnB,CAAP;;AAEA,WAAO,iCAAkB,IAAlB,EAAwB,MAAxB,CAAP;;AAEA,qBAAiB,uCAAwB,IAAxB,EAA8B,MAA9B,CAAjB;;AAEA,WAAO,0CAA2B,IAA3B,EAAiC,cAAjC,EAAiD,MAAjD,CAAP;AACA,WAAO,8BAAe,IAAf,EAAqB,MAArB,CAAP;AACA,WAAO,4BAAa,IAAb,EAAmB,MAAnB,CAAP;;AAEA,WAAO,IAAP;AACH,CAfD;;;;;;;kBAqBe,YAAqB;AAAA,QAApB,UAAoB,yDAAP,EAAO;;AAChC,QAAI,yBAAJ;QACI,eADJ;QAEI,cAFJ;;AAIA,aAAS,gCAAiB,UAAjB,CAAT;;AAEA,uBAAmB,yBAAY,OAAO,OAAnB,EAA4B,UAAC,MAAD,EAAY;AACvD,eAAO,OAAO,KAAP,GAAe,OAAO,WAAtB,GAAoC,OAAO,YAAlD;AACH,KAFkB,CAAnB;;AAIA,YAAQ,IAAR;;AAEA,WAAO;;;;;AAKH,eAAO,eAAC,GAAD,EAAS;AACZ,gBAAI,IAAI,MAAJ,KAAe,OAAO,WAA1B,EAAuC;AACnC,sBAAM,IAAI,KAAJ,CAAU,uDAAV,CAAN;AACH;;AAED,gBAAI,KAAJ,EAAW;AACP,wBAAQ,KAAR;;AAEA,uBAAO,OAAO,GAAP,EAAY,gBAAZ,EAA8B,MAA9B,CAAP;AACH,aAJD,MAIO;AACH,uBAAO,OAAO,GAAP,EAAY,gBAAZ,EAA8B,MAA9B,CAAP;AACH;AACJ;AAjBE,KAAP;AAmBH,C","file":"createStream.js","sourcesContent":["import makeStreamConfig from './makeStreamConfig';\nimport drawRow from './drawRow';\nimport {\n drawBorderBottom,\n drawBorderJoin,\n drawBorderTop\n} from './drawBorder';\nimport _ from 'lodash';\n\nimport stringifyTableData from './stringifyTableData';\nimport truncateTableData from './truncateTableData';\nimport mapDataUsingRowHeightIndex from './mapDataUsingRowHeightIndex';\nimport alignTableData from './alignTableData';\nimport padTableData from './padTableData';\nimport calculateRowHeightIndex from './calculateRowHeightIndex';\n\nlet append,\n create,\n prepareData;\n\n/**\n * @param {string[]} row\n * @param {number[]} columnWidthIndex\n * @param {Object} config\n * @returns {undefined}\n */\ncreate = (row, columnWidthIndex, config) => {\n let body,\n output,\n rows;\n\n rows = prepareData([row], config);\n\n body = _.map(rows, (literalRow) => {\n return drawRow(literalRow, config.border);\n }).join('');\n\n output = '';\n output += drawBorderTop(columnWidthIndex, config.border);\n output += body;\n output += drawBorderBottom(columnWidthIndex, config.border);\n\n output = _.trimEnd(output);\n\n process.stdout.write(output);\n};\n\n/**\n * @param {string[]} row\n * @param {number[]} columnWidthIndex\n * @param {Object} config\n * @returns {undefined}\n */\nappend = (row, columnWidthIndex, config) => {\n let body,\n output,\n rows;\n\n rows = prepareData([row], config);\n\n // console.log('rows', rows);\n\n body = _.map(rows, (literalRow) => {\n return drawRow(literalRow, config.border);\n }).join('');\n\n output = '\\r\\x1b[K';\n output += drawBorderJoin(columnWidthIndex, config.border);\n output += body;\n output += drawBorderBottom(columnWidthIndex, config.border);\n\n output = _.trimEnd(output);\n\n process.stdout.write(output);\n};\n\n/**\n * @param {Array} data\n * @param {Object} config\n * @returns {Array}\n */\nprepareData = (data, config) => {\n let rowHeightIndex,\n rows;\n\n rows = stringifyTableData(data);\n\n rows = truncateTableData(data, config);\n\n rowHeightIndex = calculateRowHeightIndex(rows, config);\n\n rows = mapDataUsingRowHeightIndex(rows, rowHeightIndex, config);\n rows = alignTableData(rows, config);\n rows = padTableData(rows, config);\n\n return rows;\n};\n\n/**\n * @param {Object} userConfig\n * @return {Object}\n */\nexport default (userConfig = {}) => {\n let columnWidthIndex,\n config,\n empty;\n\n config = makeStreamConfig(userConfig);\n\n columnWidthIndex = _.mapValues(config.columns, (column) => {\n return column.width + column.paddingLeft + column.paddingRight;\n });\n\n empty = true;\n\n return {\n /**\n * @param {string[]} row\n * @returns {undefined}\n */\n write: (row) => {\n if (row.length !== config.columnCount) {\n throw new Error('Row cell count does not match the config.columnCount.');\n }\n\n if (empty) {\n empty = false;\n\n return create(row, columnWidthIndex, config);\n } else {\n return append(row, columnWidthIndex, config);\n }\n }\n };\n};\n"]} \ No newline at end of file diff --git a/tools/eslint/node_modules/table/dist/drawBorder.js.map b/tools/eslint/node_modules/table/dist/drawBorder.js.map deleted file mode 100644 index adbf9d7403d2f9..00000000000000 --- a/tools/eslint/node_modules/table/dist/drawBorder.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["drawBorder.js"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAEA,IAAI,mBAAJ;IACI,yBADJ;IAEI,uBAFJ;IAGI,sBAHJ;;;;;;;;;;;;;;;AAkBA,QA+EI,UA/EJ,gBAAa,oBAAC,eAAD,EAAkB,KAAlB,EAA4B;AACrC,QAAI,gBAAJ;;AAEA,cAAU,mBAAM,eAAN,EAAuB,UAAC,IAAD,EAAU;AACvC,eAAO,sBAAS,MAAM,IAAf,EAAqB,IAArB,CAAP;AACH,KAFS,CAAV;;AAIA,cAAU,QAAQ,IAAR,CAAa,MAAM,IAAnB,CAAV;;AAEA,WAAO,MAAM,IAAN,GAAa,OAAb,GAAuB,MAAM,KAA7B,GAAqC,IAA5C;AACH,CAVD;;;;;;;;;;;;;;;AAyBA,QAuDI,aAvDJ,mBAAgB,uBAAC,eAAD,EAAkB,KAAlB,EAA4B;AACxC,WAAO,WAAW,eAAX,EAA4B;AAC/B,cAAM,MAAM,OADmB;AAE/B,eAAO,MAAM,QAFkB;AAG/B,cAAM,MAAM,OAHmB;AAI/B,cAAM,MAAM;AAJmB,KAA5B,CAAP;AAMH,CAPD;;;;;;;;;;;;;;;AAsBA,QAkCI,cAlCJ,oBAAiB,wBAAC,eAAD,EAAkB,KAAlB,EAA4B;AACzC,WAAO,WAAW,eAAX,EAA4B;AAC/B,cAAM,MAAM,QADmB;AAE/B,eAAO,MAAM,SAFkB;AAG/B,cAAM,MAAM,QAHmB;AAI/B,cAAM,MAAM;AAJmB,KAA5B,CAAP;AAMH,CAPD;;;;;;;;;;;;;;;AAsBA,QAaI,gBAbJ,sBAAmB,0BAAC,eAAD,EAAkB,KAAlB,EAA4B;AAC3C,WAAO,WAAW,eAAX,EAA4B;AAC/B,cAAM,MAAM,UADmB;AAE/B,eAAO,MAAM,WAFkB;AAG/B,cAAM,MAAM,UAHmB;AAI/B,cAAM,MAAM;AAJmB,KAA5B,CAAP;AAMH,CAPD;;QAUI,U,GAAA,U;QACA,a,GAAA,a;QACA,c,GAAA,c;QACA,gB,GAAA,gB","file":"drawBorder.js","sourcesContent":["import _ from 'lodash';\n\nlet drawBorder,\n drawBorderBottom,\n drawBorderJoin,\n drawBorderTop;\n\n/**\n * @typedef drawBorder~parts\n * @property {string} left\n * @property {string} right\n * @property {string} body\n * @property {string} join\n */\n\n/**\n * @param {number[]} columnSizeIndex\n * @param {drawBorder~parts} parts\n * @returns {string}\n */\ndrawBorder = (columnSizeIndex, parts) => {\n let columns;\n\n columns = _.map(columnSizeIndex, (size) => {\n return _.repeat(parts.body, size);\n });\n\n columns = columns.join(parts.join);\n\n return parts.left + columns + parts.right + '\\n';\n};\n\n/**\n * @typedef drawBorderTop~parts\n * @property {string} topLeft\n * @property {string} topRight\n * @property {string} topBody\n * @property {string} topJoin\n */\n\n/**\n * @param {number[]} columnSizeIndex\n * @param {drawBorderTop~parts} parts\n * @return {string}\n */\ndrawBorderTop = (columnSizeIndex, parts) => {\n return drawBorder(columnSizeIndex, {\n left: parts.topLeft,\n right: parts.topRight,\n body: parts.topBody,\n join: parts.topJoin\n });\n};\n\n/**\n * @typedef drawBorderJoin~parts\n * @property {string} joinLeft\n * @property {string} joinRight\n * @property {string} joinBody\n * @property {string} joinJoin\n */\n\n/**\n * @param {number[]} columnSizeIndex\n * @param {drawBorderJoin~parts} parts\n * @returns {string}\n */\ndrawBorderJoin = (columnSizeIndex, parts) => {\n return drawBorder(columnSizeIndex, {\n left: parts.joinLeft,\n right: parts.joinRight,\n body: parts.joinBody,\n join: parts.joinJoin\n });\n};\n\n/**\n * @typedef drawBorderBottom~parts\n * @property {string} topLeft\n * @property {string} topRight\n * @property {string} topBody\n * @property {string} topJoin\n */\n\n/**\n * @param {number[]} columnSizeIndex\n * @param {drawBorderBottom~parts} parts\n * @returns {string}\n */\ndrawBorderBottom = (columnSizeIndex, parts) => {\n return drawBorder(columnSizeIndex, {\n left: parts.bottomLeft,\n right: parts.bottomRight,\n body: parts.bottomBody,\n join: parts.bottomJoin\n });\n};\n\nexport {\n drawBorder,\n drawBorderTop,\n drawBorderJoin,\n drawBorderBottom\n};\n"]} \ No newline at end of file diff --git a/tools/eslint/node_modules/table/dist/drawRow.js.map b/tools/eslint/node_modules/table/dist/drawRow.js.map deleted file mode 100644 index 5cef8565f4cc23..00000000000000 --- a/tools/eslint/node_modules/table/dist/drawRow.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["drawRow.js"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;kBAYe,UAAC,OAAD,EAAU,MAAV,EAAqB;AAChC,SAAO,OAAO,QAAP,GAAkB,QAAQ,IAAR,CAAa,OAAO,QAApB,CAAlB,GAAkD,OAAO,SAAzD,GAAqE,IAA5E;AACH,C","file":"drawRow.js","sourcesContent":["/**\n * @typedef {Object} drawRow~border\n * @property {string} bodyLeft\n * @property {string} bodyRight\n * @property {string} bodyJoin\n */\n\n/**\n * @param {number[]} columns\n * @param {drawRow~border} border\n * @return {string}\n */\nexport default (columns, border) => {\n return border.bodyLeft + columns.join(border.bodyJoin) + border.bodyRight + '\\n';\n};\n"]} \ No newline at end of file diff --git a/tools/eslint/node_modules/table/dist/drawTable.js.map b/tools/eslint/node_modules/table/dist/drawTable.js.map deleted file mode 100644 index 8534c44da3fad4..00000000000000 --- a/tools/eslint/node_modules/table/dist/drawTable.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["drawTable.js"],"names":[],"mappings":";;;;;;;;;;AACA;;AAKA;;;;;;;;;;;;;;;kBAUe,UAAC,IAAD,EAAO,MAAP,EAAe,eAAf,EAAgC,YAAhC,EAA8C,kBAA9C,EAAqE;AAChF,QAAI,eAAJ;QACI,qBADJ;QAEI,iBAFJ;QAGI,kBAHJ;;AAKA,eAAW,KAAK,MAAhB;;AAEA,mBAAe,CAAf;;AAEA,aAAS,EAAT;;AAEA,QAAI,mBAAmB,YAAnB,EAAiC,QAAjC,CAAJ,EAAgD;AAC5C,kBAAU,+BAAc,eAAd,EAA+B,MAA/B,CAAV;AACH;;AAED,2BAAU,IAAV,EAAgB,UAAC,GAAD,EAAM,MAAN,EAAiB;AAC7B,kBAAU,uBAAQ,GAAR,EAAa,MAAb,CAAV;;AAEA,YAAI,CAAC,SAAL,EAAgB;AACZ,wBAAY,aAAa,YAAb,CAAZ;;AAEA;AACH;;AAED;;AAEA,YAAI,cAAc,CAAd,IAAmB,WAAW,WAAW,CAAzC,IAA8C,mBAAmB,YAAnB,EAAiC,QAAjC,CAAlD,EAA8F;AAC1F,sBAAU,gCAAe,eAAf,EAAgC,MAAhC,CAAV;AACH;AACJ,KAdD;;AAgBA,QAAI,mBAAmB,YAAnB,EAAiC,QAAjC,CAAJ,EAAgD;AAC5C,kBAAU,kCAAiB,eAAjB,EAAkC,MAAlC,CAAV;AACH;;AAED,WAAO,MAAP;AACH,C","file":"drawTable.js","sourcesContent":["import _ from 'lodash';\nimport {\n drawBorderTop,\n drawBorderJoin,\n drawBorderBottom\n} from './drawBorder';\nimport drawRow from './drawRow';\n\n/**\n * @param {Array} rows\n * @param {Object} border\n * @param {Array} columnSizeIndex\n * @param {Array} rowSpanIndex\n * @param {Function} drawHorizontalLine\n * @returns {string}\n */\nexport default (rows, border, columnSizeIndex, rowSpanIndex, drawHorizontalLine) => {\n let output,\n realRowIndex,\n rowCount,\n rowHeight;\n\n rowCount = rows.length;\n\n realRowIndex = 0;\n\n output = '';\n\n if (drawHorizontalLine(realRowIndex, rowCount)) {\n output += drawBorderTop(columnSizeIndex, border);\n }\n\n _.forEach(rows, (row, index0) => {\n output += drawRow(row, border);\n\n if (!rowHeight) {\n rowHeight = rowSpanIndex[realRowIndex];\n\n realRowIndex++;\n }\n\n rowHeight--;\n\n if (rowHeight === 0 && index0 !== rowCount - 1 && drawHorizontalLine(realRowIndex, rowCount)) {\n output += drawBorderJoin(columnSizeIndex, border);\n }\n });\n\n if (drawHorizontalLine(realRowIndex, rowCount)) {\n output += drawBorderBottom(columnSizeIndex, border);\n }\n\n return output;\n};\n"]} \ No newline at end of file diff --git a/tools/eslint/node_modules/table/dist/getBorderCharacters.js.map b/tools/eslint/node_modules/table/dist/getBorderCharacters.js.map deleted file mode 100644 index 36ba03bf8c00e4..00000000000000 --- a/tools/eslint/node_modules/table/dist/getBorderCharacters.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["getBorderCharacters.js"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBAyBe,UAAC,IAAD,EAAU;AACrB,QAAI,SAAS,WAAb,EAA0B;AACtB,eAAO;AACH,qBAAS,GADN;AAEH,qBAAS,GAFN;AAGH,qBAAS,GAHN;AAIH,sBAAU,GAJP;;AAMH,wBAAY,GANT;AAOH,wBAAY,GAPT;AAQH,wBAAY,GART;AASH,yBAAa,GATV;;AAWH,sBAAU,GAXP;AAYH,uBAAW,GAZR;AAaH,sBAAU,GAbP;;AAeH,sBAAU,GAfP;AAgBH,sBAAU,GAhBP;AAiBH,uBAAW,GAjBR;AAkBH,sBAAU;AAlBP,SAAP;AAoBH;;AAED,QAAI,SAAS,MAAb,EAAqB;AACjB,eAAO;AACH,qBAAS,GADN;AAEH,qBAAS,GAFN;AAGH,qBAAS,GAHN;AAIH,sBAAU,GAJP;;AAMH,wBAAY,GANT;AAOH,wBAAY,GAPT;AAQH,wBAAY,GART;AASH,yBAAa,GATV;;AAWH,sBAAU,GAXP;AAYH,uBAAW,GAZR;AAaH,sBAAU,GAbP;;AAeH,sBAAU,GAfP;AAgBH,sBAAU,GAhBP;AAiBH,uBAAW,GAjBR;AAkBH,sBAAU;AAlBP,SAAP;AAoBH;;AAED,QAAI,SAAS,OAAb,EAAsB;AAClB,eAAO;AACH,qBAAS,GADN;AAEH,qBAAS,GAFN;AAGH,qBAAS,GAHN;AAIH,sBAAU,GAJP;;AAMH,wBAAY,GANT;AAOH,wBAAY,GAPT;AAQH,wBAAY,GART;AASH,yBAAa,GATV;;AAWH,sBAAU,GAXP;AAYH,uBAAW,GAZR;AAaH,sBAAU,GAbP;;AAeH,sBAAU,GAfP;AAgBH,sBAAU,GAhBP;AAiBH,uBAAW,GAjBR;AAkBH,sBAAU;AAlBP,SAAP;AAoBH;;AAED,QAAI,SAAS,MAAb,EAAqB;AACjB,eAAO;AACH,qBAAS,EADN;AAEH,qBAAS,EAFN;AAGH,qBAAS,EAHN;AAIH,sBAAU,EAJP;;AAMH,wBAAY,EANT;AAOH,wBAAY,EAPT;AAQH,wBAAY,EART;AASH,yBAAa,EATV;;AAWH,sBAAU,EAXP;AAYH,uBAAW,EAZR;AAaH,sBAAU,EAbP;;AAeH,sBAAU,EAfP;AAgBH,sBAAU,EAhBP;AAiBH,uBAAW,EAjBR;AAkBH,sBAAU;AAlBP,SAAP;AAoBH;;AAED,UAAM,IAAI,KAAJ,CAAU,oCAAV,CAAN;AACH,C","file":"getBorderCharacters.js","sourcesContent":["/* eslint-disable sorting/sort-object-props */\n\n/**\n * @typedef border\n * @property {string} topBody\n * @property {string} topJoin\n * @property {string} topLeft\n * @property {string} topRight\n * @property {string} bottomBody\n * @property {string} bottomJoin\n * @property {string} bottomLeft\n * @property {string} bottomRight\n * @property {string} bodyLeft\n * @property {string} bodyRight\n * @property {string} bodyJoin\n * @property {string} joinBody\n * @property {string} joinLeft\n * @property {string} joinRight\n * @property {string} joinJoin\n */\n\n/**\n * @param {string} name\n * @returns {border}\n */\nexport default (name) => {\n if (name === 'honeywell') {\n return {\n topBody: '═',\n topJoin: '╤',\n topLeft: '╔',\n topRight: '╗',\n\n bottomBody: '═',\n bottomJoin: '╧',\n bottomLeft: '╚',\n bottomRight: '╝',\n\n bodyLeft: '║',\n bodyRight: '║',\n bodyJoin: '│',\n\n joinBody: '─',\n joinLeft: '╟',\n joinRight: '╢',\n joinJoin: '┼'\n };\n }\n\n if (name === 'norc') {\n return {\n topBody: '─',\n topJoin: '┬',\n topLeft: '┌',\n topRight: '┐',\n\n bottomBody: '─',\n bottomJoin: '┴',\n bottomLeft: '└',\n bottomRight: '┘',\n\n bodyLeft: '│',\n bodyRight: '│',\n bodyJoin: '│',\n\n joinBody: '─',\n joinLeft: '├',\n joinRight: '┤',\n joinJoin: '┼'\n };\n }\n\n if (name === 'ramac') {\n return {\n topBody: '-',\n topJoin: '+',\n topLeft: '+',\n topRight: '+',\n\n bottomBody: '-',\n bottomJoin: '+',\n bottomLeft: '+',\n bottomRight: '+',\n\n bodyLeft: '|',\n bodyRight: '|',\n bodyJoin: '|',\n\n joinBody: '-',\n joinLeft: '|',\n joinRight: '|',\n joinJoin: '|'\n };\n }\n\n if (name === 'void') {\n return {\n topBody: '',\n topJoin: '',\n topLeft: '',\n topRight: '',\n\n bottomBody: '',\n bottomJoin: '',\n bottomLeft: '',\n bottomRight: '',\n\n bodyLeft: '',\n bodyRight: '',\n bodyJoin: '',\n\n joinBody: '',\n joinLeft: '',\n joinRight: '',\n joinJoin: ''\n };\n }\n\n throw new Error('Unknown border template \"${name}\".');\n};\n"]} \ No newline at end of file diff --git a/tools/eslint/node_modules/table/dist/index.js.map b/tools/eslint/node_modules/table/dist/index.js.map deleted file mode 100644 index dcf5ef8d344cad..00000000000000 --- a/tools/eslint/node_modules/table/dist/index.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["index.js"],"names":[],"mappings":";;;;;;;AAAA;;;;AACA;;;;AACA;;;;;;QAGI,Y;QACA,mB","file":"index.js","sourcesContent":["import table from './table';\nimport createStream from './createStream';\nimport getBorderCharacters from './getBorderCharacters';\n\nexport {\n createStream,\n getBorderCharacters\n};\n\nexport default table;\n"]} \ No newline at end of file diff --git a/tools/eslint/node_modules/table/dist/makeConfig.js b/tools/eslint/node_modules/table/dist/makeConfig.js index 830ece67ef10ff..45ad8e899ce4be 100644 --- a/tools/eslint/node_modules/table/dist/makeConfig.js +++ b/tools/eslint/node_modules/table/dist/makeConfig.js @@ -29,7 +29,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * @returns {Object} */ const makeBorder = function makeBorder() { - let border = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; + let border = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; return _lodash2.default.assign({}, (0, _getBorderCharacters2.default)('honeywell'), border); }; @@ -44,8 +44,8 @@ const makeBorder = function makeBorder() { * @returns {Object} */ const makeColumns = function makeColumns(rows) { - let columns = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; - let columnDefault = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; + let columns = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + let columnDefault = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; const maximumColumnWidthIndex = (0, _calculateMaximumColumnWidthIndex2.default)(rows); @@ -77,7 +77,7 @@ const makeColumns = function makeColumns(rows) { */ exports.default = function (rows) { - let userConfig = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; + let userConfig = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; (0, _validateConfig2.default)('config.json', userConfig); diff --git a/tools/eslint/node_modules/table/dist/makeConfig.js.map b/tools/eslint/node_modules/table/dist/makeConfig.js.map deleted file mode 100644 index 25c7051d2758e4..00000000000000 --- a/tools/eslint/node_modules/table/dist/makeConfig.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["makeConfig.js"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;AACA;;;;AACA;;;;AACA;;;;;;AAEA,IAAI,mBAAJ;IACI,oBADJ;;;;;;;;AASA,aAAa,sBAAiB;AAAA,QAAhB,MAAgB,yDAAP,EAAO;;AAC1B,WAAO,sBAAS,EAAT,EAAa,mCAAoB,WAApB,CAAb,EAA+C,MAA/C,CAAP;AACH,CAFD;;;;;;;;;;;AAaA,cAAc,qBAAC,IAAD,EAA4C;AAAA,QAArC,OAAqC,yDAA3B,EAA2B;AAAA,QAAvB,aAAuB,yDAAP,EAAO;;AACtD,QAAI,gCAAJ;;AAEA,8BAA0B,gDAAiC,IAAjC,CAA1B;;AAEA,yBAAQ,KAAK,CAAL,EAAQ,MAAhB,EAAwB,UAAC,KAAD,EAAW;AAC/B,YAAI,2BAAc,QAAQ,KAAR,CAAd,CAAJ,EAAmC;AAC/B,oBAAQ,KAAR,IAAiB,EAAjB;AACH;;AAED,gBAAQ,KAAR,IAAiB,sBAAS;AACtB,uBAAW,MADW;AAEtB,mBAAO,wBAAwB,KAAxB,CAFe;AAGtB,sBAAU,KAHY;AAItB,sBAAU,QAJY;AAKtB,yBAAa,CALS;AAMtB,0BAAc;AANQ,SAAT,EAOd,aAPc,EAOC,QAAQ,KAAR,CAPD,CAAjB;AAQH,KAbD;;AAeA,WAAO,OAAP;AACH,CArBD;;;;;;;;;;;kBA+Be,UAAC,IAAD,EAA2B;AAAA,QAApB,UAAoB,yDAAP,EAAO;;AACtC,QAAI,eAAJ;;AAEA,kCAAe,UAAf;;AAEA,aAAS,yBAAY,UAAZ,CAAT;;AAEA,WAAO,MAAP,GAAgB,WAAW,OAAO,MAAlB,CAAhB;AACA,WAAO,OAAP,GAAiB,YAAY,IAAZ,EAAkB,OAAO,OAAzB,EAAkC,OAAO,aAAzC,CAAjB;;AAEA,QAAI,CAAC,OAAO,kBAAZ,EAAgC;;;;AAI5B,eAAO,kBAAP,GAA4B,YAAM;AAC9B,mBAAO,IAAP;AACH,SAFD;AAGH;;AAED,WAAO,MAAP;AACH,C","file":"makeConfig.js","sourcesContent":["import _ from 'lodash';\nimport getBorderCharacters from './getBorderCharacters';\nimport validateConfig from './validateConfig';\nimport calculateMaximumColumnWidthIndex from './calculateMaximumColumnWidthIndex';\n\nlet makeBorder,\n makeColumns;\n\n/**\n * Merges user provided border characters with the default border (\"honeywell\") characters.\n *\n * @param {Object} border\n * @returns {Object}\n */\nmakeBorder = (border = {}) => {\n return _.assign({}, getBorderCharacters('honeywell'), border);\n};\n\n/**\n * Creates a configuration for every column using default\n * values for the missing configuration properties.\n *\n * @param {Array[]} rows\n * @param {Object} columns\n * @param {Object} columnDefault\n * @returns {Object}\n */\nmakeColumns = (rows, columns = {}, columnDefault = {}) => {\n let maximumColumnWidthIndex;\n\n maximumColumnWidthIndex = calculateMaximumColumnWidthIndex(rows);\n\n _.times(rows[0].length, (index) => {\n if (_.isUndefined(columns[index])) {\n columns[index] = {};\n }\n\n columns[index] = _.assign({\n alignment: 'left',\n width: maximumColumnWidthIndex[index],\n wrapWord: false,\n truncate: Infinity,\n paddingLeft: 1,\n paddingRight: 1\n }, columnDefault, columns[index]);\n });\n\n return columns;\n};\n\n/**\n * Makes a new configuration object out of the userConfig object\n * using default values for the missing configuration properties.\n *\n * @param {Array[]} rows\n * @param {Object} userConfig\n * @returns {Object}\n */\nexport default (rows, userConfig = {}) => {\n let config;\n\n validateConfig(userConfig);\n\n config = _.cloneDeep(userConfig);\n\n config.border = makeBorder(config.border);\n config.columns = makeColumns(rows, config.columns, config.columnDefault);\n\n if (!config.drawHorizontalLine) {\n /**\n * @returns {boolean}\n */\n config.drawHorizontalLine = () => {\n return true;\n };\n }\n\n return config;\n};\n"]} \ No newline at end of file diff --git a/tools/eslint/node_modules/table/dist/makeStreamConfig.js b/tools/eslint/node_modules/table/dist/makeStreamConfig.js index 06e212adbfe498..1482dae079ec0d 100644 --- a/tools/eslint/node_modules/table/dist/makeStreamConfig.js +++ b/tools/eslint/node_modules/table/dist/makeStreamConfig.js @@ -25,7 +25,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * @returns {Object} */ const makeBorder = function makeBorder() { - let border = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; + let border = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; return _lodash2.default.assign({}, (0, _getBorderCharacters2.default)('honeywell'), border); }; @@ -40,8 +40,8 @@ const makeBorder = function makeBorder() { * @returns {Object} */ const makeColumns = function makeColumns(columnCount) { - let columns = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; - let columnDefault = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; + let columns = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + let columnDefault = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; _lodash2.default.times(columnCount, index => { if (_lodash2.default.isUndefined(columns[index])) { @@ -86,7 +86,7 @@ const makeColumns = function makeColumns(columnCount) { */ exports.default = function () { - let userConfig = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; + let userConfig = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; (0, _validateConfig2.default)('streamConfig.json', userConfig); diff --git a/tools/eslint/node_modules/table/dist/makeStreamConfig.js.map b/tools/eslint/node_modules/table/dist/makeStreamConfig.js.map deleted file mode 100644 index c3c0437ec1e42a..00000000000000 --- a/tools/eslint/node_modules/table/dist/makeStreamConfig.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["makeStreamConfig.js"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;AACA;;;;AACA;;;;;;AAEA,IAAI,mBAAJ;IACI,oBADJ;;;;;;;;AASA,aAAa,sBAAiB;AAAA,QAAhB,MAAgB,yDAAP,EAAO;;AAC1B,WAAO,sBAAS,EAAT,EAAa,mCAAoB,WAApB,CAAb,EAA+C,MAA/C,CAAP;AACH,CAFD;;;;;;;;;;;AAaA,cAAc,qBAAC,WAAD,EAAmD;AAAA,QAArC,OAAqC,yDAA3B,EAA2B;AAAA,QAAvB,aAAuB,yDAAP,EAAO;;AAC7D,yBAAQ,WAAR,EAAqB,UAAC,KAAD,EAAW;AAC5B,YAAI,2BAAc,QAAQ,KAAR,CAAd,CAAJ,EAAmC;AAC/B,oBAAQ,KAAR,IAAiB,EAAjB;AACH;;AAED,gBAAQ,KAAR,IAAiB,sBAAS;AACtB,uBAAW,MADW;;AAGtB,sBAAU,KAHY;AAItB,sBAAU,QAJY;AAKtB,yBAAa,CALS;AAMtB,0BAAc;AANQ,SAAT,EAOd,aAPc,EAOC,QAAQ,KAAR,CAPD,CAAjB;AAQH,KAbD;;AAeA,WAAO,OAAP;AACH,CAjBD;;;;;;;;;;;;;;;;;;;;;;;;;;;kBA2Ce,YAAqB;AAAA,QAApB,UAAoB,yDAAP,EAAO;;AAChC,QAAI,eAAJ;;AAEA,wCAAqB,UAArB;;AAEA,aAAS,yBAAY,UAAZ,CAAT;;AAEA,QAAI,CAAC,OAAO,aAAR,IAAyB,CAAC,OAAO,aAAP,CAAqB,KAAnD,EAA0D;AACtD,cAAM,IAAI,KAAJ,CAAU,iEAAV,CAAN;AACH;;AAED,QAAI,CAAC,OAAO,WAAZ,EAAyB;AACrB,cAAM,IAAI,KAAJ,CAAU,kCAAV,CAAN;AACH;;AAED,WAAO,MAAP,GAAgB,WAAW,OAAO,MAAlB,CAAhB;AACA,WAAO,OAAP,GAAiB,YAAY,OAAO,WAAnB,EAAgC,OAAO,OAAvC,EAAgD,OAAO,aAAvD,CAAjB;;AAEA,WAAO,MAAP;AACH,C","file":"makeStreamConfig.js","sourcesContent":["import _ from 'lodash';\nimport getBorderCharacters from './getBorderCharacters';\nimport validateStreamConfig from './validateStreamConfig';\n\nlet makeBorder,\n makeColumns;\n\n/**\n * Merges user provided border characters with the default border (\"honeywell\") characters.\n *\n * @param {Object} border\n * @returns {Object}\n */\nmakeBorder = (border = {}) => {\n return _.assign({}, getBorderCharacters('honeywell'), border);\n};\n\n/**\n * Creates a configuration for every column using default\n * values for the missing configuration properties.\n *\n * @param {number} columnCount\n * @param {Object} columns\n * @param {Object} columnDefault\n * @returns {Object}\n */\nmakeColumns = (columnCount, columns = {}, columnDefault = {}) => {\n _.times(columnCount, (index) => {\n if (_.isUndefined(columns[index])) {\n columns[index] = {};\n }\n\n columns[index] = _.assign({\n alignment: 'left',\n // width: columnDefault.width,\n wrapWord: false,\n truncate: Infinity,\n paddingLeft: 1,\n paddingRight: 1\n }, columnDefault, columns[index]);\n });\n\n return columns;\n};\n\n/**\n * @typedef {Object} columnConfig\n * @property {string} alignment\n * @property {number} width\n * @property {number} truncate\n * @property {number} paddingLeft\n * @property {number} paddingRight\n */\n\n/**\n * @typedef {Object} streamConfig\n * @property {columnConfig} columnDefault\n * @property {Object} border\n * @property {columnConfig[]}\n * @property {number} columnCount Number of columns in the table (required).\n */\n\n/**\n * Makes a new configuration object out of the userConfig object\n * using default values for the missing configuration properties.\n *\n * @param {streamConfig} userConfig\n * @returns {Object}\n */\nexport default (userConfig = {}) => {\n let config;\n\n validateStreamConfig(userConfig);\n\n config = _.cloneDeep(userConfig);\n\n if (!config.columnDefault || !config.columnDefault.width) {\n throw new Error('Must provide config.columnDefault.width when creating a stream.');\n }\n\n if (!config.columnCount) {\n throw new Error('Must provide config.columnCount.');\n }\n\n config.border = makeBorder(config.border);\n config.columns = makeColumns(config.columnCount, config.columns, config.columnDefault);\n\n return config;\n};\n"]} \ No newline at end of file diff --git a/tools/eslint/node_modules/table/dist/mapDataUsingRowHeightIndex.js.map b/tools/eslint/node_modules/table/dist/mapDataUsingRowHeightIndex.js.map deleted file mode 100644 index 4b11dec7deceb3..00000000000000 --- a/tools/eslint/node_modules/table/dist/mapDataUsingRowHeightIndex.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["mapDataUsingRowHeightIndex.js"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;AACA;;;;AACA;;;;;;;;;;;;;kBAQe,UAAC,YAAD,EAAe,cAAf,EAA+B,MAA/B,EAA0C;AACrD,QAAI,mBAAJ;QACI,mBADJ;;AAGA,iBAAa,aAAa,CAAb,EAAgB,MAA7B;;;;AAIA,iBAAa,mBAAM,YAAN,EAAoB,UAAC,KAAD,EAAQ,MAAR,EAAmB;AAChD,YAAI,kBAAJ;;AAEA,oBAAY,mBAAM,MAAM,eAAe,MAAf,CAAN,CAAN,EAAqC,YAAM;AACnD,mBAAO,oBAAO,MAAM,UAAN,CAAP,EAA0B,EAA1B,CAAP;AACH,SAFW,CAAZ;;;;;;;;AAUA,+BAAU,KAAV,EAAiB,UAAC,KAAD,EAAQ,MAAR,EAAmB;AAChC,gBAAI,qBAAJ;;AAEA,gBAAI,OAAO,OAAP,CAAe,MAAf,EAAuB,QAA3B,EAAqC;AACjC,+BAAe,wBAAS,KAAT,EAAgB,OAAO,OAAP,CAAe,MAAf,EAAuB,KAAvC,CAAf;AACH,aAFD,MAEO;AACH,+BAAe,0BAAW,KAAX,EAAkB,OAAO,OAAP,CAAe,MAAf,EAAuB,KAAzC,CAAf;AACH;;;;AAID,mCAAU,YAAV,EAAwB,UAAC,IAAD,EAAO,MAAP,EAAkB;;;AAGtC,0BAAU,MAAV,EAAkB,MAAlB,IAA4B,IAA5B;AACH,aAJD;AAKH,SAhBD;;AAkBA,eAAO,SAAP;AACH,KAhCY,CAAb;;AAkCA,WAAO,uBAAU,UAAV,CAAP;AACH,C","file":"mapDataUsingRowHeightIndex.js","sourcesContent":["import _ from 'lodash';\nimport wrapString from './wrapString';\nimport wrapWord from './wrapWord';\n\n/**\n * @param {Array} unmappedRows\n * @param {number[]} rowHeightIndex\n * @param {Object} config\n * @return {Array}\n */\nexport default (unmappedRows, rowHeightIndex, config) => {\n let mappedRows,\n tableWidth;\n\n tableWidth = unmappedRows[0].length;\n\n // console.log('unmappedRows', unmappedRows, 'rowHeightIndex', rowHeightIndex, 'config', config, 'tableWidth', tableWidth);\n\n mappedRows = _.map(unmappedRows, (cells, index0) => {\n let rowHeight;\n\n rowHeight = _.map(Array(rowHeightIndex[index0]), () => {\n return _.fill(Array(tableWidth), '');\n });\n\n // console.log('rowHeight', rowHeight);\n\n // rowHeight\n // [{row index within rowSaw; index2}]\n // [{cell index within a virtual row; index1}]\n\n _.forEach(cells, (value, index1) => {\n let chunkedValue;\n\n if (config.columns[index1].wrapWord) {\n chunkedValue = wrapWord(value, config.columns[index1].width);\n } else {\n chunkedValue = wrapString(value, config.columns[index1].width);\n }\n\n // console.log('chunkedValue', chunkedValue.length, 'rowHeight', rowHeight.length);\n\n _.forEach(chunkedValue, (part, index2) => {\n // console.log(rowHeight[index2]);\n\n rowHeight[index2][index1] = part;\n });\n });\n\n return rowHeight;\n });\n\n return _.flatten(mappedRows);\n};\n"]} \ No newline at end of file diff --git a/tools/eslint/node_modules/table/dist/padTableData.js.map b/tools/eslint/node_modules/table/dist/padTableData.js.map deleted file mode 100644 index e900566a567aa3..00000000000000 --- a/tools/eslint/node_modules/table/dist/padTableData.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["padTableData.js"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;kBAOe,UAAC,IAAD,EAAO,MAAP,EAAkB;AAC7B,WAAO,mBAAM,IAAN,EAAY,UAAC,KAAD,EAAW;AAC1B,eAAO,mBAAM,KAAN,EAAa,UAAC,KAAD,EAAQ,MAAR,EAAmB;AACnC,gBAAI,eAAJ;;AAEA,qBAAS,OAAO,OAAP,CAAe,MAAf,CAAT;;AAEA,mBAAO,sBAAS,GAAT,EAAc,OAAO,WAArB,IAAoC,KAApC,GAA4C,sBAAS,GAAT,EAAc,OAAO,YAArB,CAAnD;AACH,SANM,CAAP;AAOH,KARM,CAAP;AASH,C","file":"padTableData.js","sourcesContent":["import _ from 'lodash';\n\n/**\n * @param {table~row[]} rows\n * @param {Object} config\n * @return {table~row[]}\n */\nexport default (rows, config) => {\n return _.map(rows, (cells) => {\n return _.map(cells, (value, index1) => {\n let column;\n\n column = config.columns[index1];\n\n return _.repeat(' ', column.paddingLeft) + value + _.repeat(' ', column.paddingRight);\n });\n });\n};\n"]} \ No newline at end of file diff --git a/tools/eslint/node_modules/table/dist/stringifyTableData.js.map b/tools/eslint/node_modules/table/dist/stringifyTableData.js.map deleted file mode 100644 index c38e20fa838218..00000000000000 --- a/tools/eslint/node_modules/table/dist/stringifyTableData.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["stringifyTableData.js"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;kBAQe,UAAC,IAAD,EAAU;AACrB,WAAO,mBAAM,IAAN,EAAY,UAAC,KAAD,EAAW;AAC1B,eAAO,mBAAM,KAAN,EAAa,MAAb,CAAP;AACH,KAFM,CAAP;AAGH,C","file":"stringifyTableData.js","sourcesContent":["import _ from 'lodash';\n\n/**\n * Casts all cell values to a string.\n *\n * @param {table~row[]} rows\n * @return {table~row[]}\n */\nexport default (rows) => {\n return _.map(rows, (cells) => {\n return _.map(cells, String);\n });\n};\n"]} \ No newline at end of file diff --git a/tools/eslint/node_modules/table/dist/table.js b/tools/eslint/node_modules/table/dist/table.js index 9066efaee82854..b62ffd2b747c8f 100644 --- a/tools/eslint/node_modules/table/dist/table.js +++ b/tools/eslint/node_modules/table/dist/table.js @@ -109,7 +109,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * @returns {string} */ exports.default = function (data) { - let userConfig = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; + let userConfig = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; let rows; diff --git a/tools/eslint/node_modules/table/dist/table.js.map b/tools/eslint/node_modules/table/dist/table.js.map deleted file mode 100644 index 843d2e105c9f17..00000000000000 --- a/tools/eslint/node_modules/table/dist/table.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["table.js"],"names":[],"mappings":";;;;;;AAAA;;;;AACA;;;;AACA;;;;AACA;;;;AACA;;;;AACA;;;;AACA;;;;AACA;;;;AACA;;;;AACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBAgEe,UAAC,IAAD,EAA2B;AAAA,MAApB,UAAoB,yDAAP,EAAO;;AACtC,MAAI,uBAAJ;MACI,eADJ;MAEI,uBAFJ;MAGI,aAHJ;;AAKA,mCAAkB,IAAlB;;AAEA,SAAO,kCAAmB,IAAnB,CAAP;;AAEA,WAAS,0BAAW,IAAX,EAAiB,UAAjB,CAAT;;AAEA,SAAO,iCAAkB,IAAlB,EAAwB,MAAxB,CAAP;;AAEA,mBAAiB,uCAAwB,IAAxB,EAA8B,MAA9B,CAAjB;;AAEA,SAAO,0CAA2B,IAA3B,EAAiC,cAAjC,EAAiD,MAAjD,CAAP;AACA,SAAO,8BAAe,IAAf,EAAqB,MAArB,CAAP;AACA,SAAO,4BAAa,IAAb,EAAmB,MAAnB,CAAP;;AAEA,mBAAiB,uCAAwB,KAAK,CAAL,CAAxB,CAAjB;;AAEA,SAAO,yBAAU,IAAV,EAAgB,OAAO,MAAvB,EAA+B,cAA/B,EAA+C,cAA/C,EAA+D,OAAO,kBAAtE,CAAP;AACH,C","file":"table.js","sourcesContent":["import drawTable from './drawTable';\nimport calculateCellWidthIndex from './calculateCellWidthIndex';\nimport makeConfig from './makeConfig';\nimport calculateRowHeightIndex from './calculateRowHeightIndex';\nimport mapDataUsingRowHeightIndex from './mapDataUsingRowHeightIndex';\nimport alignTableData from './alignTableData';\nimport padTableData from './padTableData';\nimport validateTableData from './validateTableData';\nimport stringifyTableData from './stringifyTableData';\nimport truncateTableData from './truncateTableData';\n\n/**\n * @typedef {string} table~cell\n */\n\n/**\n * @typedef {table~cell[]} table~row\n */\n\n/**\n * @typedef {Object} table~columns\n * @property {string} alignment Cell content alignment (enum: left, center, right) (default: left).\n * @property {number} width Column width (default: auto).\n * @property {number} truncate Number of characters are which the content will be truncated (default: Infinity).\n * @property {number} paddingLeft Cell content padding width left (default: 1).\n * @property {number} paddingRight Cell content padding width right (default: 1).\n */\n\n/**\n * @typedef {Object} table~border\n * @property {string} topBody\n * @property {string} topJoin\n * @property {string} topLeft\n * @property {string} topRight\n * @property {string} bottomBody\n * @property {string} bottomJoin\n * @property {string} bottomLeft\n * @property {string} bottomRight\n * @property {string} bodyLeft\n * @property {string} bodyRight\n * @property {string} bodyJoin\n * @property {string} joinBody\n * @property {string} joinLeft\n * @property {string} joinRight\n * @property {string} joinJoin\n */\n\n/**\n * Used to tell whether to draw a horizontal line.\n * This callback is called for each non-content line of the table.\n * The default behavior is to always return true.\n *\n * @typedef {Function} drawHorizontalLine\n * @param {number} index\n * @param {number} size\n * @return {boolean}\n */\n\n/**\n * @typedef {Object} table~config\n * @property {table~border} border\n * @property {table~columns[]} columns Column specific configuration.\n * @property {table~columns} columnDefault Default values for all columns. Column specific settings overwrite the default values.\n * @property {table~drawHorizontalLine} drawHorizontalLine\n */\n\n/**\n * Generates a text table.\n *\n * @param {table~row[]} data\n * @param {table~config} userConfig\n * @return {string}\n */\nexport default (data, userConfig = {}) => {\n let cellWidthIndex,\n config,\n rowHeightIndex,\n rows;\n\n validateTableData(data);\n\n rows = stringifyTableData(data);\n\n config = makeConfig(rows, userConfig);\n\n rows = truncateTableData(data, config);\n\n rowHeightIndex = calculateRowHeightIndex(rows, config);\n\n rows = mapDataUsingRowHeightIndex(rows, rowHeightIndex, config);\n rows = alignTableData(rows, config);\n rows = padTableData(rows, config);\n\n cellWidthIndex = calculateCellWidthIndex(rows[0]);\n\n return drawTable(rows, config.border, cellWidthIndex, rowHeightIndex, config.drawHorizontalLine);\n};\n"]} \ No newline at end of file diff --git a/tools/eslint/node_modules/table/dist/truncateTableData.js.map b/tools/eslint/node_modules/table/dist/truncateTableData.js.map deleted file mode 100644 index dca05c3b51cdce..00000000000000 --- a/tools/eslint/node_modules/table/dist/truncateTableData.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["truncateTableData.js"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;kBAQe,UAAC,IAAD,EAAO,MAAP,EAAkB;AAC7B,WAAO,mBAAM,IAAN,EAAY,UAAC,KAAD,EAAW;AAC1B,eAAO,mBAAM,KAAN,EAAa,UAAC,OAAD,EAAU,KAAV,EAAoB;AACpC,mBAAO,wBAAW,OAAX,EAAoB;AACvB,wBAAQ,OAAO,OAAP,CAAe,KAAf,EAAsB;AADP,aAApB,CAAP;AAGH,SAJM,CAAP;AAKH,KANM,CAAP;AAOH,C","file":"truncateTableData.js","sourcesContent":["import _ from 'lodash';\n\n/**\n * @todo Make it work with ASCII content.\n * @param {table~row[]} rows\n * @param {Object} config\n * @return {table~row[]}\n */\nexport default (rows, config) => {\n return _.map(rows, (cells) => {\n return _.map(cells, (content, index) => {\n return _.truncate(content, {\n length: config.columns[index].truncate\n });\n });\n });\n};\n"]} \ No newline at end of file diff --git a/tools/eslint/node_modules/table/dist/validateConfig.js b/tools/eslint/node_modules/table/dist/validateConfig.js index 965ddc5db4654c..caba30134de2e6 100644 --- a/tools/eslint/node_modules/table/dist/validateConfig.js +++ b/tools/eslint/node_modules/table/dist/validateConfig.js @@ -1,62 +1,756 @@ 'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _ajv = require('ajv'); - -var _ajv2 = _interopRequireDefault(_ajv); - -var _ajvKeywords = require('ajv-keywords'); - -var _ajvKeywords2 = _interopRequireDefault(_ajvKeywords); - -var _config = require('./schemas/config.json'); - -var _config2 = _interopRequireDefault(_config); - -var _streamConfig = require('./schemas/streamConfig.json'); - -var _streamConfig2 = _interopRequireDefault(_streamConfig); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -const ajv = new _ajv2.default({ - allErrors: true -}); - -(0, _ajvKeywords2.default)(ajv, 'typeof'); - -ajv.addSchema(_config2.default); -ajv.addSchema(_streamConfig2.default); - -/** - * @param {string} schemaId - * @param {formatData~config} config - * @returns {undefined} - */ - -exports.default = function (schemaId) { - let config = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; - - if (!ajv.validate(schemaId, config)) { - const errors = ajv.errors.map(error => { - return { - dataPath: error.dataPath, - message: error.message, - params: error.params, - schemaPath: error.schemaPath +var equal = require('ajv/lib/compile/equal'); +var validate = (function() { + var pattern0 = new RegExp('^[0-9]+$'); + var refVal = []; + var refVal1 = (function() { + var pattern0 = new RegExp('^[0-9]+$'); + return function validate(data, dataPath, parentData, parentDataProperty, rootData) { + 'use strict'; + var vErrors = null; + var errors = 0; + if (rootData === undefined) rootData = data; + if ((data && typeof data === "object" && !Array.isArray(data))) { + var errs__0 = errors; + var valid1 = true; + for (var key0 in data) { + var isAdditional0 = !(false || validate.schema.properties[key0]); + if (isAdditional0) { + valid1 = false; + var err = { + keyword: 'additionalProperties', + dataPath: (dataPath || '') + "", + schemaPath: '#/additionalProperties', + params: { + additionalProperty: '' + key0 + '' + }, + message: 'should NOT have additional properties' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + } + if (data.topBody !== undefined) { + var errs_1 = errors; + if (!refVal2(data.topBody, (dataPath || '') + '.topBody', data, 'topBody', rootData)) { + if (vErrors === null) vErrors = refVal2.errors; + else vErrors = vErrors.concat(refVal2.errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.topJoin !== undefined) { + var errs_1 = errors; + if (!refVal[2](data.topJoin, (dataPath || '') + '.topJoin', data, 'topJoin', rootData)) { + if (vErrors === null) vErrors = refVal[2].errors; + else vErrors = vErrors.concat(refVal[2].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.topLeft !== undefined) { + var errs_1 = errors; + if (!refVal[2](data.topLeft, (dataPath || '') + '.topLeft', data, 'topLeft', rootData)) { + if (vErrors === null) vErrors = refVal[2].errors; + else vErrors = vErrors.concat(refVal[2].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.topRight !== undefined) { + var errs_1 = errors; + if (!refVal[2](data.topRight, (dataPath || '') + '.topRight', data, 'topRight', rootData)) { + if (vErrors === null) vErrors = refVal[2].errors; + else vErrors = vErrors.concat(refVal[2].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.bottomBody !== undefined) { + var errs_1 = errors; + if (!refVal[2](data.bottomBody, (dataPath || '') + '.bottomBody', data, 'bottomBody', rootData)) { + if (vErrors === null) vErrors = refVal[2].errors; + else vErrors = vErrors.concat(refVal[2].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.bottomJoin !== undefined) { + var errs_1 = errors; + if (!refVal[2](data.bottomJoin, (dataPath || '') + '.bottomJoin', data, 'bottomJoin', rootData)) { + if (vErrors === null) vErrors = refVal[2].errors; + else vErrors = vErrors.concat(refVal[2].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.bottomLeft !== undefined) { + var errs_1 = errors; + if (!refVal[2](data.bottomLeft, (dataPath || '') + '.bottomLeft', data, 'bottomLeft', rootData)) { + if (vErrors === null) vErrors = refVal[2].errors; + else vErrors = vErrors.concat(refVal[2].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.bottomRight !== undefined) { + var errs_1 = errors; + if (!refVal[2](data.bottomRight, (dataPath || '') + '.bottomRight', data, 'bottomRight', rootData)) { + if (vErrors === null) vErrors = refVal[2].errors; + else vErrors = vErrors.concat(refVal[2].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.bodyLeft !== undefined) { + var errs_1 = errors; + if (!refVal[2](data.bodyLeft, (dataPath || '') + '.bodyLeft', data, 'bodyLeft', rootData)) { + if (vErrors === null) vErrors = refVal[2].errors; + else vErrors = vErrors.concat(refVal[2].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.bodyRight !== undefined) { + var errs_1 = errors; + if (!refVal[2](data.bodyRight, (dataPath || '') + '.bodyRight', data, 'bodyRight', rootData)) { + if (vErrors === null) vErrors = refVal[2].errors; + else vErrors = vErrors.concat(refVal[2].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.bodyJoin !== undefined) { + var errs_1 = errors; + if (!refVal[2](data.bodyJoin, (dataPath || '') + '.bodyJoin', data, 'bodyJoin', rootData)) { + if (vErrors === null) vErrors = refVal[2].errors; + else vErrors = vErrors.concat(refVal[2].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.joinBody !== undefined) { + var errs_1 = errors; + if (!refVal[2](data.joinBody, (dataPath || '') + '.joinBody', data, 'joinBody', rootData)) { + if (vErrors === null) vErrors = refVal[2].errors; + else vErrors = vErrors.concat(refVal[2].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.joinLeft !== undefined) { + var errs_1 = errors; + if (!refVal[2](data.joinLeft, (dataPath || '') + '.joinLeft', data, 'joinLeft', rootData)) { + if (vErrors === null) vErrors = refVal[2].errors; + else vErrors = vErrors.concat(refVal[2].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.joinRight !== undefined) { + var errs_1 = errors; + if (!refVal[2](data.joinRight, (dataPath || '') + '.joinRight', data, 'joinRight', rootData)) { + if (vErrors === null) vErrors = refVal[2].errors; + else vErrors = vErrors.concat(refVal[2].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.joinJoin !== undefined) { + var errs_1 = errors; + if (!refVal[2](data.joinJoin, (dataPath || '') + '.joinJoin', data, 'joinJoin', rootData)) { + if (vErrors === null) vErrors = refVal[2].errors; + else vErrors = vErrors.concat(refVal[2].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + } else { + var err = { + keyword: 'type', + dataPath: (dataPath || '') + "", + schemaPath: '#/type', + params: { + type: 'object' + }, + message: 'should be object' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + validate.errors = vErrors; + return errors === 0; + }; + })(); + refVal1.schema = { + "type": "object", + "properties": { + "topBody": { + "$ref": "#/definitions/border" + }, + "topJoin": { + "$ref": "#/definitions/border" + }, + "topLeft": { + "$ref": "#/definitions/border" + }, + "topRight": { + "$ref": "#/definitions/border" + }, + "bottomBody": { + "$ref": "#/definitions/border" + }, + "bottomJoin": { + "$ref": "#/definitions/border" + }, + "bottomLeft": { + "$ref": "#/definitions/border" + }, + "bottomRight": { + "$ref": "#/definitions/border" + }, + "bodyLeft": { + "$ref": "#/definitions/border" + }, + "bodyRight": { + "$ref": "#/definitions/border" + }, + "bodyJoin": { + "$ref": "#/definitions/border" + }, + "joinBody": { + "$ref": "#/definitions/border" + }, + "joinLeft": { + "$ref": "#/definitions/border" + }, + "joinRight": { + "$ref": "#/definitions/border" + }, + "joinJoin": { + "$ref": "#/definitions/border" + } + }, + "additionalProperties": false + }; + refVal1.errors = null; + refVal[1] = refVal1; + var refVal2 = (function() { + var pattern0 = new RegExp('^[0-9]+$'); + return function validate(data, dataPath, parentData, parentDataProperty, rootData) { + 'use strict'; + var vErrors = null; + var errors = 0; + if (rootData === undefined) rootData = data; + if (typeof data !== "string") { + var err = { + keyword: 'type', + dataPath: (dataPath || '') + "", + schemaPath: '#/type', + params: { + type: 'string' + }, + message: 'should be string' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + validate.errors = vErrors; + return errors === 0; + }; + })(); + refVal2.schema = { + "type": "string" + }; + refVal2.errors = null; + refVal[2] = refVal2; + var refVal3 = (function() { + var pattern0 = new RegExp('^[0-9]+$'); + return function validate(data, dataPath, parentData, parentDataProperty, rootData) { + 'use strict'; + var vErrors = null; + var errors = 0; + if (rootData === undefined) rootData = data; + if ((data && typeof data === "object" && !Array.isArray(data))) { + var errs__0 = errors; + var valid1 = true; + for (var key0 in data) { + var isAdditional0 = !(false || pattern0.test(key0)); + if (isAdditional0) { + valid1 = false; + var err = { + keyword: 'additionalProperties', + dataPath: (dataPath || '') + "", + schemaPath: '#/additionalProperties', + params: { + additionalProperty: '' + key0 + '' + }, + message: 'should NOT have additional properties' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + } + for (var key0 in data) { + if (pattern0.test(key0)) { + var errs_1 = errors; + if (!refVal4(data[key0], (dataPath || '') + '[\'' + key0 + '\']', data, key0, rootData)) { + if (vErrors === null) vErrors = refVal4.errors; + else vErrors = vErrors.concat(refVal4.errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + } + } else { + var err = { + keyword: 'type', + dataPath: (dataPath || '') + "", + schemaPath: '#/type', + params: { + type: 'object' + }, + message: 'should be object' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + validate.errors = vErrors; + return errors === 0; + }; + })(); + refVal3.schema = { + "type": "object", + "patternProperties": { + "^[0-9]+$": { + "$ref": "#/definitions/column" + } + }, + "additionalProperties": false + }; + refVal3.errors = null; + refVal[3] = refVal3; + var refVal4 = (function() { + var pattern0 = new RegExp('^[0-9]+$'); + return function validate(data, dataPath, parentData, parentDataProperty, rootData) { + 'use strict'; + var vErrors = null; + var errors = 0; + if (rootData === undefined) rootData = data; + if ((data && typeof data === "object" && !Array.isArray(data))) { + var errs__0 = errors; + var valid1 = true; + for (var key0 in data) { + var isAdditional0 = !(false || validate.schema.properties[key0]); + if (isAdditional0) { + valid1 = false; + var err = { + keyword: 'additionalProperties', + dataPath: (dataPath || '') + "", + schemaPath: '#/additionalProperties', + params: { + additionalProperty: '' + key0 + '' + }, + message: 'should NOT have additional properties' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + } + var data1 = data.alignment; + if (data1 !== undefined) { + var errs_1 = errors; + var schema1 = validate.schema.properties.alignment.enum; + var valid1; + valid1 = false; + for (var i1 = 0; i1 < schema1.length; i1++) + if (equal(data1, schema1[i1])) { + valid1 = true; + break; + } + if (!valid1) { + var err = { + keyword: 'enum', + dataPath: (dataPath || '') + '.alignment', + schemaPath: '#/properties/alignment/enum', + params: { + allowedValues: schema1 + }, + message: 'should be equal to one of the allowed values' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + if (typeof data1 !== "string") { + var err = { + keyword: 'type', + dataPath: (dataPath || '') + '.alignment', + schemaPath: '#/properties/alignment/type', + params: { + type: 'string' + }, + message: 'should be string' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + var valid1 = errors === errs_1; + } + if (data.width !== undefined) { + var errs_1 = errors; + if (typeof data.width !== "number") { + var err = { + keyword: 'type', + dataPath: (dataPath || '') + '.width', + schemaPath: '#/properties/width/type', + params: { + type: 'number' + }, + message: 'should be number' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + var valid1 = errors === errs_1; + } + if (data.wrapWord !== undefined) { + var errs_1 = errors; + if (typeof data.wrapWord !== "boolean") { + var err = { + keyword: 'type', + dataPath: (dataPath || '') + '.wrapWord', + schemaPath: '#/properties/wrapWord/type', + params: { + type: 'boolean' + }, + message: 'should be boolean' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + var valid1 = errors === errs_1; + } + if (data.truncate !== undefined) { + var errs_1 = errors; + if (typeof data.truncate !== "number") { + var err = { + keyword: 'type', + dataPath: (dataPath || '') + '.truncate', + schemaPath: '#/properties/truncate/type', + params: { + type: 'number' + }, + message: 'should be number' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + var valid1 = errors === errs_1; + } + if (data.paddingLeft !== undefined) { + var errs_1 = errors; + if (typeof data.paddingLeft !== "number") { + var err = { + keyword: 'type', + dataPath: (dataPath || '') + '.paddingLeft', + schemaPath: '#/properties/paddingLeft/type', + params: { + type: 'number' + }, + message: 'should be number' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + var valid1 = errors === errs_1; + } + if (data.paddingRight !== undefined) { + var errs_1 = errors; + if (typeof data.paddingRight !== "number") { + var err = { + keyword: 'type', + dataPath: (dataPath || '') + '.paddingRight', + schemaPath: '#/properties/paddingRight/type', + params: { + type: 'number' + }, + message: 'should be number' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + var valid1 = errors === errs_1; + } + } else { + var err = { + keyword: 'type', + dataPath: (dataPath || '') + "", + schemaPath: '#/type', + params: { + type: 'object' + }, + message: 'should be object' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + validate.errors = vErrors; + return errors === 0; + }; + })(); + refVal4.schema = { + "type": "object", + "properties": { + "alignment": { + "type": "string", + "enum": ["left", "right", "center"] + }, + "width": { + "type": "number" + }, + "wrapWord": { + "type": "boolean" + }, + "truncate": { + "type": "number" + }, + "paddingLeft": { + "type": "number" + }, + "paddingRight": { + "type": "number" + } + }, + "additionalProperties": false + }; + refVal4.errors = null; + refVal[4] = refVal4; + return function validate(data, dataPath, parentData, parentDataProperty, rootData) { + 'use strict'; + var vErrors = null; + var errors = 0; + if (rootData === undefined) rootData = data; + if ((data && typeof data === "object" && !Array.isArray(data))) { + var errs__0 = errors; + var valid1 = true; + for (var key0 in data) { + var isAdditional0 = !(false || key0 == 'border' || key0 == 'columns' || key0 == 'columnDefault' || key0 == 'drawHorizontalLine'); + if (isAdditional0) { + valid1 = false; + var err = { + keyword: 'additionalProperties', + dataPath: (dataPath || '') + "", + schemaPath: '#/additionalProperties', + params: { + additionalProperty: '' + key0 + '' + }, + message: 'should NOT have additional properties' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + } + if (data.border !== undefined) { + var errs_1 = errors; + if (!refVal1(data.border, (dataPath || '') + '.border', data, 'border', rootData)) { + if (vErrors === null) vErrors = refVal1.errors; + else vErrors = vErrors.concat(refVal1.errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.columns !== undefined) { + var errs_1 = errors; + if (!refVal3(data.columns, (dataPath || '') + '.columns', data, 'columns', rootData)) { + if (vErrors === null) vErrors = refVal3.errors; + else vErrors = vErrors.concat(refVal3.errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.columnDefault !== undefined) { + var errs_1 = errors; + if (!refVal[4](data.columnDefault, (dataPath || '') + '.columnDefault', data, 'columnDefault', rootData)) { + if (vErrors === null) vErrors = refVal[4].errors; + else vErrors = vErrors.concat(refVal[4].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.drawHorizontalLine !== undefined) { + var errs_1 = errors; + var errs__1 = errors; + var valid1; + if (!(typeof data.drawHorizontalLine == "function")) { + if (errs__1 == errors) { + var err = { + keyword: 'typeof', + dataPath: (dataPath || '') + '.drawHorizontalLine', + schemaPath: '#/properties/drawHorizontalLine/typeof', + params: { + keyword: 'typeof' + }, + message: 'should pass "typeof" keyword validation' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } else { + for (var i1 = errs__1; i1 < errors; i1++) { + var ruleErr1 = vErrors[i1]; + if (ruleErr1.dataPath === undefined) { + ruleErr1.dataPath = (dataPath || '') + '.drawHorizontalLine'; + } + if (ruleErr1.schemaPath === undefined) { + ruleErr1.schemaPath = "#/properties/drawHorizontalLine/typeof"; + } + } + } + } + var valid1 = errors === errs_1; + } + } else { + var err = { + keyword: 'type', + dataPath: (dataPath || '') + "", + schemaPath: '#/type', + params: { + type: 'object' + }, + message: 'should be object' }; - }); - - /* eslint-disable no-console */ - console.log('config', config); - console.log('errors', errors); - /* eslint-enable no-console */ - - throw new Error('Invalid config.'); + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + validate.errors = vErrors; + return errors === 0; + }; +})(); +validate.schema = { + "id": "config.json", + "$schema": "http://json-schema.org/draft-04/schema#", + "type": "object", + "properties": { + "border": { + "$ref": "#/definitions/borders" + }, + "columns": { + "$ref": "#/definitions/columns" + }, + "columnDefault": { + "$ref": "#/definitions/column" + }, + "drawHorizontalLine": { + "typeof": "function" + } + }, + "additionalProperties": false, + "definitions": { + "columns": { + "type": "object", + "patternProperties": { + "^[0-9]+$": { + "$ref": "#/definitions/column" + } + }, + "additionalProperties": false + }, + "column": { + "type": "object", + "properties": { + "alignment": { + "type": "string", + "enum": ["left", "right", "center"] + }, + "width": { + "type": "number" + }, + "wrapWord": { + "type": "boolean" + }, + "truncate": { + "type": "number" + }, + "paddingLeft": { + "type": "number" + }, + "paddingRight": { + "type": "number" + } + }, + "additionalProperties": false + }, + "borders": { + "type": "object", + "properties": { + "topBody": { + "$ref": "#/definitions/border" + }, + "topJoin": { + "$ref": "#/definitions/border" + }, + "topLeft": { + "$ref": "#/definitions/border" + }, + "topRight": { + "$ref": "#/definitions/border" + }, + "bottomBody": { + "$ref": "#/definitions/border" + }, + "bottomJoin": { + "$ref": "#/definitions/border" + }, + "bottomLeft": { + "$ref": "#/definitions/border" + }, + "bottomRight": { + "$ref": "#/definitions/border" + }, + "bodyLeft": { + "$ref": "#/definitions/border" + }, + "bodyRight": { + "$ref": "#/definitions/border" + }, + "bodyJoin": { + "$ref": "#/definitions/border" + }, + "joinBody": { + "$ref": "#/definitions/border" + }, + "joinLeft": { + "$ref": "#/definitions/border" + }, + "joinRight": { + "$ref": "#/definitions/border" + }, + "joinJoin": { + "$ref": "#/definitions/border" + } + }, + "additionalProperties": false + }, + "border": { + "type": "string" + } } }; - -module.exports = exports['default']; \ No newline at end of file +validate.errors = null; +module.exports = validate; \ No newline at end of file diff --git a/tools/eslint/node_modules/table/dist/validateConfig.js.map b/tools/eslint/node_modules/table/dist/validateConfig.js.map deleted file mode 100644 index ad5e82b80bd67e..00000000000000 --- a/tools/eslint/node_modules/table/dist/validateConfig.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["validateConfig.js"],"names":[],"mappings":";;;;;;AAAA;;;;AACA;;;;;;;;;;;;;;;;;;;kBAce,YAAiB;AAAA,QAAhB,MAAgB,yDAAP,EAAO;;AAC5B,QAAI,eAAJ;;AAEA,aAAS,aAAI,cAAJ,CAAmB,MAAnB,mBAAT;;AAEA,QAAI,CAAC,OAAO,KAAZ,EAAmB;;AAEf,gBAAQ,GAAR,CAAY,QAAZ,EAAsB,MAAtB;AACA,gBAAQ,GAAR,CAAY,OAAZ,EAAqB;AACjB,qBAAS,OAAO,KAAP,CAAa,OADL;AAEjB,oBAAQ,OAAO,KAAP,CAAa,MAFJ;AAGjB,sBAAU,OAAO,KAAP,CAAa,QAHN;AAIjB,wBAAY,OAAO,KAAP,CAAa;AAJR,SAArB;;;AAQA,cAAM,IAAI,KAAJ,CAAU,iBAAV,CAAN;AACH;AACJ,C","file":"validateConfig.js","sourcesContent":["import schema from './schemas/config.json';\nimport tv4 from 'tv4';\n\n/**\n * @typedef {string} cell\n */\n\n/**\n * @typedef {cell[]} validateData~column\n */\n\n/**\n * @param {formatData~config} config\n * @returns {undefined}\n */\nexport default (config = {}) => {\n let result;\n\n result = tv4.validateResult(config, schema);\n\n if (!result.valid) {\n /* eslint-disable no-console */\n console.log('config', config);\n console.log('error', {\n message: result.error.message,\n params: result.error.params,\n dataPath: result.error.dataPath,\n schemaPath: result.error.schemaPath\n });\n /* eslint-enable no-console */\n\n throw new Error('Invalid config.');\n }\n};\n"]} \ No newline at end of file diff --git a/tools/eslint/node_modules/table/dist/validateStreamConfig.js b/tools/eslint/node_modules/table/dist/validateStreamConfig.js index e5cc85e3046282..09ea2aac925158 100644 --- a/tools/eslint/node_modules/table/dist/validateStreamConfig.js +++ b/tools/eslint/node_modules/table/dist/validateStreamConfig.js @@ -1,53 +1,742 @@ 'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _streamConfig = require('./schemas/streamConfig.json'); - -var _streamConfig2 = _interopRequireDefault(_streamConfig); - -var _tv = require('tv4'); - -var _tv2 = _interopRequireDefault(_tv); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * @typedef {string} cell - */ - -/** - * @typedef {cell[]} validateData~column - */ - -/** - * @param {formatData~config} config - * @returns {undefined} - */ - -exports.default = function () { - var config = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; - - var result = void 0; - - result = _tv2.default.validateResult(config, _streamConfig2.default); - - if (!result.valid) { - /* eslint-disable no-console */ - console.log('config', config); - console.log('error', { - message: result.error.message, - params: result.error.params, - dataPath: result.error.dataPath, - schemaPath: result.error.schemaPath - }); - /* eslint-enable no-console */ - - throw new Error('Invalid config.'); +var equal = require('ajv/lib/compile/equal'); +var validate = (function() { + var pattern0 = new RegExp('^[0-9]+$'); + var refVal = []; + var refVal1 = (function() { + var pattern0 = new RegExp('^[0-9]+$'); + return function validate(data, dataPath, parentData, parentDataProperty, rootData) { + 'use strict'; + var vErrors = null; + var errors = 0; + if (rootData === undefined) rootData = data; + if ((data && typeof data === "object" && !Array.isArray(data))) { + var errs__0 = errors; + var valid1 = true; + for (var key0 in data) { + var isAdditional0 = !(false || validate.schema.properties[key0]); + if (isAdditional0) { + valid1 = false; + var err = { + keyword: 'additionalProperties', + dataPath: (dataPath || '') + "", + schemaPath: '#/additionalProperties', + params: { + additionalProperty: '' + key0 + '' + }, + message: 'should NOT have additional properties' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + } + if (data.topBody !== undefined) { + var errs_1 = errors; + if (!refVal2(data.topBody, (dataPath || '') + '.topBody', data, 'topBody', rootData)) { + if (vErrors === null) vErrors = refVal2.errors; + else vErrors = vErrors.concat(refVal2.errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.topJoin !== undefined) { + var errs_1 = errors; + if (!refVal[2](data.topJoin, (dataPath || '') + '.topJoin', data, 'topJoin', rootData)) { + if (vErrors === null) vErrors = refVal[2].errors; + else vErrors = vErrors.concat(refVal[2].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.topLeft !== undefined) { + var errs_1 = errors; + if (!refVal[2](data.topLeft, (dataPath || '') + '.topLeft', data, 'topLeft', rootData)) { + if (vErrors === null) vErrors = refVal[2].errors; + else vErrors = vErrors.concat(refVal[2].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.topRight !== undefined) { + var errs_1 = errors; + if (!refVal[2](data.topRight, (dataPath || '') + '.topRight', data, 'topRight', rootData)) { + if (vErrors === null) vErrors = refVal[2].errors; + else vErrors = vErrors.concat(refVal[2].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.bottomBody !== undefined) { + var errs_1 = errors; + if (!refVal[2](data.bottomBody, (dataPath || '') + '.bottomBody', data, 'bottomBody', rootData)) { + if (vErrors === null) vErrors = refVal[2].errors; + else vErrors = vErrors.concat(refVal[2].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.bottomJoin !== undefined) { + var errs_1 = errors; + if (!refVal[2](data.bottomJoin, (dataPath || '') + '.bottomJoin', data, 'bottomJoin', rootData)) { + if (vErrors === null) vErrors = refVal[2].errors; + else vErrors = vErrors.concat(refVal[2].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.bottomLeft !== undefined) { + var errs_1 = errors; + if (!refVal[2](data.bottomLeft, (dataPath || '') + '.bottomLeft', data, 'bottomLeft', rootData)) { + if (vErrors === null) vErrors = refVal[2].errors; + else vErrors = vErrors.concat(refVal[2].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.bottomRight !== undefined) { + var errs_1 = errors; + if (!refVal[2](data.bottomRight, (dataPath || '') + '.bottomRight', data, 'bottomRight', rootData)) { + if (vErrors === null) vErrors = refVal[2].errors; + else vErrors = vErrors.concat(refVal[2].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.bodyLeft !== undefined) { + var errs_1 = errors; + if (!refVal[2](data.bodyLeft, (dataPath || '') + '.bodyLeft', data, 'bodyLeft', rootData)) { + if (vErrors === null) vErrors = refVal[2].errors; + else vErrors = vErrors.concat(refVal[2].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.bodyRight !== undefined) { + var errs_1 = errors; + if (!refVal[2](data.bodyRight, (dataPath || '') + '.bodyRight', data, 'bodyRight', rootData)) { + if (vErrors === null) vErrors = refVal[2].errors; + else vErrors = vErrors.concat(refVal[2].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.bodyJoin !== undefined) { + var errs_1 = errors; + if (!refVal[2](data.bodyJoin, (dataPath || '') + '.bodyJoin', data, 'bodyJoin', rootData)) { + if (vErrors === null) vErrors = refVal[2].errors; + else vErrors = vErrors.concat(refVal[2].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.joinBody !== undefined) { + var errs_1 = errors; + if (!refVal[2](data.joinBody, (dataPath || '') + '.joinBody', data, 'joinBody', rootData)) { + if (vErrors === null) vErrors = refVal[2].errors; + else vErrors = vErrors.concat(refVal[2].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.joinLeft !== undefined) { + var errs_1 = errors; + if (!refVal[2](data.joinLeft, (dataPath || '') + '.joinLeft', data, 'joinLeft', rootData)) { + if (vErrors === null) vErrors = refVal[2].errors; + else vErrors = vErrors.concat(refVal[2].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.joinRight !== undefined) { + var errs_1 = errors; + if (!refVal[2](data.joinRight, (dataPath || '') + '.joinRight', data, 'joinRight', rootData)) { + if (vErrors === null) vErrors = refVal[2].errors; + else vErrors = vErrors.concat(refVal[2].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.joinJoin !== undefined) { + var errs_1 = errors; + if (!refVal[2](data.joinJoin, (dataPath || '') + '.joinJoin', data, 'joinJoin', rootData)) { + if (vErrors === null) vErrors = refVal[2].errors; + else vErrors = vErrors.concat(refVal[2].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + } else { + var err = { + keyword: 'type', + dataPath: (dataPath || '') + "", + schemaPath: '#/type', + params: { + type: 'object' + }, + message: 'should be object' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + validate.errors = vErrors; + return errors === 0; + }; + })(); + refVal1.schema = { + "type": "object", + "properties": { + "topBody": { + "$ref": "#/definitions/border" + }, + "topJoin": { + "$ref": "#/definitions/border" + }, + "topLeft": { + "$ref": "#/definitions/border" + }, + "topRight": { + "$ref": "#/definitions/border" + }, + "bottomBody": { + "$ref": "#/definitions/border" + }, + "bottomJoin": { + "$ref": "#/definitions/border" + }, + "bottomLeft": { + "$ref": "#/definitions/border" + }, + "bottomRight": { + "$ref": "#/definitions/border" + }, + "bodyLeft": { + "$ref": "#/definitions/border" + }, + "bodyRight": { + "$ref": "#/definitions/border" + }, + "bodyJoin": { + "$ref": "#/definitions/border" + }, + "joinBody": { + "$ref": "#/definitions/border" + }, + "joinLeft": { + "$ref": "#/definitions/border" + }, + "joinRight": { + "$ref": "#/definitions/border" + }, + "joinJoin": { + "$ref": "#/definitions/border" + } + }, + "additionalProperties": false + }; + refVal1.errors = null; + refVal[1] = refVal1; + var refVal2 = (function() { + var pattern0 = new RegExp('^[0-9]+$'); + return function validate(data, dataPath, parentData, parentDataProperty, rootData) { + 'use strict'; + var vErrors = null; + var errors = 0; + if (rootData === undefined) rootData = data; + if (typeof data !== "string") { + var err = { + keyword: 'type', + dataPath: (dataPath || '') + "", + schemaPath: '#/type', + params: { + type: 'string' + }, + message: 'should be string' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + validate.errors = vErrors; + return errors === 0; + }; + })(); + refVal2.schema = { + "type": "string" + }; + refVal2.errors = null; + refVal[2] = refVal2; + var refVal3 = (function() { + var pattern0 = new RegExp('^[0-9]+$'); + return function validate(data, dataPath, parentData, parentDataProperty, rootData) { + 'use strict'; + var vErrors = null; + var errors = 0; + if (rootData === undefined) rootData = data; + if ((data && typeof data === "object" && !Array.isArray(data))) { + var errs__0 = errors; + var valid1 = true; + for (var key0 in data) { + var isAdditional0 = !(false || pattern0.test(key0)); + if (isAdditional0) { + valid1 = false; + var err = { + keyword: 'additionalProperties', + dataPath: (dataPath || '') + "", + schemaPath: '#/additionalProperties', + params: { + additionalProperty: '' + key0 + '' + }, + message: 'should NOT have additional properties' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + } + for (var key0 in data) { + if (pattern0.test(key0)) { + var errs_1 = errors; + if (!refVal4(data[key0], (dataPath || '') + '[\'' + key0 + '\']', data, key0, rootData)) { + if (vErrors === null) vErrors = refVal4.errors; + else vErrors = vErrors.concat(refVal4.errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + } + } else { + var err = { + keyword: 'type', + dataPath: (dataPath || '') + "", + schemaPath: '#/type', + params: { + type: 'object' + }, + message: 'should be object' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + validate.errors = vErrors; + return errors === 0; + }; + })(); + refVal3.schema = { + "type": "object", + "patternProperties": { + "^[0-9]+$": { + "$ref": "#/definitions/column" + } + }, + "additionalProperties": false + }; + refVal3.errors = null; + refVal[3] = refVal3; + var refVal4 = (function() { + var pattern0 = new RegExp('^[0-9]+$'); + return function validate(data, dataPath, parentData, parentDataProperty, rootData) { + 'use strict'; + var vErrors = null; + var errors = 0; + if (rootData === undefined) rootData = data; + if ((data && typeof data === "object" && !Array.isArray(data))) { + var errs__0 = errors; + var valid1 = true; + for (var key0 in data) { + var isAdditional0 = !(false || validate.schema.properties[key0]); + if (isAdditional0) { + valid1 = false; + var err = { + keyword: 'additionalProperties', + dataPath: (dataPath || '') + "", + schemaPath: '#/additionalProperties', + params: { + additionalProperty: '' + key0 + '' + }, + message: 'should NOT have additional properties' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + } + var data1 = data.alignment; + if (data1 !== undefined) { + var errs_1 = errors; + var schema1 = validate.schema.properties.alignment.enum; + var valid1; + valid1 = false; + for (var i1 = 0; i1 < schema1.length; i1++) + if (equal(data1, schema1[i1])) { + valid1 = true; + break; + } + if (!valid1) { + var err = { + keyword: 'enum', + dataPath: (dataPath || '') + '.alignment', + schemaPath: '#/properties/alignment/enum', + params: { + allowedValues: schema1 + }, + message: 'should be equal to one of the allowed values' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + if (typeof data1 !== "string") { + var err = { + keyword: 'type', + dataPath: (dataPath || '') + '.alignment', + schemaPath: '#/properties/alignment/type', + params: { + type: 'string' + }, + message: 'should be string' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + var valid1 = errors === errs_1; + } + if (data.width !== undefined) { + var errs_1 = errors; + if (typeof data.width !== "number") { + var err = { + keyword: 'type', + dataPath: (dataPath || '') + '.width', + schemaPath: '#/properties/width/type', + params: { + type: 'number' + }, + message: 'should be number' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + var valid1 = errors === errs_1; + } + if (data.wrapWord !== undefined) { + var errs_1 = errors; + if (typeof data.wrapWord !== "boolean") { + var err = { + keyword: 'type', + dataPath: (dataPath || '') + '.wrapWord', + schemaPath: '#/properties/wrapWord/type', + params: { + type: 'boolean' + }, + message: 'should be boolean' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + var valid1 = errors === errs_1; + } + if (data.truncate !== undefined) { + var errs_1 = errors; + if (typeof data.truncate !== "number") { + var err = { + keyword: 'type', + dataPath: (dataPath || '') + '.truncate', + schemaPath: '#/properties/truncate/type', + params: { + type: 'number' + }, + message: 'should be number' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + var valid1 = errors === errs_1; + } + if (data.paddingLeft !== undefined) { + var errs_1 = errors; + if (typeof data.paddingLeft !== "number") { + var err = { + keyword: 'type', + dataPath: (dataPath || '') + '.paddingLeft', + schemaPath: '#/properties/paddingLeft/type', + params: { + type: 'number' + }, + message: 'should be number' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + var valid1 = errors === errs_1; + } + if (data.paddingRight !== undefined) { + var errs_1 = errors; + if (typeof data.paddingRight !== "number") { + var err = { + keyword: 'type', + dataPath: (dataPath || '') + '.paddingRight', + schemaPath: '#/properties/paddingRight/type', + params: { + type: 'number' + }, + message: 'should be number' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + var valid1 = errors === errs_1; + } + } else { + var err = { + keyword: 'type', + dataPath: (dataPath || '') + "", + schemaPath: '#/type', + params: { + type: 'object' + }, + message: 'should be object' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + validate.errors = vErrors; + return errors === 0; + }; + })(); + refVal4.schema = { + "type": "object", + "properties": { + "alignment": { + "type": "string", + "enum": ["left", "right", "center"] + }, + "width": { + "type": "number" + }, + "wrapWord": { + "type": "boolean" + }, + "truncate": { + "type": "number" + }, + "paddingLeft": { + "type": "number" + }, + "paddingRight": { + "type": "number" + } + }, + "additionalProperties": false + }; + refVal4.errors = null; + refVal[4] = refVal4; + return function validate(data, dataPath, parentData, parentDataProperty, rootData) { + 'use strict'; + var vErrors = null; + var errors = 0; + if (rootData === undefined) rootData = data; + if ((data && typeof data === "object" && !Array.isArray(data))) { + var errs__0 = errors; + var valid1 = true; + for (var key0 in data) { + var isAdditional0 = !(false || key0 == 'border' || key0 == 'columns' || key0 == 'columnDefault' || key0 == 'columnCount'); + if (isAdditional0) { + valid1 = false; + var err = { + keyword: 'additionalProperties', + dataPath: (dataPath || '') + "", + schemaPath: '#/additionalProperties', + params: { + additionalProperty: '' + key0 + '' + }, + message: 'should NOT have additional properties' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + } + if (data.border !== undefined) { + var errs_1 = errors; + if (!refVal1(data.border, (dataPath || '') + '.border', data, 'border', rootData)) { + if (vErrors === null) vErrors = refVal1.errors; + else vErrors = vErrors.concat(refVal1.errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.columns !== undefined) { + var errs_1 = errors; + if (!refVal3(data.columns, (dataPath || '') + '.columns', data, 'columns', rootData)) { + if (vErrors === null) vErrors = refVal3.errors; + else vErrors = vErrors.concat(refVal3.errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.columnDefault !== undefined) { + var errs_1 = errors; + if (!refVal[4](data.columnDefault, (dataPath || '') + '.columnDefault', data, 'columnDefault', rootData)) { + if (vErrors === null) vErrors = refVal[4].errors; + else vErrors = vErrors.concat(refVal[4].errors); + errors = vErrors.length; + } + var valid1 = errors === errs_1; + } + if (data.columnCount !== undefined) { + var errs_1 = errors; + if (typeof data.columnCount !== "number") { + var err = { + keyword: 'type', + dataPath: (dataPath || '') + '.columnCount', + schemaPath: '#/properties/columnCount/type', + params: { + type: 'number' + }, + message: 'should be number' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; + } + var valid1 = errors === errs_1; + } + } else { + var err = { + keyword: 'type', + dataPath: (dataPath || '') + "", + schemaPath: '#/type', + params: { + type: 'object' + }, + message: 'should be object' + }; + if (vErrors === null) vErrors = [err]; + else vErrors.push(err); + errors++; } + validate.errors = vErrors; + return errors === 0; + }; +})(); +validate.schema = { + "id": "streamConfig.json", + "$schema": "http://json-schema.org/draft-04/schema#", + "type": "object", + "properties": { + "border": { + "$ref": "#/definitions/borders" + }, + "columns": { + "$ref": "#/definitions/columns" + }, + "columnDefault": { + "$ref": "#/definitions/column" + }, + "columnCount": { + "type": "number" + } + }, + "additionalProperties": false, + "definitions": { + "columns": { + "type": "object", + "patternProperties": { + "^[0-9]+$": { + "$ref": "#/definitions/column" + } + }, + "additionalProperties": false + }, + "column": { + "type": "object", + "properties": { + "alignment": { + "type": "string", + "enum": ["left", "right", "center"] + }, + "width": { + "type": "number" + }, + "wrapWord": { + "type": "boolean" + }, + "truncate": { + "type": "number" + }, + "paddingLeft": { + "type": "number" + }, + "paddingRight": { + "type": "number" + } + }, + "additionalProperties": false + }, + "borders": { + "type": "object", + "properties": { + "topBody": { + "$ref": "#/definitions/border" + }, + "topJoin": { + "$ref": "#/definitions/border" + }, + "topLeft": { + "$ref": "#/definitions/border" + }, + "topRight": { + "$ref": "#/definitions/border" + }, + "bottomBody": { + "$ref": "#/definitions/border" + }, + "bottomJoin": { + "$ref": "#/definitions/border" + }, + "bottomLeft": { + "$ref": "#/definitions/border" + }, + "bottomRight": { + "$ref": "#/definitions/border" + }, + "bodyLeft": { + "$ref": "#/definitions/border" + }, + "bodyRight": { + "$ref": "#/definitions/border" + }, + "bodyJoin": { + "$ref": "#/definitions/border" + }, + "joinBody": { + "$ref": "#/definitions/border" + }, + "joinLeft": { + "$ref": "#/definitions/border" + }, + "joinRight": { + "$ref": "#/definitions/border" + }, + "joinJoin": { + "$ref": "#/definitions/border" + } + }, + "additionalProperties": false + }, + "border": { + "type": "string" + } + } }; - -module.exports = exports['default']; -//# sourceMappingURL=validateStreamConfig.js.map +validate.errors = null; +module.exports = validate; \ No newline at end of file diff --git a/tools/eslint/node_modules/table/dist/validateStreamConfig.js.map b/tools/eslint/node_modules/table/dist/validateStreamConfig.js.map deleted file mode 100644 index c43bee9d5f1e1e..00000000000000 --- a/tools/eslint/node_modules/table/dist/validateStreamConfig.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["validateStreamConfig.js"],"names":[],"mappings":";;;;;;AAAA;;;;AACA;;;;;;;;;;;;;;;;;;;kBAce,YAAiB;AAAA,QAAhB,MAAgB,yDAAP,EAAO;;AAC5B,QAAI,eAAJ;;AAEA,aAAS,aAAI,cAAJ,CAAmB,MAAnB,yBAAT;;AAEA,QAAI,CAAC,OAAO,KAAZ,EAAmB;;AAEf,gBAAQ,GAAR,CAAY,QAAZ,EAAsB,MAAtB;AACA,gBAAQ,GAAR,CAAY,OAAZ,EAAqB;AACjB,qBAAS,OAAO,KAAP,CAAa,OADL;AAEjB,oBAAQ,OAAO,KAAP,CAAa,MAFJ;AAGjB,sBAAU,OAAO,KAAP,CAAa,QAHN;AAIjB,wBAAY,OAAO,KAAP,CAAa;AAJR,SAArB;;;AAQA,cAAM,IAAI,KAAJ,CAAU,iBAAV,CAAN;AACH;AACJ,C","file":"validateStreamConfig.js","sourcesContent":["import schema from './schemas/streamConfig.json';\nimport tv4 from 'tv4';\n\n/**\n * @typedef {string} cell\n */\n\n/**\n * @typedef {cell[]} validateData~column\n */\n\n/**\n * @param {formatData~config} config\n * @returns {undefined}\n */\nexport default (config = {}) => {\n let result;\n\n result = tv4.validateResult(config, schema);\n\n if (!result.valid) {\n /* eslint-disable no-console */\n console.log('config', config);\n console.log('error', {\n message: result.error.message,\n params: result.error.params,\n dataPath: result.error.dataPath,\n schemaPath: result.error.schemaPath\n });\n /* eslint-enable no-console */\n\n throw new Error('Invalid config.');\n }\n};\n"]} \ No newline at end of file diff --git a/tools/eslint/node_modules/table/dist/validateTableData.js.map b/tools/eslint/node_modules/table/dist/validateTableData.js.map deleted file mode 100644 index 92092051fad066..00000000000000 --- a/tools/eslint/node_modules/table/dist/validateTableData.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["validateTableData.js"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBAce,UAAC,IAAD,EAAU;AACrB,QAAI,qBAAJ;;AAEA,QAAI,CAAC,uBAAU,IAAV,CAAL,EAAsB;AAClB,cAAM,IAAI,KAAJ,CAAU,8BAAV,CAAN;AACH;;AAED,QAAI,KAAK,MAAL,KAAgB,CAApB,EAAuB;AACnB,cAAM,IAAI,KAAJ,CAAU,qCAAV,CAAN;AACH;;AAED,QAAI,KAAK,CAAL,EAAQ,MAAR,KAAmB,CAAvB,EAA0B;AACtB,cAAM,IAAI,KAAJ,CAAU,wCAAV,CAAN;AACH;;AAED,mBAAe,KAAK,CAAL,EAAQ,MAAvB;;AAEA,2BAAU,IAAV,EAAgB,UAAC,KAAD,EAAW;AACvB,YAAI,CAAC,uBAAU,KAAV,CAAL,EAAuB;AACnB,kBAAM,IAAI,KAAJ,CAAU,kCAAV,CAAN;AACH;;AAED,YAAI,MAAM,MAAN,KAAiB,YAArB,EAAmC;AAC/B,kBAAM,IAAI,KAAJ,CAAU,+CAAV,CAAN;AACH;;;;AAID,+BAAU,KAAV,EAAiB,UAAC,IAAD,EAAU;AACvB,gBAAI,cAAc,IAAd,CAAmB,IAAnB,CAAJ,EAA8B;AAC1B,sBAAM,IAAI,KAAJ,CAAU,iDAAV,CAAN;AACH;AACJ,SAJD;AAKH,KAhBD;AAiBH,C","file":"validateTableData.js","sourcesContent":["import _ from 'lodash';\n\n/**\n * @typedef {string} cell\n */\n\n/**\n * @typedef {cell[]} validateData~column\n */\n\n/**\n * @param {column[]} rows\n * @returns {undefined}\n */\nexport default (rows) => {\n let columnNumber;\n\n if (!_.isArray(rows)) {\n throw new Error('Table data must be an array.');\n }\n\n if (rows.length === 0) {\n throw new Error('Table must define at least one row.');\n }\n\n if (rows[0].length === 0) {\n throw new Error('Table must define at least one column.');\n }\n\n columnNumber = rows[0].length;\n\n _.forEach(rows, (cells) => {\n if (!_.isArray(cells)) {\n throw new Error('Table row data must be an array.');\n }\n\n if (cells.length !== columnNumber) {\n throw new Error('Table must have a consistent number of cells.');\n }\n\n // @todo Make an exception for newline characters.\n // @see https://github.com/gajus/table/issues/9\n _.forEach(cells, (cell) => {\n if (/[\\x01-\\x1A]/.test(cell)) {\n throw new Error('Table data must not contain control characters.');\n }\n });\n });\n};\n"]} \ No newline at end of file diff --git a/tools/eslint/node_modules/table/dist/wrapString.js.map b/tools/eslint/node_modules/table/dist/wrapString.js.map deleted file mode 100644 index 0ba89f7ddd6406..00000000000000 --- a/tools/eslint/node_modules/table/dist/wrapString.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["wrapString.js"],"names":[],"mappings":";;;;;;;;;;AACA;;;;AACA;;;;;;;;;;;;;;;;;;kBAae,UAAC,OAAD,EAAU,IAAV,EAAmB;AAC9B,QAAI,eAAJ;QACI,qBADJ;;AAGA,mBAAe,OAAf;;AAEA,aAAS,EAAT;;AAEA,OAAG;AACC,eAAO,IAAP,CAAY,yBAAM,YAAN,EAAoB,CAApB,EAAuB,IAAvB,CAAZ;;AAEA,uBAAe,oBAAO,yBAAM,YAAN,EAAoB,IAApB,CAAP,CAAf;AACH,KAJD,QAIS,2BAAY,YAAZ,CAJT;;AAMA,WAAO,MAAP;AACH,C","file":"wrapString.js","sourcesContent":["import _ from 'lodash';\nimport slice from 'slice-ansi';\nimport stringWidth from 'string-width';\n\n/**\n * Creates an array of strings split into groups the length of size.\n * This function works with strings that contain ASCII characters.\n *\n * wrapText is different from would-be \"chunk\" implementation\n * in that whitespace characters that occur on a chunk size limit are trimmed.\n *\n * @param {string} subject\n * @param {number} size\n * @returns {Array}\n */\nexport default (subject, size) => {\n let chunks,\n subjectSlice;\n\n subjectSlice = subject;\n\n chunks = [];\n\n do {\n chunks.push(slice(subjectSlice, 0, size));\n\n subjectSlice = _.trim(slice(subjectSlice, size));\n } while (stringWidth(subjectSlice));\n\n return chunks;\n};\n"]} \ No newline at end of file diff --git a/tools/eslint/node_modules/table/dist/wrapWord.js.map b/tools/eslint/node_modules/table/dist/wrapWord.js.map deleted file mode 100644 index 92e36ba776c864..00000000000000 --- a/tools/eslint/node_modules/table/dist/wrapWord.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["wrapWord.js"],"names":[],"mappings":";;;;;;;;;;AACA;;;;AACA;;;;;;;;;;;;kBAOe,UAAC,KAAD,EAAQ,IAAR,EAAiB;AAC5B,QAAI,cAAJ;QACI,eADJ;QAEI,WAFJ;QAGI,gBAHJ;;AAKA,cAAU,KAAV;;AAEA,aAAS,EAAT;;;AAGA,SAAK,IAAI,MAAJ,CAAW,WAAW,IAAX,GAAkB,mBAAlB,IAAyC,OAAO,CAAhD,IAAqD,yBAAhE,CAAL;;AAEA,OAAG;AACC,gBAAQ,QAAQ,KAAR,CAAc,EAAd,CAAR;;;;AAIA,YAAI,KAAJ,EAAW;AACP,oBAAQ,MAAM,CAAN,CAAR;;AAEA,sBAAU,yBAAM,OAAN,EAAe,2BAAY,KAAZ,CAAf,CAAV;;AAEA,oBAAQ,oBAAO,KAAP,CAAR;AACH,SAND,MAMO;AACH,oBAAQ,yBAAM,OAAN,EAAe,CAAf,EAAkB,IAAlB,CAAR;AACA,sBAAU,yBAAM,OAAN,EAAe,IAAf,CAAV;AACH;;AAED,eAAO,IAAP,CAAY,KAAZ;AACH,KAjBD,QAiBS,2BAAY,OAAZ,CAjBT;;AAmBA,WAAO,MAAP;AACH,C","file":"wrapWord.js","sourcesContent":["import _ from 'lodash';\nimport slice from 'slice-ansi';\nimport stringWidth from 'string-width';\n\n/**\n * @param {string} input\n * @param {number} size\n * @returns {Array}\n */\nexport default (input, size) => {\n let chunk,\n chunks,\n re,\n subject;\n\n subject = input;\n\n chunks = [];\n\n // https://regex101.com/r/gY5kZ1/1\n re = new RegExp('(^.{1,' + size + '}(\\\\s+|$))|(^.{1,' + (size - 1) + '}(\\\\\\\\|/|_|\\\\.|,|;|\\-))');\n\n do {\n chunk = subject.match(re);\n\n // console.log('chunk', chunk, re);\n\n if (chunk) {\n chunk = chunk[0];\n\n subject = slice(subject, stringWidth(chunk));\n\n chunk = _.trim(chunk);\n } else {\n chunk = slice(subject, 0, size);\n subject = slice(subject, size);\n }\n\n chunks.push(chunk);\n } while (stringWidth(subject));\n\n return chunks;\n};\n"]} \ No newline at end of file diff --git a/tools/eslint/node_modules/table/node_modules/is-fullwidth-code-point/index.js b/tools/eslint/node_modules/table/node_modules/is-fullwidth-code-point/index.js new file mode 100644 index 00000000000000..d506327c3e5576 --- /dev/null +++ b/tools/eslint/node_modules/table/node_modules/is-fullwidth-code-point/index.js @@ -0,0 +1,46 @@ +'use strict'; +/* eslint-disable yoda */ +module.exports = x => { + if (Number.isNaN(x)) { + return false; + } + + // code points are derived from: + // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt + if ( + x >= 0x1100 && ( + x <= 0x115f || // Hangul Jamo + x === 0x2329 || // LEFT-POINTING ANGLE BRACKET + x === 0x232a || // RIGHT-POINTING ANGLE BRACKET + // CJK Radicals Supplement .. Enclosed CJK Letters and Months + (0x2e80 <= x && x <= 0x3247 && x !== 0x303f) || + // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A + (0x3250 <= x && x <= 0x4dbf) || + // CJK Unified Ideographs .. Yi Radicals + (0x4e00 <= x && x <= 0xa4c6) || + // Hangul Jamo Extended-A + (0xa960 <= x && x <= 0xa97c) || + // Hangul Syllables + (0xac00 <= x && x <= 0xd7a3) || + // CJK Compatibility Ideographs + (0xf900 <= x && x <= 0xfaff) || + // Vertical Forms + (0xfe10 <= x && x <= 0xfe19) || + // CJK Compatibility Forms .. Small Form Variants + (0xfe30 <= x && x <= 0xfe6b) || + // Halfwidth and Fullwidth Forms + (0xff01 <= x && x <= 0xff60) || + (0xffe0 <= x && x <= 0xffe6) || + // Kana Supplement + (0x1b000 <= x && x <= 0x1b001) || + // Enclosed Ideographic Supplement + (0x1f200 <= x && x <= 0x1f251) || + // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane + (0x20000 <= x && x <= 0x3fffd) + ) + ) { + return true; + } + + return false; +}; diff --git a/tools/eslint/node_modules/table/node_modules/is-fullwidth-code-point/license b/tools/eslint/node_modules/table/node_modules/is-fullwidth-code-point/license new file mode 100644 index 00000000000000..654d0bfe943437 --- /dev/null +++ b/tools/eslint/node_modules/table/node_modules/is-fullwidth-code-point/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tools/eslint/node_modules/table/node_modules/is-fullwidth-code-point/package.json b/tools/eslint/node_modules/table/node_modules/is-fullwidth-code-point/package.json new file mode 100644 index 00000000000000..4f2674f067ec32 --- /dev/null +++ b/tools/eslint/node_modules/table/node_modules/is-fullwidth-code-point/package.json @@ -0,0 +1,113 @@ +{ + "_args": [ + [ + { + "raw": "is-fullwidth-code-point@^2.0.0", + "scope": null, + "escapedName": "is-fullwidth-code-point", + "name": "is-fullwidth-code-point", + "rawSpec": "^2.0.0", + "spec": ">=2.0.0 <3.0.0", + "type": "range" + }, + "/Users/trott/io.js/tools/node_modules/table/node_modules/string-width" + ] + ], + "_from": "is-fullwidth-code-point@>=2.0.0 <3.0.0", + "_id": "is-fullwidth-code-point@2.0.0", + "_inCache": true, + "_location": "/table/is-fullwidth-code-point", + "_nodeVersion": "4.5.0", + "_npmOperationalInternal": { + "host": "packages-16-east.internal.npmjs.com", + "tmp": "tmp/is-fullwidth-code-point-2.0.0.tgz_1474526567505_0.299921662081033" + }, + "_npmUser": { + "name": "sindresorhus", + "email": "sindresorhus@gmail.com" + }, + "_npmVersion": "3.10.7", + "_phantomChildren": {}, + "_requested": { + "raw": "is-fullwidth-code-point@^2.0.0", + "scope": null, + "escapedName": "is-fullwidth-code-point", + "name": "is-fullwidth-code-point", + "rawSpec": "^2.0.0", + "spec": ">=2.0.0 <3.0.0", + "type": "range" + }, + "_requiredBy": [ + "/table/string-width" + ], + "_resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz", + "_shasum": "a3b30a5c4f199183167aaab93beefae3ddfb654f", + "_shrinkwrap": null, + "_spec": "is-fullwidth-code-point@^2.0.0", + "_where": "/Users/trott/io.js/tools/node_modules/table/node_modules/string-width", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/sindresorhus/is-fullwidth-code-point/issues" + }, + "dependencies": {}, + "description": "Check if the character represented by a given Unicode code point is fullwidth", + "devDependencies": { + "ava": "*", + "xo": "*" + }, + "directories": {}, + "dist": { + "shasum": "a3b30a5c4f199183167aaab93beefae3ddfb654f", + "tarball": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz" + }, + "engines": { + "node": ">=4" + }, + "files": [ + "index.js" + ], + "gitHead": "e94a78056056c5546f2bf4c4cf812a2163a46dae", + "homepage": "https://github.com/sindresorhus/is-fullwidth-code-point#readme", + "keywords": [ + "fullwidth", + "full-width", + "full", + "width", + "unicode", + "character", + "char", + "string", + "str", + "codepoint", + "code", + "point", + "is", + "detect", + "check" + ], + "license": "MIT", + "maintainers": [ + { + "name": "sindresorhus", + "email": "sindresorhus@gmail.com" + } + ], + "name": "is-fullwidth-code-point", + "optionalDependencies": {}, + "readme": "ERROR: No README data found!", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/is-fullwidth-code-point.git" + }, + "scripts": { + "test": "xo && ava" + }, + "version": "2.0.0", + "xo": { + "esnext": true + } +} diff --git a/tools/eslint/node_modules/table/node_modules/is-fullwidth-code-point/readme.md b/tools/eslint/node_modules/table/node_modules/is-fullwidth-code-point/readme.md new file mode 100644 index 00000000000000..093b0281b2c46b --- /dev/null +++ b/tools/eslint/node_modules/table/node_modules/is-fullwidth-code-point/readme.md @@ -0,0 +1,39 @@ +# is-fullwidth-code-point [![Build Status](https://travis-ci.org/sindresorhus/is-fullwidth-code-point.svg?branch=master)](https://travis-ci.org/sindresorhus/is-fullwidth-code-point) + +> Check if the character represented by a given [Unicode code point](https://en.wikipedia.org/wiki/Code_point) is [fullwidth](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms) + + +## Install + +``` +$ npm install --save is-fullwidth-code-point +``` + + +## Usage + +```js +const isFullwidthCodePoint = require('is-fullwidth-code-point'); + +isFullwidthCodePoint('谢'.codePointAt()); +//=> true + +isFullwidthCodePoint('a'.codePointAt()); +//=> false +``` + + +## API + +### isFullwidthCodePoint(input) + +#### input + +Type: `number` + +[Code point](https://en.wikipedia.org/wiki/Code_point) of a character. + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/tools/eslint/node_modules/table/node_modules/string-width/index.js b/tools/eslint/node_modules/table/node_modules/string-width/index.js new file mode 100644 index 00000000000000..25a8943c1dcad6 --- /dev/null +++ b/tools/eslint/node_modules/table/node_modules/string-width/index.js @@ -0,0 +1,35 @@ +'use strict'; +const stripAnsi = require('strip-ansi'); +const isFullwidthCodePoint = require('is-fullwidth-code-point'); + +module.exports = str => { + if (typeof str !== 'string' || str.length === 0) { + return 0; + } + + let width = 0; + + str = stripAnsi(str); + + for (let i = 0; i < str.length; i++) { + const code = str.codePointAt(i); + + // ignore control characters + if (code <= 0x1f || (code >= 0x7f && code <= 0x9f)) { + continue; + } + + // surrogates + if (code >= 0x10000) { + i++; + } + + if (isFullwidthCodePoint(code)) { + width += 2; + } else { + width++; + } + } + + return width; +}; diff --git a/tools/eslint/node_modules/table/node_modules/string-width/license b/tools/eslint/node_modules/table/node_modules/string-width/license new file mode 100644 index 00000000000000..654d0bfe943437 --- /dev/null +++ b/tools/eslint/node_modules/table/node_modules/string-width/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tools/eslint/node_modules/table/node_modules/string-width/package.json b/tools/eslint/node_modules/table/node_modules/string-width/package.json new file mode 100644 index 00000000000000..2fd6a297eb8855 --- /dev/null +++ b/tools/eslint/node_modules/table/node_modules/string-width/package.json @@ -0,0 +1,125 @@ +{ + "_args": [ + [ + { + "raw": "string-width@^2.0.0", + "scope": null, + "escapedName": "string-width", + "name": "string-width", + "rawSpec": "^2.0.0", + "spec": ">=2.0.0 <3.0.0", + "type": "range" + }, + "/Users/trott/io.js/tools/node_modules/table" + ] + ], + "_from": "string-width@>=2.0.0 <3.0.0", + "_id": "string-width@2.0.0", + "_inCache": true, + "_location": "/table/string-width", + "_nodeVersion": "4.5.0", + "_npmOperationalInternal": { + "host": "packages-16-east.internal.npmjs.com", + "tmp": "tmp/string-width-2.0.0.tgz_1474527284011_0.7386264291126281" + }, + "_npmUser": { + "name": "sindresorhus", + "email": "sindresorhus@gmail.com" + }, + "_npmVersion": "3.10.7", + "_phantomChildren": {}, + "_requested": { + "raw": "string-width@^2.0.0", + "scope": null, + "escapedName": "string-width", + "name": "string-width", + "rawSpec": "^2.0.0", + "spec": ">=2.0.0 <3.0.0", + "type": "range" + }, + "_requiredBy": [ + "/table" + ], + "_resolved": "https://registry.npmjs.org/string-width/-/string-width-2.0.0.tgz", + "_shasum": "635c5436cc72a6e0c387ceca278d4e2eec52687e", + "_shrinkwrap": null, + "_spec": "string-width@^2.0.0", + "_where": "/Users/trott/io.js/tools/node_modules/table", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/sindresorhus/string-width/issues" + }, + "dependencies": { + "is-fullwidth-code-point": "^2.0.0", + "strip-ansi": "^3.0.0" + }, + "description": "Get the visual width of a string - the number of columns required to display it", + "devDependencies": { + "ava": "*", + "xo": "*" + }, + "directories": {}, + "dist": { + "shasum": "635c5436cc72a6e0c387ceca278d4e2eec52687e", + "tarball": "https://registry.npmjs.org/string-width/-/string-width-2.0.0.tgz" + }, + "engines": { + "node": ">=4" + }, + "files": [ + "index.js" + ], + "gitHead": "523d7ba4dbb24d40cde88d2c36bb1c7124ab6f82", + "homepage": "https://github.com/sindresorhus/string-width#readme", + "keywords": [ + "string", + "str", + "character", + "char", + "unicode", + "width", + "visual", + "column", + "columns", + "fullwidth", + "full-width", + "full", + "ansi", + "escape", + "codes", + "cli", + "command-line", + "terminal", + "console", + "cjk", + "chinese", + "japanese", + "korean", + "fixed-width" + ], + "license": "MIT", + "maintainers": [ + { + "name": "sindresorhus", + "email": "sindresorhus@gmail.com" + } + ], + "name": "string-width", + "optionalDependencies": {}, + "readme": "ERROR: No README data found!", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/string-width.git" + }, + "scripts": { + "test": "xo && ava" + }, + "version": "2.0.0", + "xo": { + "esnext": true + } +} diff --git a/tools/eslint/node_modules/table/node_modules/string-width/readme.md b/tools/eslint/node_modules/table/node_modules/string-width/readme.md new file mode 100644 index 00000000000000..1ab42c93580ecb --- /dev/null +++ b/tools/eslint/node_modules/table/node_modules/string-width/readme.md @@ -0,0 +1,42 @@ +# string-width [![Build Status](https://travis-ci.org/sindresorhus/string-width.svg?branch=master)](https://travis-ci.org/sindresorhus/string-width) + +> Get the visual width of a string - the number of columns required to display it + +Some Unicode characters are [fullwidth](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms) and use double the normal width. [ANSI escape codes](http://en.wikipedia.org/wiki/ANSI_escape_code) are stripped and doesn't affect the width. + +Useful to be able to measure the actual width of command-line output. + + +## Install + +``` +$ npm install --save string-width +``` + + +## Usage + +```js +const stringWidth = require('string-width'); + +stringWidth('古'); +//=> 2 + +stringWidth('\u001b[1m古\u001b[22m'); +//=> 2 + +stringWidth('a'); +//=> 1 +``` + + +## Related + +- [string-width-cli](https://github.com/sindresorhus/string-width-cli) - CLI for this module +- [string-length](https://github.com/sindresorhus/string-length) - Get the real length of a string +- [widest-line](https://github.com/sindresorhus/widest-line) - Get the visual width of the widest line in a string + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/tools/eslint/node_modules/table/package.json b/tools/eslint/node_modules/table/package.json index fb2f250fa08068..33c29ec498b7ce 100644 --- a/tools/eslint/node_modules/table/package.json +++ b/tools/eslint/node_modules/table/package.json @@ -14,20 +14,22 @@ ] ], "_from": "table@>=3.7.8 <4.0.0", - "_id": "table@3.8.0", + "_id": "table@3.8.3", "_inCache": true, "_location": "/table", - "_nodeVersion": "6.4.0", + "_nodeVersion": "6.8.1", "_npmOperationalInternal": { "host": "packages-16-east.internal.npmjs.com", - "tmp": "tmp/table-3.8.0.tgz_1474139512457_0.8613335366826504" + "tmp": "tmp/table-3.8.3.tgz_1476810452789_0.6529890382662416" }, "_npmUser": { "name": "gajus", "email": "gajus@gajus.com" }, - "_npmVersion": "3.10.3", - "_phantomChildren": {}, + "_npmVersion": "3.10.8", + "_phantomChildren": { + "strip-ansi": "3.0.1" + }, "_requested": { "raw": "table@^3.7.8", "scope": null, @@ -40,8 +42,8 @@ "_requiredBy": [ "/eslint" ], - "_resolved": "https://registry.npmjs.org/table/-/table-3.8.0.tgz", - "_shasum": "252166c7f3286684a9d561b0f3a8929caf3a997b", + "_resolved": "https://registry.npmjs.org/table/-/table-3.8.3.tgz", + "_shasum": "2bbc542f0fda9861a755d3947fefd8b3f513855f", "_shrinkwrap": null, "_spec": "table@^3.7.8", "_where": "/Users/trott/io.js/tools/node_modules/eslint", @@ -59,28 +61,33 @@ "chalk": "^1.1.1", "lodash": "^4.0.0", "slice-ansi": "0.0.4", - "string-width": "^1.0.1" + "string-width": "^2.0.0" }, "description": "Formats data into a string table.", "devDependencies": { + "ajv-cli": "^1.1.0", "babel": "^6.5.2", "babel-cli": "^6.14.0", + "babel-core": "^6.14.0", "babel-plugin-add-module-exports": "^0.2.1", + "babel-plugin-istanbul": "^2.0.3", "babel-preset-es2015-node4": "^2.1.0", "babel-register": "^6.14.0", "chai": "^3.4.1", "eslint": "^3.5.0", "eslint-config-canonical": "^1.8.6", "gitdown": "^2.4.0", + "husky": "^0.11.7", "mocha": "^3.0.2", + "nyc": "^8.3.1", "sinon": "^1.17.2" }, "directories": {}, "dist": { - "shasum": "252166c7f3286684a9d561b0f3a8929caf3a997b", - "tarball": "https://registry.npmjs.org/table/-/table-3.8.0.tgz" + "shasum": "2bbc542f0fda9861a755d3947fefd8b3f513855f", + "tarball": "https://registry.npmjs.org/table/-/table-3.8.3.tgz" }, - "gitHead": "076dd77627213007a989b2c845fa2f3a38896eeb", + "gitHead": "2d1c0d9ebad31f9c76e784e6a88f701de8705005", "homepage": "https://github.com/gajus/table#readme", "keywords": [ "ascii", @@ -98,6 +105,17 @@ } ], "name": "table", + "nyc": { + "include": [ + "src/*.js" + ], + "instrument": false, + "lines": 70, + "require": [ + "babel-register" + ], + "sourceMap": false + }, "optionalDependencies": {}, "readme": "ERROR: No README data found!", "repository": { @@ -105,10 +123,13 @@ "url": "git+https://github.com/gajus/table.git" }, "scripts": { - "build": "babel --copy-files ./src --out-dir ./dist", - "lint": "eslint ./src ./tests", - "readme": "gitdown ./.README/README.md --output-file ./README.md", - "test": "mocha --compilers js:babel-register" + "build": "rm -fr ./dist && babel --copy-files ./src --out-dir ./dist && npm run make-validators", + "lint": "npm run build && eslint ./src ./tests", + "make-readme": "gitdown ./.README/README.md --output-file ./README.md", + "make-validators": "ajv compile --all-errors --inline-refs=false -s src/schemas/config -c ajv-keywords/keywords/typeof -o dist/validateConfig.js && ajv compile --all-errors --inline-refs=false -s src/schemas/streamConfig -c ajv-keywords/keywords/typeof -o dist/validateStreamConfig.js", + "precommit": "npm run lint && npm run test", + "prepublish": "NODE_ENV=production npm run build", + "test": "npm run build && nyc --check-coverage mocha" }, - "version": "3.8.0" + "version": "3.8.3" } diff --git a/tools/eslint/node_modules/tryit/package.json b/tools/eslint/node_modules/tryit/package.json index 7a7a28b076f45c..e0b4e1b8dac03e 100644 --- a/tools/eslint/node_modules/tryit/package.json +++ b/tools/eslint/node_modules/tryit/package.json @@ -14,15 +14,19 @@ ] ], "_from": "tryit@>=1.0.1 <2.0.0", - "_id": "tryit@1.0.2", + "_id": "tryit@1.0.3", "_inCache": true, "_location": "/tryit", - "_nodeVersion": "4.1.0", + "_nodeVersion": "6.8.1", + "_npmOperationalInternal": { + "host": "packages-12-west.internal.npmjs.com", + "tmp": "tmp/tryit-1.0.3.tgz_1477606530482_0.8131801665294915" + }, "_npmUser": { "name": "henrikjoreteg", "email": "henrik@joreteg.com" }, - "_npmVersion": "3.3.8", + "_npmVersion": "3.10.8", "_phantomChildren": {}, "_requested": { "raw": "tryit@^1.0.1", @@ -36,8 +40,8 @@ "_requiredBy": [ "/is-resolvable" ], - "_resolved": "https://registry.npmjs.org/tryit/-/tryit-1.0.2.tgz", - "_shasum": "c196b0073e6b1c595d93c9c830855b7acc32a453", + "_resolved": "https://registry.npmjs.org/tryit/-/tryit-1.0.3.tgz", + "_shasum": "393be730a9446fd1ead6da59a014308f36c289cb", "_shrinkwrap": null, "_spec": "tryit@^1.0.1", "_where": "/Users/trott/io.js/tools/node_modules/is-resolvable", @@ -56,10 +60,13 @@ }, "directories": {}, "dist": { - "shasum": "c196b0073e6b1c595d93c9c830855b7acc32a453", - "tarball": "https://registry.npmjs.org/tryit/-/tryit-1.0.2.tgz" + "shasum": "393be730a9446fd1ead6da59a014308f36c289cb", + "tarball": "https://registry.npmjs.org/tryit/-/tryit-1.0.3.tgz" }, - "gitHead": "b567b4feb491e2ee89addd3d06f66d6ec2217cf5", + "files": [ + "tryit.js" + ], + "gitHead": "706147151922a456988a641b08984b2d1fcf2a86", "homepage": "https://github.com/HenrikJoreteg/tryit#readme", "keywords": [ "errors", @@ -84,5 +91,5 @@ "scripts": { "test": "node test/test.js | tap-spec" }, - "version": "1.0.2" + "version": "1.0.3" } diff --git a/tools/eslint/node_modules/typedarray/package.json b/tools/eslint/node_modules/typedarray/package.json index ab02da539baf7a..19821370412450 100644 --- a/tools/eslint/node_modules/typedarray/package.json +++ b/tools/eslint/node_modules/typedarray/package.json @@ -2,18 +2,18 @@ "_args": [ [ { - "raw": "typedarray@~0.0.5", + "raw": "typedarray@^0.0.6", "scope": null, "escapedName": "typedarray", "name": "typedarray", - "rawSpec": "~0.0.5", - "spec": ">=0.0.5 <0.1.0", + "rawSpec": "^0.0.6", + "spec": ">=0.0.6 <0.0.7", "type": "range" }, "/Users/trott/io.js/tools/node_modules/concat-stream" ] ], - "_from": "typedarray@>=0.0.5 <0.1.0", + "_from": "typedarray@>=0.0.6 <0.0.7", "_id": "typedarray@0.0.6", "_inCache": true, "_location": "/typedarray", @@ -24,12 +24,12 @@ "_npmVersion": "1.4.3", "_phantomChildren": {}, "_requested": { - "raw": "typedarray@~0.0.5", + "raw": "typedarray@^0.0.6", "scope": null, "escapedName": "typedarray", "name": "typedarray", - "rawSpec": "~0.0.5", - "spec": ">=0.0.5 <0.1.0", + "rawSpec": "^0.0.6", + "spec": ">=0.0.6 <0.0.7", "type": "range" }, "_requiredBy": [ @@ -38,7 +38,7 @@ "_resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz", "_shasum": "867ac74e3864187b1d3d47d996a78ec5c8830777", "_shrinkwrap": null, - "_spec": "typedarray@~0.0.5", + "_spec": "typedarray@^0.0.6", "_where": "/Users/trott/io.js/tools/node_modules/concat-stream", "author": { "name": "James Halliday", diff --git a/tools/eslint/package.json b/tools/eslint/package.json index f0155d89330b9c..d6c8d488cb5dfa 100644 --- a/tools/eslint/package.json +++ b/tools/eslint/package.json @@ -2,25 +2,25 @@ "_args": [ [ { - "raw": "eslint", + "raw": "eslint@3.13.0", "scope": null, "escapedName": "eslint", "name": "eslint", - "rawSpec": "", - "spec": "latest", - "type": "tag" + "rawSpec": "3.13.0", + "spec": "3.13.0", + "type": "version" }, "/Users/trott/io.js/tools" ] ], - "_from": "eslint@latest", - "_id": "eslint@3.8.0", + "_from": "eslint@3.13.0", + "_id": "eslint@3.13.0", "_inCache": true, "_location": "/eslint", "_nodeVersion": "4.4.7", "_npmOperationalInternal": { "host": "packages-12-west.internal.npmjs.com", - "tmp": "tmp/eslint-3.8.0.tgz_1476481030547_0.1366094599943608" + "tmp": "tmp/eslint-3.13.0.tgz_1483735229408_0.023912116652354598" }, "_npmUser": { "name": "eslint", @@ -29,21 +29,21 @@ "_npmVersion": "2.15.8", "_phantomChildren": {}, "_requested": { - "raw": "eslint", + "raw": "eslint@3.13.0", "scope": null, "escapedName": "eslint", "name": "eslint", - "rawSpec": "", - "spec": "latest", - "type": "tag" + "rawSpec": "3.13.0", + "spec": "3.13.0", + "type": "version" }, "_requiredBy": [ "#USER" ], - "_resolved": "https://registry.npmjs.org/eslint/-/eslint-3.8.0.tgz", - "_shasum": "4fbbf6833d66654860c23a099c47a0f086de34b7", + "_resolved": "https://registry.npmjs.org/eslint/-/eslint-3.13.0.tgz", + "_shasum": "636925fd163c9babe2e8be7ae43caf518d469577", "_shrinkwrap": null, - "_spec": "eslint", + "_spec": "eslint@3.13.0", "_where": "/Users/trott/io.js/tools", "author": { "name": "Nicholas C. Zakas", @@ -56,6 +56,7 @@ "url": "https://github.com/eslint/eslint/issues/" }, "dependencies": { + "babel-code-frame": "^6.16.0", "chalk": "^1.1.3", "concat-stream": "^1.4.6", "debug": "^2.1.1", @@ -66,8 +67,8 @@ "esutils": "^2.0.2", "file-entry-cache": "^2.0.0", "glob": "^7.0.3", - "globals": "^9.2.0", - "ignore": "^3.1.5", + "globals": "^9.14.0", + "ignore": "^3.2.0", "imurmurhash": "^0.1.4", "inquirer": "^0.12.0", "is-my-json-valid": "^2.10.0", @@ -83,9 +84,9 @@ "pluralize": "^1.2.1", "progress": "^1.1.8", "require-uncached": "^1.0.2", - "shelljs": "^0.6.0", + "shelljs": "^0.7.5", "strip-bom": "^3.0.0", - "strip-json-comments": "~1.0.1", + "strip-json-comments": "~2.0.1", "table": "^3.7.8", "text-table": "~0.2.0", "user-home": "^2.0.0" @@ -118,9 +119,9 @@ "leche": "^2.1.1", "linefix": "^0.1.1", "load-perf": "^0.2.0", - "markdownlint": "^0.2.0", + "markdownlint": "^0.3.1", "mocha": "^2.4.5", - "mock-fs": "^3.10.0", + "mock-fs": "^3.12.1", "npm-license": "^0.3.2", "phantomjs-prebuilt": "^2.1.7", "proxyquire": "^1.7.10", @@ -132,8 +133,8 @@ }, "directories": {}, "dist": { - "shasum": "4fbbf6833d66654860c23a099c47a0f086de34b7", - "tarball": "https://registry.npmjs.org/eslint/-/eslint-3.8.0.tgz" + "shasum": "636925fd163c9babe2e8be7ae43caf518d469577", + "tarball": "https://registry.npmjs.org/eslint/-/eslint-3.13.0.tgz" }, "engines": { "node": ">=4" @@ -146,7 +147,7 @@ "lib", "messages" ], - "gitHead": "82220042725dd0e86b5ddbeac4166e1eb147aa04", + "gitHead": "8571ab82af1d86bf4aa6a9be79ece42493607c69", "homepage": "http://eslint.org", "keywords": [ "ast", @@ -193,5 +194,5 @@ "release": "node Makefile.js release", "test": "node Makefile.js test" }, - "version": "3.8.0" + "version": "3.13.0" } From 8fae9d4cfb7558635eeddcfa9ca1c2bb64d92a73 Mon Sep 17 00:00:00 2001 From: Sakthipriyan Vairamani Date: Wed, 13 Jul 2016 09:27:40 +0530 Subject: [PATCH 169/291] tools: rename eslintrc to an undeprecated format MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit As per ESLint documentation, http://eslint.org/docs/user-guide/configuring#configuration-file-formats the file format .eslintrc is deprecated. This patch just renames the files to .yaml and the structure is already in yaml format. PR-URL: https://github.com/nodejs/node/pull/7699 Reviewed-By: James M Snell Reviewed-By: Colin Ihrig Reviewed-By: Michael Dawson Reviewed-By: Benjamin Gruenbaum Reviewed-By: Michaël Zasso Reviewed-By: Joyee Cheung Reviewed-By: Gibson Fahnestock Reviewed-By: Prince John Wesley Reviewed-By: Johan Bergström Reviewed-By: Rich Trott --- .eslintrc => .eslintrc.yaml | 0 lib/{.eslintrc => .eslintrc.yaml} | 0 test/{.eslintrc => .eslintrc.yaml} | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename .eslintrc => .eslintrc.yaml (100%) rename lib/{.eslintrc => .eslintrc.yaml} (100%) rename test/{.eslintrc => .eslintrc.yaml} (100%) diff --git a/.eslintrc b/.eslintrc.yaml similarity index 100% rename from .eslintrc rename to .eslintrc.yaml diff --git a/lib/.eslintrc b/lib/.eslintrc.yaml similarity index 100% rename from lib/.eslintrc rename to lib/.eslintrc.yaml diff --git a/test/.eslintrc b/test/.eslintrc.yaml similarity index 100% rename from test/.eslintrc rename to test/.eslintrc.yaml From 55377db9b0f323a8d3b8bfe295c97850ef7f2c0c Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Mon, 2 Jan 2017 22:27:40 -0800 Subject: [PATCH 170/291] test: refactor test-stream-transform-object * use common.mustCall() as appropriate * eliminate exit handler * var -> const/let * provide duration for setInterval() PR-URL: https://github.com/nodejs/node/pull/10588 Reviewed-By: Italo A. Casas Reviewed-By: Gibson Fahnestock Reviewed-By: James M Snell Reviewed-By: Sakthipriyan Vairamani --- ...tream-transform-objectmode-falsey-value.js | 35 +++++++++---------- 1 file changed, 16 insertions(+), 19 deletions(-) diff --git a/test/parallel/test-stream-transform-objectmode-falsey-value.js b/test/parallel/test-stream-transform-objectmode-falsey-value.js index 429cc1c960eefb..9a05034b206421 100644 --- a/test/parallel/test-stream-transform-objectmode-falsey-value.js +++ b/test/parallel/test-stream-transform-objectmode-falsey-value.js @@ -1,33 +1,30 @@ 'use strict'; -require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); -var stream = require('stream'); -var PassThrough = stream.PassThrough; +const stream = require('stream'); +const PassThrough = stream.PassThrough; -var src = new PassThrough({ objectMode: true }); -var tx = new PassThrough({ objectMode: true }); -var dest = new PassThrough({ objectMode: true }); +const src = new PassThrough({ objectMode: true }); +const tx = new PassThrough({ objectMode: true }); +const dest = new PassThrough({ objectMode: true }); -var expect = [ -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; -var results = []; -process.on('exit', function() { - assert.deepStrictEqual(results, expect); - console.log('ok'); -}); +const expect = [ -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; +const results = []; -dest.on('data', function(x) { +dest.on('data', common.mustCall(function(x) { results.push(x); -}); +}, expect.length)); src.pipe(tx).pipe(dest); -var i = -1; -var int = setInterval(function() { - if (i > 10) { +let i = -1; +const int = setInterval(common.mustCall(function() { + if (results.length === expect.length) { src.end(); clearInterval(int); + assert.deepStrictEqual(results, expect); } else { src.write(i++); } -}); +}, expect.length + 1), 1); From a06419b0454eced1a3ccd78342c90caaa3f0ab88 Mon Sep 17 00:00:00 2001 From: David Goussev Date: Fri, 30 Dec 2016 19:50:35 -0800 Subject: [PATCH 171/291] test: refactor test-stream2-readable-wrap.js Use common.mustCall() where appropriate, var to const/let, assert.equal() -> assert.strictEqual(), explicit time provided to setTimeout() PR-URL: https://github.com/nodejs/node/pull/10551 Reviewed-By: Rich Trott Reviewed-By: Gibson Fahnestock --- test/parallel/test-stream2-readable-wrap.js | 63 +++++++-------------- 1 file changed, 22 insertions(+), 41 deletions(-) diff --git a/test/parallel/test-stream2-readable-wrap.js b/test/parallel/test-stream2-readable-wrap.js index 0cbd106d5b4b35..aa091dc3d806f0 100644 --- a/test/parallel/test-stream2-readable-wrap.js +++ b/test/parallel/test-stream2-readable-wrap.js @@ -1,77 +1,63 @@ 'use strict'; -require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); +const Readable = require('_stream_readable'); +const Writable = require('_stream_writable'); +const EE = require('events').EventEmitter; -var Readable = require('_stream_readable'); -var Writable = require('_stream_writable'); -var EE = require('events').EventEmitter; - -var testRuns = 0, completedRuns = 0; function runTest(highWaterMark, objectMode, produce) { - testRuns++; - var old = new EE(); - var r = new Readable({ highWaterMark: highWaterMark, - objectMode: objectMode }); - assert.equal(r, r.wrap(old)); + const old = new EE(); + const r = new Readable({ highWaterMark: highWaterMark, + objectMode: objectMode }); + assert.strictEqual(r, r.wrap(old)); - var ended = false; - r.on('end', function() { - ended = true; - }); + r.on('end', common.mustCall(function() {})); old.pause = function() { - console.error('old.pause()'); old.emit('pause'); flowing = false; }; old.resume = function() { - console.error('old.resume()'); old.emit('resume'); flow(); }; - var flowing; - var chunks = 10; - var oldEnded = false; - var expected = []; + let flowing; + let chunks = 10; + let oldEnded = false; + const expected = []; function flow() { flowing = true; while (flowing && chunks-- > 0) { - var item = produce(); + const item = produce(); expected.push(item); - console.log('old.emit', chunks, flowing); old.emit('data', item); - console.log('after emit', chunks, flowing); } if (chunks <= 0) { oldEnded = true; - console.log('old end', chunks, flowing); old.emit('end'); } } - var w = new Writable({ highWaterMark: highWaterMark * 2, - objectMode: objectMode }); - var written = []; + const w = new Writable({ highWaterMark: highWaterMark * 2, + objectMode: objectMode }); + const written = []; w._write = function(chunk, encoding, cb) { - console.log('_write', chunk); written.push(chunk); - setTimeout(cb); + setTimeout(cb, 1); }; - w.on('finish', function() { - completedRuns++; + w.on('finish', common.mustCall(function() { performAsserts(); - }); + })); r.pipe(w); flow(); function performAsserts() { - assert(ended); assert(oldEnded); assert.deepStrictEqual(written, expected); } @@ -81,10 +67,5 @@ runTest(100, false, function() { return Buffer.allocUnsafe(100); }); runTest(10, false, function() { return Buffer.from('xxxxxxxxxx'); }); runTest(1, true, function() { return { foo: 'bar' }; }); -var objectChunks = [ 5, 'a', false, 0, '', 'xyz', { x: 4 }, 7, [], 555 ]; +const objectChunks = [ 5, 'a', false, 0, '', 'xyz', { x: 4 }, 7, [], 555 ]; runTest(1, true, function() { return objectChunks.shift(); }); - -process.on('exit', function() { - assert.equal(testRuns, completedRuns); - console.log('ok'); -}); From 29a4d354bcc25309812e6ea62f994fb725f8c515 Mon Sep 17 00:00:00 2001 From: Sumit Goel Date: Wed, 11 Jan 2017 21:20:09 -0800 Subject: [PATCH 172/291] test: refactor test-cli-eval.js * assert unused vars in test-cli-eval.js * assert in more idiomatic way test-cli-eval * rename status to err in test-cli-eval.js PR-URL: https://github.com/nodejs/node/pull/10759 Reviewed-By: Rich Trott Reviewed-By: James M Snell --- test/parallel/test-cli-eval.js | 39 ++++++++++++++++++++++++---------- 1 file changed, 28 insertions(+), 11 deletions(-) diff --git a/test/parallel/test-cli-eval.js b/test/parallel/test-cli-eval.js index 8db7ad30872223..0ac376d67efecf 100644 --- a/test/parallel/test-cli-eval.js +++ b/test/parallel/test-cli-eval.js @@ -19,6 +19,7 @@ var filename = __filename.replace(/\\/g, '/'); // assert that nothing is written to stdout child.exec(nodejs + ' --eval 42', function(err, stdout, stderr) { + assert.ifError(err); assert.strictEqual(stdout, ''); assert.strictEqual(stderr, ''); }); @@ -26,6 +27,7 @@ child.exec(nodejs + ' --eval 42', // assert that "42\n" is written to stderr child.exec(nodejs + ' --eval "console.error(42)"', function(err, stdout, stderr) { + assert.ifError(err); assert.strictEqual(stdout, ''); assert.strictEqual(stderr, '42\n'); }); @@ -36,12 +38,14 @@ child.exec(nodejs + ' --eval "console.error(42)"', child.exec(cmd + '42', function(err, stdout, stderr) { + assert.ifError(err); assert.strictEqual(stdout, '42\n'); assert.strictEqual(stderr, ''); }); child.exec(cmd + "'[]'", common.mustCall( function(err, stdout, stderr) { + assert.ifError(err); assert.strictEqual(stdout, '[]\n'); assert.strictEqual(stderr, ''); })); @@ -49,31 +53,40 @@ child.exec(nodejs + ' --eval "console.error(42)"', // assert that module loading works child.exec(nodejs + ' --eval "require(\'' + filename + '\')"', - function(status, stdout, stderr) { - assert.strictEqual(status.code, 42); + function(err, stdout, stderr) { + assert.strictEqual(err.code, 42); + assert.strictEqual( + stdout, 'Loaded as a module, exiting with status code 42.\n'); + assert.strictEqual(stderr, ''); }); // Check that builtin modules are pre-defined. child.exec(nodejs + ' --print "os.platform()"', - function(status, stdout, stderr) { + function(err, stdout, stderr) { + assert.ifError(err); assert.strictEqual(stderr, ''); assert.strictEqual(stdout.trim(), require('os').platform()); }); // module path resolve bug, regression test child.exec(nodejs + ' --eval "require(\'./test/parallel/test-cli-eval.js\')"', - function(status, stdout, stderr) { - assert.strictEqual(status.code, 42); + function(err, stdout, stderr) { + assert.strictEqual(err.code, 42); + assert.strictEqual( + stdout, 'Loaded as a module, exiting with status code 42.\n'); + assert.strictEqual(stderr, ''); }); // Missing argument should not crash -child.exec(nodejs + ' -e', common.mustCall(function(status, stdout, stderr) { - assert.notStrictEqual(status, null); - assert.strictEqual(status.code, 9); +child.exec(nodejs + ' -e', common.mustCall(function(err, stdout, stderr) { + assert.strictEqual(err.code, 9); + assert.strictEqual(stdout, ''); + assert(stderr.match(/node: -e requires an argument\n/)); })); // empty program should do nothing -child.exec(nodejs + ' -e ""', function(status, stdout, stderr) { +child.exec(nodejs + ' -e ""', function(err, stdout, stderr) { + assert.ifError(err); assert.strictEqual(stdout, ''); assert.strictEqual(stderr, ''); }); @@ -81,21 +94,25 @@ child.exec(nodejs + ' -e ""', function(status, stdout, stderr) { // "\\-42" should be interpreted as an escaped expression, not a switch child.exec(nodejs + ' -p "\\-42"', function(err, stdout, stderr) { + assert.ifError(err); assert.strictEqual(stdout, '-42\n'); assert.strictEqual(stderr, ''); }); child.exec(nodejs + ' --use-strict -p process.execArgv', - function(status, stdout, stderr) { + function(err, stdout, stderr) { + assert.ifError(err); assert.strictEqual( stdout, "[ '--use-strict', '-p', 'process.execArgv' ]\n" ); + assert.strictEqual(stderr, ''); }); // Regression test for https://github.com/nodejs/node/issues/3574 const emptyFile = path.join(common.fixturesDir, 'empty.js'); child.exec(nodejs + ` -e 'require("child_process").fork("${emptyFile}")'`, - function(status, stdout, stderr) { + function(err, stdout, stderr) { + assert.ifError(err); assert.strictEqual(stdout, ''); assert.strictEqual(stderr, ''); }); From 32da59ab184bfc9a80f2d543eb9cc47097e83a95 Mon Sep 17 00:00:00 2001 From: cjihrig Date: Mon, 16 Jan 2017 16:11:17 -0500 Subject: [PATCH 173/291] test: fix broken assertion This commit fixes a broken assertion in test-cli-eval.js. PR-URL: https://github.com/nodejs/node/pull/10840 Reviewed-By: James M Snell Reviewed-By: Italo A. Casas Reviewed-By: Anna Henningsen --- test/parallel/test-cli-eval.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test/parallel/test-cli-eval.js b/test/parallel/test-cli-eval.js index 0ac376d67efecf..d00092186b8184 100644 --- a/test/parallel/test-cli-eval.js +++ b/test/parallel/test-cli-eval.js @@ -81,7 +81,8 @@ child.exec(nodejs + ' --eval "require(\'./test/parallel/test-cli-eval.js\')"', child.exec(nodejs + ' -e', common.mustCall(function(err, stdout, stderr) { assert.strictEqual(err.code, 9); assert.strictEqual(stdout, ''); - assert(stderr.match(/node: -e requires an argument\n/)); + assert.strictEqual(stderr.trim(), + `${process.execPath}: -e requires an argument`); })); // empty program should do nothing From 807e99b81ddf41c0868a335caa5470d72b9f3e8c Mon Sep 17 00:00:00 2001 From: Adrian Estrada Date: Wed, 11 Jan 2017 22:14:36 -0500 Subject: [PATCH 174/291] test: validate errors in test-buffer-indexof * validate errors in assert.throws * use arrow functions PR-URL: https://github.com/nodejs/node/pull/10752 Reviewed-By: James M Snell Reviewed-By: Luigi Pinca Reviewed-By: Colin Ihrig --- test/parallel/test-buffer-indexof.js | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/test/parallel/test-buffer-indexof.js b/test/parallel/test-buffer-indexof.js index 746a2723167a60..27b71b1b17008a 100644 --- a/test/parallel/test-buffer-indexof.js +++ b/test/parallel/test-buffer-indexof.js @@ -337,15 +337,20 @@ assert.strictEqual(Buffer.from('aaaaa').indexOf('b', 'ucs2'), -1); } } -assert.throws(function() { - b.indexOf(function() { }); -}); -assert.throws(function() { +const argumentExpected = + /^TypeError: "val" argument must be string, number or Buffer$/; + +assert.throws(() => { + b.indexOf(() => { }); +}, argumentExpected); + +assert.throws(() => { b.indexOf({}); -}); -assert.throws(function() { +}, argumentExpected); + +assert.throws(() => { b.indexOf([]); -}); +}, argumentExpected); // All code for handling encodings is shared between Buffer.indexOf and // Buffer.lastIndexOf, so only testing the separate lastIndexOf semantics. From 5250b3358e7036ca7be84782007106d0b582ea99 Mon Sep 17 00:00:00 2001 From: Vse Mozhet Byt Date: Sun, 11 Dec 2016 01:22:04 +0200 Subject: [PATCH 175/291] doc: document argument variant in the repl.md `options` in the `repl.start([options])` can be a string. Ref: https://github.com/nodejs/node/pull/10160 PR-URL: https://github.com/nodejs/node/pull/10221 Reviewed-By: Benjamin Gruenbaum --- doc/api/repl.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/doc/api/repl.md b/doc/api/repl.md index eb32f2c2b2755b..1b03ba47a25d99 100644 --- a/doc/api/repl.md +++ b/doc/api/repl.md @@ -418,6 +418,15 @@ added: v0.1.91 The `repl.start()` method creates and starts a `repl.REPLServer` instance. +If `options` is a string, then it specifies the input prompt: + +```js +const repl = require('repl'); + +// a Unix style prompt +repl.start('$ '); +``` + ## The Node.js REPL Node.js itself uses the `repl` module to provide its own interactive interface From dd9aefde690f5dd7da3cf8e1ce2d5fa03431649e Mon Sep 17 00:00:00 2001 From: cjihrig Date: Fri, 30 Dec 2016 18:38:06 -0500 Subject: [PATCH 176/291] test: use const for all require() calls PR-URL: https://github.com/nodejs/node/pull/10550 Reviewed-By: Rich Trott --- test/addons/async-hello-world/test.js | 2 +- .../hello-world-function-export/test.js | 2 +- test/addons/hello-world/test.js | 2 +- test/addons/load-long-path/test.js | 2 +- test/addons/repl-domain-abort/test.js | 10 +++---- test/debugger/helper-debugger-repl.js | 4 +-- .../test-debugger-repl-break-in-module.js | 2 +- test/debugger/test-debugger-repl-restart.js | 2 +- test/debugger/test-debugger-repl-term.js | 2 +- test/debugger/test-debugger-repl-utf8.js | 2 +- test/debugger/test-debugger-repl.js | 2 +- test/disabled/test-debug-brk-file.js | 10 +++---- test/disabled/test-dgram-send-error.js | 2 +- test/disabled/test-fs-largefile.js | 6 ++-- test/disabled/test-http-abort-stream-end.js | 6 ++-- test/disabled/test-https-loop-to-google.js | 4 +-- test/disabled/test-readline.js | 6 ++-- test/disabled/test-sendfd.js | 14 ++++----- test/disabled/test-setuidgid.js | 4 +-- test/disabled/tls_server.js | 12 ++++---- test/fixtures/GH-892-request.js | 6 ++-- test/fixtures/a.js | 2 +- test/fixtures/a1.js | 2 +- test/fixtures/b/c.js | 6 ++-- test/fixtures/break-in-module/main.js | 2 +- test/fixtures/child-process-spawn-node.js | 2 +- .../child_process_should_emit_error.js | 2 +- test/fixtures/cluster-preload-test.js | 2 +- test/fixtures/cluster-preload.js | 6 ++-- test/fixtures/create-file.js | 2 +- test/fixtures/cycles/folder/foo.js | 2 +- test/fixtures/cycles/root.js | 2 +- test/fixtures/echo-close-check.js | 8 ++--- test/fixtures/echo.js | 4 +-- test/fixtures/listen-on-socket-and-exit.js | 4 +-- test/fixtures/module-require/parent/index.js | 2 +- test/fixtures/node_modules/baz/index.js | 2 +- test/fixtures/node_modules/foo.js | 2 +- test/fixtures/not-main-module.js | 2 +- test/fixtures/parent-process-nonpersistent.js | 2 +- test/fixtures/path-resolve.js | 2 +- test/fixtures/path.js | 2 +- test/fixtures/print-chars-from-buffer.js | 2 +- test/fixtures/print-chars.js | 2 +- test/fixtures/recvfd.js | 2 +- test/fixtures/stdio-filter.js | 2 +- test/fixtures/test-init-native/fs.js | 2 +- test/fixtures/test-regress-GH-4015.js | 2 +- test/fixtures/uncaught-exceptions/domain.js | 2 +- test/gc/node_modules/bindings/README.md | 2 +- test/gc/node_modules/bindings/bindings.js | 2 +- test/gc/node_modules/nan/tools/1to2.js | 2 +- test/gc/node_modules/weak/README.md | 4 +-- test/gc/node_modules/weak/build/Makefile | 2 +- test/gc/node_modules/weak/build/config.gypi | 21 +++++++++---- .../node_modules/weak/build/weakref.target.mk | 30 ++++++++++++------- test/gc/node_modules/weak/lib/weak.js | 4 +-- .../test-dgram-send-cb-quelches-error.js | 8 ++--- test/internet/test-dns-cares-domains.js | 6 ++-- test/internet/test-dns-txt-sigsegv.js | 4 +-- .../internet/test-http-https-default-ports.js | 6 ++-- test/internet/test-net-connect-timeout.js | 4 +-- test/internet/test-net-connect-unref.js | 2 +- .../internet/test-tls-connnect-melissadata.js | 4 +-- test/message/error_exit.js | 2 +- test/message/eval_messages.js | 2 +- test/message/stdin_messages.js | 2 +- .../undefined_reference_in_new_context.js | 2 +- test/message/vm_display_runtime_error.js | 2 +- test/message/vm_display_syntax_error.js | 2 +- test/message/vm_dont_display_runtime_error.js | 2 +- test/message/vm_dont_display_syntax_error.js | 2 +- test/parallel/test-assert.js | 4 +-- test/parallel/test-beforeexit-event-exit.js | 2 +- .../test-child-process-constructor.js | 4 +-- .../test-child-process-default-options.js | 6 ++-- test/parallel/test-child-process-env.js | 6 ++-- test/parallel/test-child-process-exit-code.js | 8 ++--- .../test-child-process-fork-exec-argv.js | 4 +-- .../test-child-process-fork-exec-path.js | 8 ++--- test/parallel/test-child-process-fork-net2.js | 6 ++-- test/parallel/test-child-process-fork-ref.js | 4 +-- test/parallel/test-child-process-fork-ref2.js | 2 +- test/parallel/test-child-process-fork.js | 4 +-- test/parallel/test-child-process-fork3.js | 4 +-- test/parallel/test-child-process-internal.js | 4 +-- .../test-child-process-set-blocking.js | 4 +-- test/parallel/test-child-process-silent.js | 4 +-- .../test-child-process-spawnsync-env.js | 4 +-- .../test-child-process-spawnsync-timeout.js | 4 +-- test/parallel/test-child-process-stdin-ipc.js | 4 +-- .../test-child-process-stdio-inherit.js | 6 ++-- ...test-cluster-disconnect-with-no-workers.js | 4 +-- test/parallel/test-cluster-eaddrinuse.js | 8 ++--- test/parallel/test-cluster-fork-env.js | 4 +-- test/parallel/test-cluster-listening-port.js | 8 ++--- test/parallel/test-cluster-message.js | 8 ++--- .../parallel/test-cluster-rr-domain-listen.js | 8 ++--- test/parallel/test-cluster-send-deadlock.js | 8 ++--- .../test-cluster-setup-master-cumulative.js | 4 +-- .../test-cluster-setup-master-emit.js | 4 +-- .../test-cluster-setup-master-multiple.js | 4 +-- test/parallel/test-cluster-setup-master.js | 4 +-- test/parallel/test-cluster-worker-death.js | 4 +-- test/parallel/test-cluster-worker-destroy.js | 2 +- test/parallel/test-cluster-worker-events.js | 4 +-- .../test-cluster-worker-forced-exit.js | 4 +-- .../test-cluster-worker-isconnected.js | 4 +-- test/parallel/test-cluster-worker-isdead.js | 4 +-- test/parallel/test-cluster-worker-no-exit.js | 6 ++-- .../test-cluster-worker-wait-server-close.js | 8 ++--- test/parallel/test-common.js | 4 +-- .../test-console-not-call-toString.js | 2 +- test/parallel/test-crypto-certificate.js | 8 ++--- test/parallel/test-crypto-dh-odd-key.js | 6 ++-- test/parallel/test-crypto-domain.js | 8 ++--- test/parallel/test-crypto-domains.js | 8 ++--- test/parallel/test-crypto-fips.js | 8 ++--- test/parallel/test-crypto-from-binary.js | 6 ++-- test/parallel/test-crypto-hash.js | 10 +++---- test/parallel/test-crypto-hmac.js | 6 ++-- test/parallel/test-crypto-padding-aes256.js | 6 ++-- test/parallel/test-crypto-rsa-dsa.js | 10 +++---- test/parallel/test-crypto-sign-verify.js | 8 ++--- test/parallel/test-crypto-stream.js | 10 +++---- test/parallel/test-crypto-verify-failure.js | 8 ++--- test/parallel/test-cwd-enoent-repl.js | 8 ++--- test/parallel/test-cwd-enoent.js | 8 ++--- test/parallel/test-debug-port-from-cmdline.js | 6 ++-- test/parallel/test-delayed-require.js | 6 ++-- test/parallel/test-dgram-address.js | 6 ++-- test/parallel/test-dgram-bind.js | 4 +-- test/parallel/test-dgram-bytes-length.js | 4 +-- .../test-dgram-close-is-not-callback.js | 4 +-- test/parallel/test-dgram-implicit-bind.js | 2 +- test/parallel/test-dgram-listen-after-bind.js | 4 +-- test/parallel/test-dgram-oob-buffer.js | 4 +-- test/parallel/test-dgram-ref.js | 2 +- test/parallel/test-dgram-regress-4496.js | 4 +-- .../parallel/test-dgram-send-bad-arguments.js | 4 +-- test/parallel/test-dgram-unref.js | 2 +- test/parallel/test-dh-padding.js | 8 ++--- .../parallel/test-domain-abort-on-uncaught.js | 4 +-- test/parallel/test-domain-crypto.js | 6 ++-- test/parallel/test-domain-enter-exit.js | 4 +-- .../test-domain-exit-dispose-again.js | 4 +-- test/parallel/test-domain-exit-dispose.js | 6 ++-- test/parallel/test-domain-http-server.js | 6 ++-- test/parallel/test-domain-implicit-fs.js | 6 ++-- test/parallel/test-domain-multi.js | 6 ++-- test/parallel/test-domain-nested-throw.js | 6 ++-- test/parallel/test-domain-nested.js | 4 +-- ...in-no-error-handler-abort-on-uncaught-5.js | 2 +- ...in-no-error-handler-abort-on-uncaught-9.js | 2 +- test/parallel/test-domain-safe-exit.js | 4 +-- test/parallel/test-domain-stack.js | 2 +- test/parallel/test-domain-timers.js | 4 +-- ...st-domain-top-level-error-handler-throw.js | 6 ++-- ...domain-with-abort-on-uncaught-exception.js | 4 +-- test/parallel/test-dsa-fips-invalid-key.js | 8 ++--- test/parallel/test-error-reporting.js | 8 ++--- test/parallel/test-event-emitter-errors.js | 4 +-- .../test-event-emitter-get-max-listeners.js | 4 +-- ...st-event-emitter-listeners-side-effects.js | 4 +-- .../test-event-emitter-method-names.js | 4 +-- ...mitter-no-error-provided-to-error-event.js | 6 ++-- test/parallel/test-event-emitter-num-args.js | 4 +-- ...-emitter-set-max-listeners-side-effects.js | 4 +-- test/parallel/test-event-emitter-subclass.js | 6 ++-- test/parallel/test-exception-handler.js | 2 +- test/parallel/test-fs-access.js | 8 ++--- test/parallel/test-fs-exists.js | 4 +-- test/parallel/test-fs-long-path.js | 6 ++-- test/parallel/test-fs-mkdir.js | 6 ++-- test/parallel/test-fs-null-bytes.js | 6 ++-- test/parallel/test-fs-open-flags.js | 4 +-- test/parallel/test-fs-read-stream-fd.js | 6 ++-- .../test-fs-readfile-zero-byte-liar.js | 4 +-- test/parallel/test-fs-sir-writes-alot.js | 8 ++--- test/parallel/test-fs-stat.js | 4 +-- test/parallel/test-fs-stream-double-close.js | 4 +-- .../test-fs-symlink-dir-junction-relative.js | 8 ++--- test/parallel/test-fs-sync-fd-leak.js | 4 +-- test/parallel/test-fs-truncate-GH-6233.js | 6 ++-- test/parallel/test-fs-utimes.js | 8 ++--- test/parallel/test-fs-write-file-buffer.js | 8 ++--- test/parallel/test-fs-write-file-sync.js | 8 ++--- test/parallel/test-fs-write-stream-end.js | 8 ++--- test/parallel/test-fs-write-stream-err.js | 6 ++-- test/parallel/test-fs-write-string-coerce.js | 10 +++---- test/parallel/test-global.js | 4 +-- test/parallel/test-http-1.0-keep-alive.js | 4 +-- test/parallel/test-http-1.0.js | 8 ++--- test/parallel/test-http-abort-before-end.js | 4 +-- test/parallel/test-http-abort-client.js | 2 +- .../test-http-agent-destroyed-socket.js | 4 +-- .../parallel/test-http-agent-error-on-idle.js | 4 +-- test/parallel/test-http-agent-false.js | 4 +-- test/parallel/test-http-agent-maxsockets.js | 4 +-- test/parallel/test-http-agent-no-protocol.js | 4 +-- test/parallel/test-http-agent-null.js | 2 +- test/parallel/test-http-agent.js | 4 +-- test/parallel/test-http-automatic-headers.js | 4 +-- test/parallel/test-http-blank-header.js | 6 ++-- test/parallel/test-http-buffer-sanity.js | 4 +-- test/parallel/test-http-byteswritten.js | 4 +-- test/parallel/test-http-chunked-304.js | 8 ++--- test/parallel/test-http-chunked.js | 4 +-- test/parallel/test-http-client-abort-event.js | 2 +- test/parallel/test-http-client-abort2.js | 2 +- test/parallel/test-http-client-agent.js | 4 +-- .../test-http-client-default-headers-exist.js | 4 +-- test/parallel/test-http-client-encoding.js | 2 +- test/parallel/test-http-client-get-url.js | 4 +-- test/parallel/test-http-client-parse-error.js | 6 ++-- test/parallel/test-http-client-pipe-end.js | 4 +-- test/parallel/test-http-client-race-2.js | 6 ++-- test/parallel/test-http-client-race.js | 6 ++-- .../test-http-client-read-in-error.js | 6 ++-- .../test-http-client-timeout-agent.js | 4 +-- test/parallel/test-http-client-timeout.js | 4 +-- test/parallel/test-http-client-upload-buf.js | 4 +-- test/parallel/test-http-client-upload.js | 4 +-- test/parallel/test-http-conn-reset.js | 6 ++-- test/parallel/test-http-content-length.js | 4 +-- test/parallel/test-http-contentLength0.js | 2 +- test/parallel/test-http-date-header.js | 4 +-- test/parallel/test-http-default-encoding.js | 4 +-- test/parallel/test-http-default-port.js | 13 ++++---- .../test-http-destroyed-socket-write2.js | 6 ++-- test/parallel/test-http-dns-error.js | 12 ++++---- test/parallel/test-http-eof-on-connect.js | 4 +-- test/parallel/test-http-exceptions.js | 2 +- test/parallel/test-http-expect-continue.js | 4 +-- test/parallel/test-http-extra-response.js | 6 ++-- test/parallel/test-http-flush.js | 2 +- test/parallel/test-http-full-response.js | 8 ++--- .../test-http-get-pipeline-problem.js | 8 ++--- test/parallel/test-http-head-request.js | 2 +- ...test-http-head-response-has-no-body-end.js | 2 +- .../test-http-head-response-has-no-body.js | 2 +- test/parallel/test-http-header-read.js | 4 +-- test/parallel/test-http-hex-write.js | 4 +-- .../test-http-keep-alive-close-on-header.js | 4 +-- test/parallel/test-http-keepalive-client.js | 4 +-- .../test-http-keepalive-maxsockets.js | 4 +-- test/parallel/test-http-keepalive-request.js | 4 +-- .../test-http-localaddress-bind-error.js | 2 +- test/parallel/test-http-malformed-request.js | 8 ++--- .../test-http-many-ended-pipelines.js | 4 +-- test/parallel/test-http-max-headers-count.js | 4 +-- test/parallel/test-http-methods.js | 6 ++-- test/parallel/test-http-multi-line-headers.js | 6 ++-- test/parallel/test-http-mutable-headers.js | 4 +-- test/parallel/test-http-no-content-length.js | 6 ++-- test/parallel/test-http-outgoing-finish.js | 4 +-- test/parallel/test-http-parser-bad-ref.js | 2 +- test/parallel/test-http-parser-free.js | 4 +-- test/parallel/test-http-parser.js | 2 +- test/parallel/test-http-pause.js | 4 +-- test/parallel/test-http-pipe-fs.js | 8 ++--- test/parallel/test-http-proxy.js | 6 ++-- test/parallel/test-http-raw-headers.js | 4 +-- .../test-http-remove-header-stays-removed.js | 4 +-- test/parallel/test-http-request-end-twice.js | 4 +-- test/parallel/test-http-request-end.js | 4 +-- test/parallel/test-http-request-methods.js | 6 ++-- .../parallel/test-http-res-write-after-end.js | 4 +-- ...test-http-res-write-end-dont-take-array.js | 4 +-- test/parallel/test-http-response-close.js | 2 +- .../parallel/test-http-response-no-headers.js | 6 ++-- test/parallel/test-http-response-readable.js | 4 +-- .../test-http-response-status-message.js | 6 ++-- .../parallel/test-http-server-multiheaders.js | 4 +-- .../test-http-server-multiheaders2.js | 4 +-- test/parallel/test-http-server-stale-close.js | 6 ++-- test/parallel/test-http-server-unconsume.js | 6 ++-- test/parallel/test-http-server.js | 10 +++---- test/parallel/test-http-set-cookies.js | 4 +-- test/parallel/test-http-set-timeout-server.js | 8 ++--- test/parallel/test-http-set-trailers.js | 8 ++--- test/parallel/test-http-should-keep-alive.js | 6 ++-- test/parallel/test-http-status-code.js | 4 +-- test/parallel/test-http-status-message.js | 6 ++-- test/parallel/test-http-timeout-overflow.js | 4 +-- test/parallel/test-http-timeout.js | 2 +- test/parallel/test-http-upgrade-agent.js | 8 ++--- test/parallel/test-http-upgrade-client.js | 8 ++--- test/parallel/test-http-upgrade-client2.js | 2 +- test/parallel/test-http-upgrade-server.js | 8 ++--- test/parallel/test-http-upgrade-server2.js | 6 ++-- ...p-url.parse-auth-with-header-in-request.js | 6 ++-- test/parallel/test-http-url.parse-auth.js | 6 ++-- test/parallel/test-http-url.parse-basic.js | 6 ++-- .../test-http-url.parse-https.request.js | 10 +++---- ....parse-only-support-http-https-protocol.js | 6 ++-- test/parallel/test-http-url.parse-path.js | 6 ++-- test/parallel/test-http-url.parse-post.js | 6 ++-- test/parallel/test-http-url.parse-search.js | 6 ++-- test/parallel/test-http-wget.js | 6 ++-- test/parallel/test-http-write-callbacks.js | 4 +-- test/parallel/test-http-write-empty-string.js | 4 +-- test/parallel/test-http-write-head.js | 4 +-- test/parallel/test-http-zero-length-write.js | 6 ++-- test/parallel/test-https-agent-servername.js | 6 ++-- test/parallel/test-https-byteswritten.js | 8 ++--- .../test-https-client-checkServerIdentity.js | 10 +++---- test/parallel/test-https-client-get-url.js | 6 ++-- test/parallel/test-https-client-reject.js | 10 +++---- test/parallel/test-https-client-resume.js | 10 +++---- .../parallel/test-https-connecting-to-http.js | 6 ++-- test/parallel/test-https-drain.js | 10 +++---- test/parallel/test-https-eof-for-eom.js | 10 +++---- test/parallel/test-https-foafssl.js | 12 ++++---- test/parallel/test-https-host-headers.js | 6 ++-- .../test-https-localaddress-bind-error.js | 6 ++-- test/parallel/test-https-localaddress.js | 2 +- test/parallel/test-https-pfx.js | 8 ++--- test/parallel/test-https-req-split.js | 6 ++-- .../parallel/test-https-resume-after-renew.js | 6 ++-- .../parallel/test-https-set-timeout-server.js | 10 +++---- test/parallel/test-https-socket-options.js | 8 ++--- test/parallel/test-https-strict.js | 8 ++--- test/parallel/test-https-timeout-server-2.js | 10 +++---- test/parallel/test-internal-modules-expose.js | 2 +- test/parallel/test-listen-fd-cluster.js | 12 ++++---- .../test-listen-fd-detached-inherit.js | 10 +++---- test/parallel/test-listen-fd-detached.js | 12 ++++---- test/parallel/test-listen-fd-server.js | 10 +++---- test/parallel/test-memory-usage-emfile.js | 4 +-- test/parallel/test-memory-usage.js | 2 +- ...test-microtask-queue-integration-domain.js | 2 +- .../test-microtask-queue-integration.js | 2 +- .../test-microtask-queue-run-domain.js | 2 +- ...st-microtask-queue-run-immediate-domain.js | 2 +- .../test-microtask-queue-run-immediate.js | 2 +- test/parallel/test-microtask-queue-run.js | 2 +- .../test-module-globalpaths-nodepath.js | 17 +++++------ test/parallel/test-module-loading-error.js | 2 +- test/parallel/test-module-version.js | 2 +- test/parallel/test-net-after-close.js | 4 +-- .../test-net-better-error-messages-path.js | 6 ++-- test/parallel/test-net-bind-twice.js | 4 +-- test/parallel/test-net-buffersize.js | 4 +-- test/parallel/test-net-bytes-stats.js | 4 +-- test/parallel/test-net-can-reset-timeout.js | 2 +- test/parallel/test-net-connect-buffer.js | 4 +-- test/parallel/test-net-connect-options.js | 4 +-- .../test-net-connect-paused-connection.js | 2 +- test/parallel/test-net-dns-custom-lookup.js | 6 ++-- test/parallel/test-net-dns-error.js | 4 +-- test/parallel/test-net-dns-lookup-skip.js | 4 +-- test/parallel/test-net-dns-lookup.js | 4 +-- test/parallel/test-net-during-close.js | 4 +-- test/parallel/test-net-eaddrinuse.js | 4 +-- test/parallel/test-net-end-without-connect.js | 2 +- test/parallel/test-net-isip.js | 4 +-- test/parallel/test-net-large-string.js | 4 +-- ...n-close-server-callback-is-not-function.js | 2 +- test/parallel/test-net-listen-close-server.js | 2 +- test/parallel/test-net-listen-error.js | 2 +- .../test-net-listen-exclusive-random-ports.js | 6 ++-- test/parallel/test-net-listen-shared-ports.js | 8 ++--- test/parallel/test-net-localport.js | 6 ++-- .../parallel/test-net-persistent-keepalive.js | 4 +-- test/parallel/test-net-persistent-nodelay.js | 4 +-- .../parallel/test-net-persistent-ref-unref.js | 4 +-- test/parallel/test-net-reconnect.js | 4 +-- test/parallel/test-net-server-bind.js | 6 ++-- test/parallel/test-net-server-close.js | 4 +-- test/parallel/test-net-server-connections.js | 4 +-- .../test-net-server-listen-remove-callback.js | 4 +-- ...-connections-close-makes-more-available.js | 4 +-- .../test-net-server-unref-persistent.js | 2 +- test/parallel/test-net-server-unref.js | 2 +- .../parallel/test-net-socket-destroy-twice.js | 4 +-- test/parallel/test-net-stream.js | 4 +-- test/parallel/test-net-write-after-close.js | 2 +- test/parallel/test-net-write-connect-write.js | 4 +-- test/parallel/test-net-write-slow.js | 4 +-- test/parallel/test-next-tick-domain.js | 2 +- test/parallel/test-next-tick-errors.js | 2 +- .../test-next-tick-intentional-starvation.js | 2 +- test/parallel/test-next-tick-ordering.js | 2 +- test/parallel/test-next-tick-ordering2.js | 2 +- test/parallel/test-next-tick.js | 2 +- test/parallel/test-path-makelong.js | 4 +-- test/parallel/test-pipe-address.js | 6 ++-- test/parallel/test-pipe-return-val.js | 4 +-- test/parallel/test-pipe-stream.js | 6 ++-- test/parallel/test-pipe-unref.js | 4 +-- test/parallel/test-process-argv-0.js | 6 ++-- test/parallel/test-process-before-exit.js | 2 +- test/parallel/test-process-binding.js | 2 +- test/parallel/test-process-config.js | 6 ++-- test/parallel/test-process-exec-argv.js | 4 +-- test/parallel/test-process-exit-code.js | 4 +-- .../test-process-exit-from-before-exit.js | 2 +- test/parallel/test-process-exit-recursive.js | 2 +- test/parallel/test-process-exit.js | 2 +- test/parallel/test-process-getgroups.js | 4 +-- test/parallel/test-process-hrtime.js | 2 +- test/parallel/test-process-kill-null.js | 4 +-- test/parallel/test-process-kill-pid.js | 2 +- test/parallel/test-process-raw-debug.js | 6 ++-- test/parallel/test-process-wrap.js | 2 +- .../test-promises-unhandled-rejections.js | 6 ++-- test/parallel/test-querystring.js | 6 ++-- test/parallel/test-readline-keys.js | 10 +++---- test/parallel/test-readline-set-raw-mode.js | 6 ++-- test/parallel/test-ref-unref-return.js | 6 ++-- test/parallel/test-regress-GH-1531.js | 6 ++-- test/parallel/test-regress-GH-1899.js | 6 ++-- test/parallel/test-regress-GH-2245.js | 2 +- test/parallel/test-regress-GH-4948.js | 4 +-- test/parallel/test-regress-GH-5927.js | 4 +-- test/parallel/test-regress-GH-6235.js | 2 +- test/parallel/test-regress-GH-746.js | 2 +- test/parallel/test-regress-GH-819.js | 2 +- test/parallel/test-regress-GH-node-9326.js | 4 +-- test/parallel/test-repl-.save.load.js | 8 ++--- test/parallel/test-repl-autolibs.js | 6 ++-- test/parallel/test-repl-domain.js | 4 +-- test/parallel/test-repl-harmony.js | 4 +-- .../test-repl-syntax-error-handling.js | 6 ++-- test/parallel/test-repl-tab.js | 6 ++-- .../test-repl-unexpected-token-recoverable.js | 4 +-- test/parallel/test-require-cache.js | 2 +- ...ons-same-filename-as-dir-trailing-slash.js | 6 ++-- test/parallel/test-require-process.js | 4 +-- test/parallel/test-sigint-infinite-loop.js | 4 +-- test/parallel/test-signal-safety.js | 2 +- .../test-socket-write-after-fin-error.js | 4 +-- test/parallel/test-socket-write-after-fin.js | 4 +-- test/parallel/test-stdin-pipe-resume.js | 4 +-- test/parallel/test-stdio-readable-writable.js | 2 +- ...out-cannot-be-closed-child-process-pipe.js | 4 +-- test/parallel/test-stdout-stderr-reading.js | 6 ++-- test/parallel/test-stream-pipe-event.js | 6 ++-- test/parallel/test-stream-push-order.js | 4 +-- test/parallel/test-stream-push-strings.js | 6 ++-- ...stream-readable-constructor-set-methods.js | 4 +-- .../test-stream-readable-flow-recursion.js | 4 +-- ...tream-transform-constructor-set-methods.js | 4 +-- .../test-stream-transform-split-objectmode.js | 4 +-- .../test-stream-unshift-empty-chunk.js | 4 +-- ...stream-writable-change-default-encoding.js | 6 ++-- ...stream-writable-constructor-set-methods.js | 4 +-- .../test-stream-writable-decoded-encoding.js | 6 ++-- test/parallel/test-stream-writev.js | 4 +-- ...est-stream2-base64-single-char-read-end.js | 6 ++-- test/parallel/test-stream2-compatibility.js | 8 ++--- test/parallel/test-stream2-finish-pipe.js | 4 +-- .../test-stream2-httpclient-response-end.js | 4 +-- .../parallel/test-stream2-large-read-stall.js | 4 +-- test/parallel/test-stream2-objects.js | 6 ++-- .../test-stream2-pipe-error-handling.js | 4 +-- .../test-stream2-pipe-error-once-listener.js | 4 +-- test/parallel/test-stream2-push.js | 11 ++++--- test/parallel/test-stream2-read-sync-stack.js | 2 +- .../test-stream2-readable-from-list.js | 6 ++-- .../test-stream2-readable-legacy-drain.js | 4 +-- .../test-stream2-readable-non-empty-end.js | 4 +-- .../test-stream2-readable-wrap-empty.js | 4 +-- test/parallel/test-stream2-set-encoding.js | 6 ++-- test/parallel/test-stream2-transform.js | 6 ++-- test/parallel/test-stream2-unpipe-leak.js | 6 ++-- test/parallel/test-stream2-writable.js | 8 ++--- test/parallel/test-stream3-pause-then-read.js | 4 +-- test/parallel/test-string-decoder-end.js | 4 +-- test/parallel/test-string-decoder.js | 6 ++-- test/parallel/test-stringbytes-external.js | 2 +- test/parallel/test-sys.js | 6 ++-- test/parallel/test-tcp-wrap-connect.js | 4 +-- test/parallel/test-tcp-wrap.js | 2 +- test/parallel/test-timer-close.js | 2 +- test/parallel/test-timers-args.js | 2 +- test/parallel/test-timers-immediate-queue.js | 2 +- test/parallel/test-timers-ordering.js | 2 +- .../test-timers-uncaught-exception.js | 2 +- test/parallel/test-timers-unref-leak.js | 2 +- test/parallel/test-timers-unref.js | 2 +- test/parallel/test-timers.js | 2 +- test/parallel/test-tls-alert.js | 10 +++---- .../test-tls-async-cb-after-socket-end.js | 2 +- test/parallel/test-tls-cert-regression.js | 4 +-- test/parallel/test-tls-client-abort.js | 10 +++---- test/parallel/test-tls-client-abort2.js | 6 ++-- .../test-tls-client-default-ciphers.js | 4 +-- test/parallel/test-tls-client-destroy-soon.js | 8 ++--- test/parallel/test-tls-client-mindhsize.js | 8 ++--- test/parallel/test-tls-client-resume.js | 8 ++--- test/parallel/test-tls-close-error.js | 6 ++-- test/parallel/test-tls-close-notify.js | 6 ++-- test/parallel/test-tls-connect-no-host.js | 10 +++---- test/parallel/test-tls-connect-pipe.js | 6 ++-- test/parallel/test-tls-connect.js | 10 +++---- .../parallel/test-tls-delayed-attach-error.js | 8 ++--- test/parallel/test-tls-delayed-attach.js | 10 +++---- test/parallel/test-tls-dhe.js | 10 +++---- test/parallel/test-tls-ecdh-disable.js | 10 +++---- test/parallel/test-tls-econnreset.js | 6 ++-- test/parallel/test-tls-fast-writing.js | 8 ++--- test/parallel/test-tls-handshake-error.js | 6 ++-- test/parallel/test-tls-handshake-nohang.js | 4 +-- test/parallel/test-tls-honorcipherorder.js | 8 ++--- test/parallel/test-tls-invoke-queued.js | 8 ++--- test/parallel/test-tls-js-stream.js | 12 ++++---- test/parallel/test-tls-legacy-onselect.js | 6 ++-- test/parallel/test-tls-max-send-fragment.js | 8 ++--- test/parallel/test-tls-multi-key.js | 8 ++--- test/parallel/test-tls-no-rsa-key.js | 8 ++--- test/parallel/test-tls-no-sslv23.js | 6 ++-- test/parallel/test-tls-npn-server-client.js | 2 +- test/parallel/test-tls-over-http-tunnel.js | 12 ++++---- test/parallel/test-tls-pause.js | 10 +++---- .../test-tls-peer-certificate-encoding.js | 12 ++++---- .../test-tls-peer-certificate-multi-keys.js | 12 ++++---- test/parallel/test-tls-request-timeout.js | 8 ++--- test/parallel/test-tls-securepair-server.js | 14 ++++----- test/parallel/test-tls-sni-option.js | 2 +- test/parallel/test-tls-sni-server-client.js | 2 +- test/parallel/test-umask.js | 4 +-- test/parallel/test-utf8-scripts.js | 2 +- test/parallel/test-util-inspect.js | 12 ++++---- test/parallel/test-util-log.js | 4 +-- test/parallel/test-v8-flag-type-check.js | 4 +-- test/parallel/test-v8-flags.js | 6 ++-- test/parallel/test-v8-stats.js | 4 +-- test/parallel/test-vm-basic.js | 4 +-- test/parallel/test-vm-cached-data.js | 4 +-- test/parallel/test-vm-context-async-script.js | 4 +-- .../test-vm-context-property-forwarding.js | 4 +-- test/parallel/test-vm-context.js | 6 ++-- .../test-vm-create-and-run-in-context.js | 4 +-- .../test-vm-create-context-accessors.js | 4 +-- test/parallel/test-vm-create-context-arg.js | 4 +-- ...st-vm-create-context-circular-reference.js | 4 +-- test/parallel/test-vm-cross-context.js | 4 +-- test/parallel/test-vm-function-declaration.js | 4 +-- .../test-vm-global-define-property.js | 4 +-- test/parallel/test-vm-global-identity.js | 4 +-- test/parallel/test-vm-harmony-symbols.js | 4 +-- test/parallel/test-vm-is-context.js | 4 +-- test/parallel/test-vm-proxies.js | 4 +-- test/parallel/test-vm-static-this.js | 6 ++-- test/parallel/test-vm-syntax-error-message.js | 4 +-- test/parallel/test-vm-timeout.js | 4 +-- test/parallel/test-zerolengthbufferbug.js | 2 +- test/pummel/test-abort-fatal-error.js | 4 +-- test/pummel/test-child-process-spawn-loop.js | 6 ++-- test/pummel/test-dh-regr.js | 6 ++-- test/pummel/test-dtrace-jsstack.js | 6 ++-- test/pummel/test-exec.js | 6 ++-- test/pummel/test-fs-watch-file-slow.js | 8 ++--- test/pummel/test-fs-watch-file.js | 8 ++--- test/pummel/test-fs-watch-non-recursive.js | 6 ++-- .../test-http-many-keep-alive-connections.js | 6 ++-- test/pummel/test-https-ci-reneg-attack.js | 12 ++++---- test/pummel/test-https-large-response.js | 8 ++--- test/pummel/test-https-no-reader.js | 12 ++++---- test/pummel/test-keep-alive.js | 10 +++---- test/pummel/test-net-connect-econnrefused.js | 6 ++-- test/pummel/test-net-connect-memleak.js | 6 ++-- test/pummel/test-net-many-clients.js | 6 ++-- test/pummel/test-net-pause.js | 6 ++-- test/pummel/test-net-pingpong-delay.js | 6 ++-- test/pummel/test-net-pingpong.js | 6 ++-- test/pummel/test-net-timeout.js | 6 ++-- test/pummel/test-net-timeout2.js | 4 +-- test/pummel/test-net-write-callbacks.js | 6 ++-- test/pummel/test-process-hrtime.js | 2 +- test/pummel/test-process-uptime.js | 2 +- test/pummel/test-regress-GH-814.js | 6 ++-- test/pummel/test-regress-GH-814_2.js | 8 ++--- test/pummel/test-regress-GH-892.js | 13 ++++---- test/pummel/test-stream-pipe-multi.js | 4 +-- test/pummel/test-stream2-basic.js | 8 ++--- test/pummel/test-timers.js | 2 +- test/pummel/test-tls-ci-reneg-attack.js | 10 +++---- test/pummel/test-tls-connect-memleak.js | 8 ++--- test/pummel/test-tls-securepair-client.js | 14 ++++----- test/pummel/test-tls-server-large-request.js | 12 ++++---- test/pummel/test-tls-session-timeout.js | 12 ++++---- test/pummel/test-tls-throttle.js | 8 ++--- test/pummel/test-vm-memleak.js | 2 +- test/pummel/test-watch-file.js | 8 ++--- .../sequential/test-child-process-execsync.js | 8 ++--- test/sequential/test-debugger-debug-brk.js | 6 ++-- test/sequential/test-module-loading.js | 30 +++++++++---------- test/sequential/test-net-GH-5504.js | 8 ++--- test/sequential/test-regress-GH-1726.js | 4 +-- test/sequential/test-regress-GH-4015.js | 6 ++-- test/sequential/test-regress-GH-4027.js | 8 ++--- test/sequential/test-regress-GH-784.js | 6 ++-- test/sequential/test-regress-GH-877.js | 6 ++-- test/sequential/test-repl-timeout-throw.js | 2 +- .../test-require-cache-without-stat.js | 6 ++-- test/sequential/test-stream2-fs.js | 12 ++++---- test/sequential/test-stream2-stderr-sync.js | 6 ++-- test/sequential/test-util-debug.js | 6 ++-- test/sequential/test-vm-timeout-rethrow.js | 6 ++-- test/timers/test-timers-reliability.js | 2 +- 603 files changed, 1567 insertions(+), 1546 deletions(-) diff --git a/test/addons/async-hello-world/test.js b/test/addons/async-hello-world/test.js index 7c27382c1c60f4..a6aa8aa20fffbc 100644 --- a/test/addons/async-hello-world/test.js +++ b/test/addons/async-hello-world/test.js @@ -1,6 +1,6 @@ 'use strict'; const common = require('../../common'); -var assert = require('assert'); +const assert = require('assert'); const binding = require(`./build/${common.buildType}/binding`); binding(5, common.mustCall(function(err, val) { diff --git a/test/addons/hello-world-function-export/test.js b/test/addons/hello-world-function-export/test.js index 74ea66c79c548c..173cf5428e086f 100644 --- a/test/addons/hello-world-function-export/test.js +++ b/test/addons/hello-world-function-export/test.js @@ -1,6 +1,6 @@ 'use strict'; const common = require('../../common'); -var assert = require('assert'); +const assert = require('assert'); const binding = require(`./build/${common.buildType}/binding`); assert.strictEqual(binding(), 'world'); console.log('binding.hello() =', binding()); diff --git a/test/addons/hello-world/test.js b/test/addons/hello-world/test.js index 32066388efe6cb..b0148e9d9e9014 100644 --- a/test/addons/hello-world/test.js +++ b/test/addons/hello-world/test.js @@ -1,6 +1,6 @@ 'use strict'; const common = require('../../common'); -var assert = require('assert'); +const assert = require('assert'); const binding = require(`./build/${common.buildType}/binding`); assert.strictEqual(binding.hello(), 'world'); console.log('binding.hello() =', binding.hello()); diff --git a/test/addons/load-long-path/test.js b/test/addons/load-long-path/test.js index b17942b45a6f34..6e540fea559450 100644 --- a/test/addons/load-long-path/test.js +++ b/test/addons/load-long-path/test.js @@ -32,6 +32,6 @@ var contents = fs.readFileSync(addonPath); fs.writeFileSync(addonDestinationPath, contents); // Attempt to load at long path destination -var addon = require(addonDestinationPath); +const addon = require(addonDestinationPath); assert.notEqual(addon, null); assert.strictEqual(addon.hello(), 'world'); diff --git a/test/addons/repl-domain-abort/test.js b/test/addons/repl-domain-abort/test.js index 5591b4f2b38e90..1f30f0f9beae54 100644 --- a/test/addons/repl-domain-abort/test.js +++ b/test/addons/repl-domain-abort/test.js @@ -1,9 +1,9 @@ 'use strict'; -var common = require('../../common'); -var assert = require('assert'); -var repl = require('repl'); -var stream = require('stream'); -var path = require('path'); +const common = require('../../common'); +const assert = require('assert'); +const repl = require('repl'); +const stream = require('stream'); +const path = require('path'); var buildType = process.config.target_defaults.default_configuration; var buildPath = path.join(__dirname, 'build', buildType, 'binding'); // On Windows, escape backslashes in the path before passing it to REPL. diff --git a/test/debugger/helper-debugger-repl.js b/test/debugger/helper-debugger-repl.js index 602ab1c05e53d6..d6c3e5ca9e609a 100644 --- a/test/debugger/helper-debugger-repl.js +++ b/test/debugger/helper-debugger-repl.js @@ -1,7 +1,7 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); -var spawn = require('child_process').spawn; +const assert = require('assert'); +const spawn = require('child_process').spawn; process.env.NODE_DEBUGGER_TIMEOUT = 2000; var port = common.PORT; diff --git a/test/debugger/test-debugger-repl-break-in-module.js b/test/debugger/test-debugger-repl-break-in-module.js index 91782ae6e3ef28..2e7b9a58aacb0e 100644 --- a/test/debugger/test-debugger-repl-break-in-module.js +++ b/test/debugger/test-debugger-repl-break-in-module.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var repl = require('./helper-debugger-repl.js'); +const repl = require('./helper-debugger-repl.js'); repl.startDebugger('break-in-module/main.js'); diff --git a/test/debugger/test-debugger-repl-restart.js b/test/debugger/test-debugger-repl-restart.js index 206cd2e7417627..7dbef4288a6f44 100644 --- a/test/debugger/test-debugger-repl-restart.js +++ b/test/debugger/test-debugger-repl-restart.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var repl = require('./helper-debugger-repl.js'); +const repl = require('./helper-debugger-repl.js'); repl.startDebugger('breakpoints.js'); var linesWithBreakpoint = [ diff --git a/test/debugger/test-debugger-repl-term.js b/test/debugger/test-debugger-repl-term.js index 6872f6ce2f9c72..8c44372f681672 100644 --- a/test/debugger/test-debugger-repl-term.js +++ b/test/debugger/test-debugger-repl-term.js @@ -2,7 +2,7 @@ require('../common'); process.env.NODE_FORCE_READLINE = 1; -var repl = require('./helper-debugger-repl.js'); +const repl = require('./helper-debugger-repl.js'); repl.startDebugger('breakpoints.js'); diff --git a/test/debugger/test-debugger-repl-utf8.js b/test/debugger/test-debugger-repl-utf8.js index 6654a498219859..1af75840f5a6cf 100644 --- a/test/debugger/test-debugger-repl-utf8.js +++ b/test/debugger/test-debugger-repl-utf8.js @@ -1,5 +1,5 @@ 'use strict'; -var common = require('../common'); +const common = require('../common'); var script = common.fixturesDir + '/breakpoints_utf8.js'; process.env.NODE_DEBUGGER_TEST_SCRIPT = script; diff --git a/test/debugger/test-debugger-repl.js b/test/debugger/test-debugger-repl.js index 8a87d40d163af7..19060d9690c820 100644 --- a/test/debugger/test-debugger-repl.js +++ b/test/debugger/test-debugger-repl.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var repl = require('./helper-debugger-repl.js'); +const repl = require('./helper-debugger-repl.js'); repl.startDebugger('breakpoints.js'); diff --git a/test/disabled/test-debug-brk-file.js b/test/disabled/test-debug-brk-file.js index ee20577ded6145..d697de87d06eff 100644 --- a/test/disabled/test-debug-brk-file.js +++ b/test/disabled/test-debug-brk-file.js @@ -1,9 +1,9 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var spawn = require('child_process').spawn; -var path = require('path'); -var net = require('net'); +const common = require('../common'); +const assert = require('assert'); +const spawn = require('child_process').spawn; +const path = require('path'); +const net = require('net'); var isDone = false; var targetPath = path.resolve(common.fixturesDir, 'debug-target.js'); diff --git a/test/disabled/test-dgram-send-error.js b/test/disabled/test-dgram-send-error.js index 7da60de3581ff3..d7ec016540044c 100644 --- a/test/disabled/test-dgram-send-error.js +++ b/test/disabled/test-dgram-send-error.js @@ -10,7 +10,7 @@ const common = require('../common'); var ITERATIONS = 1000; -var assert = require('assert'), +const assert = require('assert'), dgram = require('dgram'); var buf = Buffer.alloc(1024, 42); diff --git a/test/disabled/test-fs-largefile.js b/test/disabled/test-fs-largefile.js index fb0058b358a5c3..b78378548413b7 100644 --- a/test/disabled/test-fs-largefile.js +++ b/test/disabled/test-fs-largefile.js @@ -1,7 +1,7 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var path = require('path'), +const common = require('../common'); +const assert = require('assert'); +const path = require('path'), fs = require('fs'), filepath = path.join(common.tmpDir, 'large.txt'), fd = fs.openSync(filepath, 'w+'), diff --git a/test/disabled/test-http-abort-stream-end.js b/test/disabled/test-http-abort-stream-end.js index cfa531cedf5523..3e8bff21248ca2 100644 --- a/test/disabled/test-http-abort-stream-end.js +++ b/test/disabled/test-http-abort-stream-end.js @@ -1,8 +1,8 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); -var http = require('http'); +const http = require('http'); var maxSize = 1024; var size = 0; diff --git a/test/disabled/test-https-loop-to-google.js b/test/disabled/test-https-loop-to-google.js index e498895ed23be0..2c307f3d1732cd 100644 --- a/test/disabled/test-https-loop-to-google.js +++ b/test/disabled/test-https-loop-to-google.js @@ -5,8 +5,8 @@ // Tested on node 0.5.0-pre commit 9851574 -var common = require('../common'); -var https = require('https'); +const common = require('../common'); +const https = require('https'); for (var i = 0; i < 10; ++i) { https.get({ diff --git a/test/disabled/test-readline.js b/test/disabled/test-readline.js index 9bb9943bd2a403..7896833b93d186 100644 --- a/test/disabled/test-readline.js +++ b/test/disabled/test-readline.js @@ -1,9 +1,9 @@ 'use strict'; // Can't test this when 'make test' doesn't assign a tty to the stdout. // Yet another use-case for require('tty').spawn ? -var common = require('../common'); -var assert = require('assert'); -var readline = require('readline'); +const common = require('../common'); +const assert = require('assert'); +const readline = require('readline'); var key = { xterm: { diff --git a/test/disabled/test-sendfd.js b/test/disabled/test-sendfd.js index d473cd93c33153..969e8b5850dfe2 100644 --- a/test/disabled/test-sendfd.js +++ b/test/disabled/test-sendfd.js @@ -26,15 +26,15 @@ // seen in a response yet. This is intended to ensure that all blobs // sent out have been relayed back to us. -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); -var buffer = require('buffer'); -var child_process = require('child_process'); -var fs = require('fs'); -var net = require('net'); +const buffer = require('buffer'); +const child_process = require('child_process'); +const fs = require('fs'); +const net = require('net'); var netBinding = process.binding('net'); -var path = require('path'); +const path = require('path'); var DATA = { 'ppid' : process.pid, diff --git a/test/disabled/test-setuidgid.js b/test/disabled/test-setuidgid.js index bf3726ab006d36..6b3b578f37991a 100644 --- a/test/disabled/test-setuidgid.js +++ b/test/disabled/test-setuidgid.js @@ -1,7 +1,7 @@ 'use strict'; // Requires special privileges -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); var oldgid = process.getgid(); process.setgid('nobody'); diff --git a/test/disabled/tls_server.js b/test/disabled/tls_server.js index 1e72809a8a04ad..2347ab44103946 100644 --- a/test/disabled/tls_server.js +++ b/test/disabled/tls_server.js @@ -1,11 +1,11 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); -var util = require('util'); -var net = require('net'); -var fs = require('fs'); -var crypto = require('crypto'); +const util = require('util'); +const net = require('net'); +const fs = require('fs'); +const crypto = require('crypto'); var keyPem = fs.readFileSync(common.fixturesDir + '/cert.pem'); var certPem = fs.readFileSync(common.fixturesDir + '/cert.pem'); diff --git a/test/fixtures/GH-892-request.js b/test/fixtures/GH-892-request.js index 96c355857fea4c..eccbafcf4399c2 100644 --- a/test/fixtures/GH-892-request.js +++ b/test/fixtures/GH-892-request.js @@ -1,8 +1,8 @@ // Called by test/pummel/test-regress-GH-892.js -var https = require('https'); -var fs = require('fs'); -var assert = require('assert'); +const https = require('https'); +const fs = require('fs'); +const assert = require('assert'); var PORT = parseInt(process.argv[2]); var bytesExpected = parseInt(process.argv[3]); diff --git a/test/fixtures/a.js b/test/fixtures/a.js index 990a78534a68c9..1e8bbcf210b8b6 100644 --- a/test/fixtures/a.js +++ b/test/fixtures/a.js @@ -1,4 +1,4 @@ -var c = require('./b/c'); +const c = require('./b/c'); console.error('load fixtures/a.js'); diff --git a/test/fixtures/a1.js b/test/fixtures/a1.js index 990a78534a68c9..1e8bbcf210b8b6 100644 --- a/test/fixtures/a1.js +++ b/test/fixtures/a1.js @@ -1,4 +1,4 @@ -var c = require('./b/c'); +const c = require('./b/c'); console.error('load fixtures/a.js'); diff --git a/test/fixtures/b/c.js b/test/fixtures/b/c.js index 1b568c2fc9a66e..a27baeb658ae50 100644 --- a/test/fixtures/b/c.js +++ b/test/fixtures/b/c.js @@ -1,8 +1,8 @@ -var d = require('./d'); +const d = require('./d'); -var assert = require('assert'); +const assert = require('assert'); -var package = require('./package'); +const package = require('./package'); assert.equal('world', package.hello); diff --git a/test/fixtures/break-in-module/main.js b/test/fixtures/break-in-module/main.js index cb7074ed2a3659..cfb44c766abac3 100644 --- a/test/fixtures/break-in-module/main.js +++ b/test/fixtures/break-in-module/main.js @@ -1,4 +1,4 @@ -var mod = require('./mod.js'); +const mod = require('./mod.js'); mod.hello(); mod.hello(); debugger; diff --git a/test/fixtures/child-process-spawn-node.js b/test/fixtures/child-process-spawn-node.js index 01a494ee596c8e..f93fd998fe0e37 100644 --- a/test/fixtures/child-process-spawn-node.js +++ b/test/fixtures/child-process-spawn-node.js @@ -1,4 +1,4 @@ -var assert = require('assert'); +const assert = require('assert'); function onmessage(m) { console.log('CHILD got message:', m); diff --git a/test/fixtures/child_process_should_emit_error.js b/test/fixtures/child_process_should_emit_error.js index 9f7b2bb80ffcbb..34d23fc58347ac 100644 --- a/test/fixtures/child_process_should_emit_error.js +++ b/test/fixtures/child_process_should_emit_error.js @@ -1,4 +1,4 @@ -var exec = require('child_process').exec; +const exec = require('child_process').exec; [0, 1].forEach(function(i) { exec('ls', function(err, stdout, stderr) { diff --git a/test/fixtures/cluster-preload-test.js b/test/fixtures/cluster-preload-test.js index 43d3887b0daf01..0094fe6657fd7c 100644 --- a/test/fixtures/cluster-preload-test.js +++ b/test/fixtures/cluster-preload-test.js @@ -1,4 +1,4 @@ -var cluster = require('cluster'); +const cluster = require('cluster'); if (cluster.isMaster) { cluster.fork(); // one child cluster.on('exit', function(worker, code, signal) { diff --git a/test/fixtures/cluster-preload.js b/test/fixtures/cluster-preload.js index 6637b418babb0d..26d81d8b7a53f6 100644 --- a/test/fixtures/cluster-preload.js +++ b/test/fixtures/cluster-preload.js @@ -1,12 +1,12 @@ -var assert = require('assert'); +const assert = require('assert'); // https://github.com/nodejs/node/issues/1803 // this module is used as a preload module. It should have a parent with the // module search paths initialized from the current working directory assert.ok(module.parent); -var expectedPaths = require('module')._nodeModulePaths(process.cwd()); +const expectedPaths = require('module')._nodeModulePaths(process.cwd()); assert.deepEqual(module.parent.paths, expectedPaths); -var cluster = require('cluster'); +const cluster = require('cluster'); cluster.isMaster || process.exit(42 + cluster.worker.id); // +42 to distinguish // from exit(1) for other random reasons diff --git a/test/fixtures/create-file.js b/test/fixtures/create-file.js index d6f731b784d6d5..1cf417616e1636 100644 --- a/test/fixtures/create-file.js +++ b/test/fixtures/create-file.js @@ -1,4 +1,4 @@ -var fs = require('fs'); +const fs = require('fs'); var file_name = process.argv[2]; var file_size = parseInt(process.argv[3]); diff --git a/test/fixtures/cycles/folder/foo.js b/test/fixtures/cycles/folder/foo.js index a6b284dd56e1b9..573f885f4e4090 100644 --- a/test/fixtures/cycles/folder/foo.js +++ b/test/fixtures/cycles/folder/foo.js @@ -1,4 +1,4 @@ -var root = require('./../root'); +const root = require('./../root'); exports.hello = function() { return root.calledFromFoo(); diff --git a/test/fixtures/cycles/root.js b/test/fixtures/cycles/root.js index 9b8b2459e6743f..5e3504e2a643e1 100644 --- a/test/fixtures/cycles/root.js +++ b/test/fixtures/cycles/root.js @@ -1,4 +1,4 @@ -var foo = exports.foo = require('./folder/foo'); +const foo = exports.foo = require('./folder/foo'); exports.hello = 'hello'; exports.sayHello = function() { diff --git a/test/fixtures/echo-close-check.js b/test/fixtures/echo-close-check.js index 57b2af95672a24..720bcc9de458ba 100644 --- a/test/fixtures/echo-close-check.js +++ b/test/fixtures/echo-close-check.js @@ -1,7 +1,7 @@ -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); -var fs = require('fs'); +const common = require('../common'); +const assert = require('assert'); +const net = require('net'); +const fs = require('fs'); process.stdout.write('hello world\r\n'); diff --git a/test/fixtures/echo.js b/test/fixtures/echo.js index c03e661d1c5704..429541b5849bd4 100644 --- a/test/fixtures/echo.js +++ b/test/fixtures/echo.js @@ -1,5 +1,5 @@ -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); process.stdout.write('hello world\r\n'); diff --git a/test/fixtures/listen-on-socket-and-exit.js b/test/fixtures/listen-on-socket-and-exit.js index 7fb0d970de7e0d..8627625965e87d 100644 --- a/test/fixtures/listen-on-socket-and-exit.js +++ b/test/fixtures/listen-on-socket-and-exit.js @@ -1,7 +1,7 @@ // child process that listens on a socket, allows testing of an EADDRINUSE condition -var common = require('../common'); -var net = require('net'); +const common = require('../common'); +const net = require('net'); common.refreshTmpDir(); diff --git a/test/fixtures/module-require/parent/index.js b/test/fixtures/module-require/parent/index.js index e174cba6fffc88..52e650bbdbd2cc 100644 --- a/test/fixtures/module-require/parent/index.js +++ b/test/fixtures/module-require/parent/index.js @@ -1,4 +1,4 @@ -var child = require('../child'); +const child = require('../child'); //console.log(child.module.require, child.module); console.log(child.module.require('target')); console.log(child.loaded); diff --git a/test/fixtures/node_modules/baz/index.js b/test/fixtures/node_modules/baz/index.js index 859ea0924d6fb7..59fc9fe79bcb61 100644 --- a/test/fixtures/node_modules/baz/index.js +++ b/test/fixtures/node_modules/baz/index.js @@ -1,7 +1,7 @@ console.error(__filename); console.error(module.paths.join('\n') + '\n'); // this should work, and get the one that doesn't throw -var assert = require('assert'); +const assert = require('assert'); assert.equal(require('bar'), require('../bar.js')); // this should work, and get the one in ./node_modules/asdf.js diff --git a/test/fixtures/node_modules/foo.js b/test/fixtures/node_modules/foo.js index f69ac7b00e5a4b..56a98f76a86ddf 100644 --- a/test/fixtures/node_modules/foo.js +++ b/test/fixtures/node_modules/foo.js @@ -1,4 +1,4 @@ console.error(__filename); console.error(module.paths.join('\n') + '\n'); -var assert = require('assert'); +const assert = require('assert'); assert.equal(require('baz'), require('./baz/index.js')); diff --git a/test/fixtures/not-main-module.js b/test/fixtures/not-main-module.js index 3da57f44285910..de024cd92ef942 100644 --- a/test/fixtures/not-main-module.js +++ b/test/fixtures/not-main-module.js @@ -1,4 +1,4 @@ -var assert = require('assert'); +const assert = require('assert'); assert.notEqual(module, require.main, 'require.main should not == module'); assert.notEqual(module, process.mainModule, 'process.mainModule should not === module'); diff --git a/test/fixtures/parent-process-nonpersistent.js b/test/fixtures/parent-process-nonpersistent.js index a71d1a3882de27..e55c7bf896d4d3 100644 --- a/test/fixtures/parent-process-nonpersistent.js +++ b/test/fixtures/parent-process-nonpersistent.js @@ -1,5 +1,5 @@ -var spawn = require('child_process').spawn, +const spawn = require('child_process').spawn, path = require('path'), childPath = path.join(__dirname, 'child-process-persistent.js'); diff --git a/test/fixtures/path-resolve.js b/test/fixtures/path-resolve.js index 00eb3d3691ea3c..883d14b73e6791 100644 --- a/test/fixtures/path-resolve.js +++ b/test/fixtures/path-resolve.js @@ -1,4 +1,4 @@ // Tests resolving a path in the context of a spawned process. // See https://github.com/nodejs/node/issues/7215 -var path = require('path'); +const path = require('path'); console.log(path.resolve(process.argv[2])); diff --git a/test/fixtures/path.js b/test/fixtures/path.js index cdfcec876159df..b6323ff059f963 100644 --- a/test/fixtures/path.js +++ b/test/fixtures/path.js @@ -1,5 +1,5 @@ // This is actually more a fixture than a test. It is used to make -var common = require('../common'); +const common = require('../common'); // sure that require('./path') and require('path') do different things. // It has to be in the same directory as the test 'test-module-loading.js' // and it has to have the same name as an internal module. diff --git a/test/fixtures/print-chars-from-buffer.js b/test/fixtures/print-chars-from-buffer.js index fc902a896fe54f..b2f4ac43584c59 100644 --- a/test/fixtures/print-chars-from-buffer.js +++ b/test/fixtures/print-chars-from-buffer.js @@ -1,4 +1,4 @@ -var assert = require('assert'); +const assert = require('assert'); var n = parseInt(process.argv[2]); diff --git a/test/fixtures/print-chars.js b/test/fixtures/print-chars.js index b9707fbf75fa67..e350a025a54723 100644 --- a/test/fixtures/print-chars.js +++ b/test/fixtures/print-chars.js @@ -1,4 +1,4 @@ -var assert = require('assert'); +const assert = require('assert'); var n = parseInt(process.argv[2]); diff --git a/test/fixtures/recvfd.js b/test/fixtures/recvfd.js index 75df69a3dc3954..4c9d96ffe07612 100644 --- a/test/fixtures/recvfd.js +++ b/test/fixtures/recvfd.js @@ -1,7 +1,7 @@ // See test/simple/test-sendfd.js for a complete description of what this // script is doing and how it fits into the test as a whole. -var net = require('net'); +const net = require('net'); var receivedData = []; var receivedFDs = []; diff --git a/test/fixtures/stdio-filter.js b/test/fixtures/stdio-filter.js index 8e4f50305131f4..cc0e53c39d0353 100644 --- a/test/fixtures/stdio-filter.js +++ b/test/fixtures/stdio-filter.js @@ -1,4 +1,4 @@ -var util = require('util'); +const util = require('util'); var regexIn = process.argv[2]; var replacement = process.argv[3]; diff --git a/test/fixtures/test-init-native/fs.js b/test/fixtures/test-init-native/fs.js index 6b47b418f44561..6481485d22918c 100644 --- a/test/fixtures/test-init-native/fs.js +++ b/test/fixtures/test-init-native/fs.js @@ -1,5 +1,5 @@ (function() { - var fs = require('fs'); + const fs = require('fs'); if (fs.readFile) { require('util').print('fs loaded successfully'); } diff --git a/test/fixtures/test-regress-GH-4015.js b/test/fixtures/test-regress-GH-4015.js index 0d9c05d6d71638..9f947fa091a5f5 100644 --- a/test/fixtures/test-regress-GH-4015.js +++ b/test/fixtures/test-regress-GH-4015.js @@ -1,4 +1,4 @@ -var fs = require('fs'); +const fs = require('fs'); function load() { fs.statSync('.'); diff --git a/test/fixtures/uncaught-exceptions/domain.js b/test/fixtures/uncaught-exceptions/domain.js index c00b22dbb9c86d..9ede6993a7331b 100644 --- a/test/fixtures/uncaught-exceptions/domain.js +++ b/test/fixtures/uncaught-exceptions/domain.js @@ -1,4 +1,4 @@ -var domain = require('domain'); +const domain = require('domain'); var d = domain.create(); d.on('error', function(err) { diff --git a/test/gc/node_modules/bindings/README.md b/test/gc/node_modules/bindings/README.md index 585cf512b9b1f6..2dc83f5d85e5cc 100644 --- a/test/gc/node_modules/bindings/README.md +++ b/test/gc/node_modules/bindings/README.md @@ -35,7 +35,7 @@ Example and architecture is as simple as: ``` js -var bindings = require('bindings')('binding.node') +const bindings = require('bindings')('binding.node') // Use your bindings defined in your C files bindings.your_c_function() diff --git a/test/gc/node_modules/bindings/bindings.js b/test/gc/node_modules/bindings/bindings.js index 93dcf85a187afe..b60ff631cc9f06 100644 --- a/test/gc/node_modules/bindings/bindings.js +++ b/test/gc/node_modules/bindings/bindings.js @@ -3,7 +3,7 @@ * Module dependencies. */ -var fs = require('fs') +const fs = require('fs') , path = require('path') , join = path.join , dirname = path.dirname diff --git a/test/gc/node_modules/nan/tools/1to2.js b/test/gc/node_modules/nan/tools/1to2.js index 15d156481873f7..3464857ace54be 100755 --- a/test/gc/node_modules/nan/tools/1to2.js +++ b/test/gc/node_modules/nan/tools/1to2.js @@ -7,7 +7,7 @@ * MIT License ********************************************************************/ -var commander = require('commander'), +const commander = require('commander'), fs = require('fs'), glob = require('glob'), groups = [], diff --git a/test/gc/node_modules/weak/README.md b/test/gc/node_modules/weak/README.md index c153bb509c737a..1dad235ce180df 100644 --- a/test/gc/node_modules/weak/README.md +++ b/test/gc/node_modules/weak/README.md @@ -36,7 +36,7 @@ Here's an example of calling a `cleanup()` function on a Object before it gets garbage collected: ``` js -var weak = require('weak') +const weak = require('weak') // we are going to "monitor" this Object and invoke "cleanup" // before the object is garbage collected @@ -80,7 +80,7 @@ at the highest scope possible (top-level being the best). Named functions work really well for this: ``` js -var http = require('http') +const http = require('http') , weak = require('weak') http.createServer(function (req, res) { diff --git a/test/gc/node_modules/weak/build/Makefile b/test/gc/node_modules/weak/build/Makefile index ab2f0190ef9c5f..0fd5a88f9d3c7d 100644 --- a/test/gc/node_modules/weak/build/Makefile +++ b/test/gc/node_modules/weak/build/Makefile @@ -326,7 +326,7 @@ ifeq ($(strip $(foreach prefix,$(NO_LOAD),\ endif quiet_cmd_regen_makefile = ACTION Regenerating $@ -cmd_regen_makefile = cd $(srcdir); /Users/trott/io.js/deps/npm/node_modules/node-gyp/gyp/gyp_main.py -fmake --ignore-environment "--toplevel-dir=." -I/Users/trott/io.js/test/gc/node_modules/weak/build/config.gypi -I/Users/trott/io.js/deps/npm/node_modules/node-gyp/addon.gypi -I/Users/trott/io.js/common.gypi "--depth=." "-Goutput_dir=." "--generator-output=build" "-Dlibrary=shared_library" "-Dvisibility=default" "-Dnode_root_dir=/Users/trott/io.js" "-Dnode_gyp_dir=/Users/trott/io.js/deps/npm/node_modules/node-gyp" "-Dnode_lib_file=node.lib" "-Dmodule_root_dir=/Users/trott/io.js/test/gc/node_modules/weak" binding.gyp +cmd_regen_makefile = cd $(srcdir); /Users/cjihrig/iojs/node/deps/npm/node_modules/node-gyp/gyp/gyp_main.py -fmake --ignore-environment "--toplevel-dir=." -I/Users/cjihrig/iojs/node/test/gc/node_modules/weak/build/config.gypi -I/Users/cjihrig/iojs/node/deps/npm/node_modules/node-gyp/addon.gypi -I/Users/cjihrig/iojs/node/common.gypi "--depth=." "-Goutput_dir=." "--generator-output=build" "-Dlibrary=shared_library" "-Dvisibility=default" "-Dnode_root_dir=/Users/cjihrig/iojs/node" "-Dnode_gyp_dir=/Users/cjihrig/iojs/node/deps/npm/node_modules/node-gyp" "-Dnode_lib_file=node.lib" "-Dmodule_root_dir=/Users/cjihrig/iojs/node/test/gc/node_modules/weak" binding.gyp Makefile: $(srcdir)/../../../../deps/npm/node_modules/node-gyp/addon.gypi $(srcdir)/build/config.gypi $(srcdir)/binding.gyp $(srcdir)/../../../../common.gypi $(call do_cmd,regen_makefile) diff --git a/test/gc/node_modules/weak/build/config.gypi b/test/gc/node_modules/weak/build/config.gypi index 9354987d41ab17..ce322bc5f3961a 100644 --- a/test/gc/node_modules/weak/build/config.gypi +++ b/test/gc/node_modules/weak/build/config.gypi @@ -9,47 +9,58 @@ }, "variables": { "asan": 0, + "coverage": "false", + "debug_devtools": "node", + "force_dynamic_crt": 0, "host_arch": "x64", - "icu_data_file": "icudt57l.dat", - "icu_data_in": "../../deps/icu-small/source/data/in/icudt57l.dat", + "icu_data_file": "icudt58l.dat", + "icu_data_in": "../../deps/icu-small/source/data/in/icudt58l.dat", "icu_endianness": "l", "icu_gyp_path": "tools/icu/icu-generic.gyp", "icu_locales": "en,root", "icu_path": "deps/icu-small", "icu_small": "true", - "icu_ver_major": "57", + "icu_ver_major": "58", "llvm_version": 0, "node_byteorder": "little", + "node_enable_d8": "false", "node_enable_v8_vtunejit": "false", "node_install_npm": "true", + "node_module_version": 51, "node_no_browser_globals": "false", "node_prefix": "/usr/local", "node_release_urlbase": "", + "node_shared": "false", "node_shared_cares": "false", "node_shared_http_parser": "false", "node_shared_libuv": "false", "node_shared_openssl": "false", "node_shared_zlib": "false", "node_tag": "", + "node_use_bundled_v8": "true", "node_use_dtrace": "true", "node_use_etw": "false", "node_use_lttng": "false", "node_use_openssl": "true", "node_use_perfctr": "false", + "node_use_v8_platform": "true", "openssl_fips": "", "openssl_no_asm": 0, + "shlib_suffix": "51.dylib", "target_arch": "x64", "uv_parent_path": "/deps/uv/", "uv_use_dtrace": "true", "v8_enable_gdbjit": 0, "v8_enable_i18n_support": 1, + "v8_inspector": "true", "v8_no_strict_aliasing": 1, "v8_optimized_debug": 0, "v8_random_seed": 0, "v8_use_snapshot": "true", "want_separate_host_toolset": 0, - "xcode_version": "7.0", - "nodedir": "/Users/trott/io.js", + "want_separate_host_toolset_mkpeephole": 0, + "xcode_version": "8.0", + "nodedir": "/Users/cjihrig/iojs/node", "copy_dev_lib": "false", "standalone_static_library": 1 } diff --git a/test/gc/node_modules/weak/build/weakref.target.mk b/test/gc/node_modules/weak/build/weakref.target.mk index 8572d7412ffd34..bb8d2bd72fffab 100644 --- a/test/gc/node_modules/weak/build/weakref.target.mk +++ b/test/gc/node_modules/weak/build/weakref.target.mk @@ -4,6 +4,9 @@ TOOLSET := target TARGET := weakref DEFS_Debug := \ '-DNODE_GYP_MODULE_NAME=weakref' \ + '-DUSING_UV_SHARED=1' \ + '-DUSING_V8_SHARED=1' \ + '-DV8_DEPRECATION_WARNINGS=1' \ '-D_DARWIN_USE_64_BIT_INODE=1' \ '-D_LARGEFILE_SOURCE' \ '-D_FILE_OFFSET_BITS=64' \ @@ -29,6 +32,7 @@ CFLAGS_C_Debug := \ # Flags passed to only C++ files. CFLAGS_CC_Debug := \ -std=gnu++0x \ + -stdlib=libc++ \ -fno-rtti \ -fno-exceptions \ -fno-threadsafe-statics \ @@ -41,14 +45,17 @@ CFLAGS_OBJC_Debug := CFLAGS_OBJCC_Debug := INCS_Debug := \ - -I/Users/trott/io.js/include/node \ - -I/Users/trott/io.js/src \ - -I/Users/trott/io.js/deps/uv/include \ - -I/Users/trott/io.js/deps/v8/include \ + -I/Users/cjihrig/iojs/node/include/node \ + -I/Users/cjihrig/iojs/node/src \ + -I/Users/cjihrig/iojs/node/deps/uv/include \ + -I/Users/cjihrig/iojs/node/deps/v8/include \ -I$(srcdir)/../nan DEFS_Release := \ '-DNODE_GYP_MODULE_NAME=weakref' \ + '-DUSING_UV_SHARED=1' \ + '-DUSING_V8_SHARED=1' \ + '-DV8_DEPRECATION_WARNINGS=1' \ '-D_DARWIN_USE_64_BIT_INODE=1' \ '-D_LARGEFILE_SOURCE' \ '-D_FILE_OFFSET_BITS=64' \ @@ -72,6 +79,7 @@ CFLAGS_C_Release := \ # Flags passed to only C++ files. CFLAGS_CC_Release := \ -std=gnu++0x \ + -stdlib=libc++ \ -fno-rtti \ -fno-exceptions \ -fno-threadsafe-statics \ @@ -84,10 +92,10 @@ CFLAGS_OBJC_Release := CFLAGS_OBJCC_Release := INCS_Release := \ - -I/Users/trott/io.js/include/node \ - -I/Users/trott/io.js/src \ - -I/Users/trott/io.js/deps/uv/include \ - -I/Users/trott/io.js/deps/v8/include \ + -I/Users/cjihrig/iojs/node/include/node \ + -I/Users/cjihrig/iojs/node/src \ + -I/Users/cjihrig/iojs/node/deps/uv/include \ + -I/Users/cjihrig/iojs/node/deps/v8/include \ -I$(srcdir)/../nan OBJS := \ @@ -125,7 +133,8 @@ LDFLAGS_Debug := \ -Wl,-search_paths_first \ -mmacosx-version-min=10.7 \ -arch x86_64 \ - -L$(builddir) + -L$(builddir) \ + -stdlib=libc++ LIBTOOLFLAGS_Debug := \ -undefined dynamic_lookup \ @@ -138,7 +147,8 @@ LDFLAGS_Release := \ -Wl,-search_paths_first \ -mmacosx-version-min=10.7 \ -arch x86_64 \ - -L$(builddir) + -L$(builddir) \ + -stdlib=libc++ LIBTOOLFLAGS_Release := \ -undefined dynamic_lookup \ diff --git a/test/gc/node_modules/weak/lib/weak.js b/test/gc/node_modules/weak/lib/weak.js index 5502b0de201372..66ba2e71388c59 100644 --- a/test/gc/node_modules/weak/lib/weak.js +++ b/test/gc/node_modules/weak/lib/weak.js @@ -3,8 +3,8 @@ * Module dependencies. */ -var Emitter = require('events').EventEmitter; -var bindings = require('bindings')('weakref.node'); +const Emitter = require('events').EventEmitter; +const bindings = require('bindings')('weakref.node'); /** * Set global weak callback function. diff --git a/test/internet/test-dgram-send-cb-quelches-error.js b/test/internet/test-dgram-send-cb-quelches-error.js index 56612edead4fd2..e20c8e107081cd 100644 --- a/test/internet/test-dgram-send-cb-quelches-error.js +++ b/test/internet/test-dgram-send-cb-quelches-error.js @@ -1,9 +1,9 @@ 'use strict'; -var common = require('../common'); +const common = require('../common'); var mustCall = common.mustCall; -var assert = require('assert'); -var dgram = require('dgram'); -var dns = require('dns'); +const assert = require('assert'); +const dgram = require('dgram'); +const dns = require('dns'); var socket = dgram.createSocket('udp4'); var buffer = Buffer.from('gary busey'); diff --git a/test/internet/test-dns-cares-domains.js b/test/internet/test-dns-cares-domains.js index 76ebf0d628b1c4..61ac679274d8b3 100644 --- a/test/internet/test-dns-cares-domains.js +++ b/test/internet/test-dns-cares-domains.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var dns = require('dns'); -var domain = require('domain'); +const assert = require('assert'); +const dns = require('dns'); +const domain = require('domain'); var methods = [ 'resolve4', diff --git a/test/internet/test-dns-txt-sigsegv.js b/test/internet/test-dns-txt-sigsegv.js index 4c2f12f7a97c28..3c85d546cfcddd 100644 --- a/test/internet/test-dns-txt-sigsegv.js +++ b/test/internet/test-dns-txt-sigsegv.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var dns = require('dns'); +const assert = require('assert'); +const dns = require('dns'); dns.resolveTxt('www.microsoft.com', function(err, records) { assert.equal(err, null); diff --git a/test/internet/test-http-https-default-ports.js b/test/internet/test-http-https-default-ports.js index 8b00e434e9cba6..c7e6b3baf7ccdc 100644 --- a/test/internet/test-http-https-default-ports.js +++ b/test/internet/test-http-https-default-ports.js @@ -1,13 +1,13 @@ 'use strict'; -var common = require('../common'); +const common = require('../common'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var https = require('https'); +const https = require('https'); -var http = require('http'); +const http = require('http'); https.get('https://www.google.com/', common.mustCall(function(res) { res.resume(); diff --git a/test/internet/test-net-connect-timeout.js b/test/internet/test-net-connect-timeout.js index 0f58622aa19912..e379f4146720b9 100644 --- a/test/internet/test-net-connect-timeout.js +++ b/test/internet/test-net-connect-timeout.js @@ -4,8 +4,8 @@ // https://groups.google.com/forum/#!topic/nodejs-dev/jR7-5UDqXkw const common = require('../common'); -var net = require('net'); -var assert = require('assert'); +const net = require('net'); +const assert = require('assert'); var start = new Date(); diff --git a/test/internet/test-net-connect-unref.js b/test/internet/test-net-connect-unref.js index 52929d2152774d..fa45cc711e1016 100644 --- a/test/internet/test-net-connect-unref.js +++ b/test/internet/test-net-connect-unref.js @@ -1,6 +1,6 @@ 'use strict'; const common = require('../common'); -var net = require('net'); +const net = require('net'); var client; var TIMEOUT = 10 * 1000; diff --git a/test/internet/test-tls-connnect-melissadata.js b/test/internet/test-tls-connnect-melissadata.js index 7ab7f2aa7a7895..3c6c205d6e4013 100644 --- a/test/internet/test-tls-connnect-melissadata.js +++ b/test/internet/test-tls-connnect-melissadata.js @@ -2,13 +2,13 @@ // Test for authorized access to the server which has a cross root // certification between Starfield Class 2 and ValiCert Class 2 -var common = require('../common'); +const common = require('../common'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var tls = require('tls'); +const tls = require('tls'); var socket = tls.connect(443, 'address.melissadata.net', function() { socket.resume(); socket.destroy(); diff --git a/test/message/error_exit.js b/test/message/error_exit.js index 18d9dfb4ee998c..7235801514dd45 100644 --- a/test/message/error_exit.js +++ b/test/message/error_exit.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); process.on('exit', function(code) { console.error('Exiting with code=%d', code); diff --git a/test/message/eval_messages.js b/test/message/eval_messages.js index bb1569601c889f..188311851c5163 100644 --- a/test/message/eval_messages.js +++ b/test/message/eval_messages.js @@ -2,7 +2,7 @@ require('../common'); -var spawn = require('child_process').spawn; +const spawn = require('child_process').spawn; function run(cmd, strict, cb) { var args = []; diff --git a/test/message/stdin_messages.js b/test/message/stdin_messages.js index 6e1ced4124f2a6..4759e2b0d51159 100644 --- a/test/message/stdin_messages.js +++ b/test/message/stdin_messages.js @@ -2,7 +2,7 @@ require('../common'); -var spawn = require('child_process').spawn; +const spawn = require('child_process').spawn; function run(cmd, strict, cb) { var args = []; diff --git a/test/message/undefined_reference_in_new_context.js b/test/message/undefined_reference_in_new_context.js index 73821ae53d4f5f..77c5e1e29111b9 100644 --- a/test/message/undefined_reference_in_new_context.js +++ b/test/message/undefined_reference_in_new_context.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var vm = require('vm'); +const vm = require('vm'); console.error('before'); diff --git a/test/message/vm_display_runtime_error.js b/test/message/vm_display_runtime_error.js index a7ca9907444181..861e87f2f2bb93 100644 --- a/test/message/vm_display_runtime_error.js +++ b/test/message/vm_display_runtime_error.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var vm = require('vm'); +const vm = require('vm'); console.error('beginning'); diff --git a/test/message/vm_display_syntax_error.js b/test/message/vm_display_syntax_error.js index 62bbd432a2f98a..02612fb92d9a22 100644 --- a/test/message/vm_display_syntax_error.js +++ b/test/message/vm_display_syntax_error.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var vm = require('vm'); +const vm = require('vm'); console.error('beginning'); diff --git a/test/message/vm_dont_display_runtime_error.js b/test/message/vm_dont_display_runtime_error.js index 19d0120a90abfd..6a96243a83cf4a 100644 --- a/test/message/vm_dont_display_runtime_error.js +++ b/test/message/vm_dont_display_runtime_error.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var vm = require('vm'); +const vm = require('vm'); console.error('beginning'); diff --git a/test/message/vm_dont_display_syntax_error.js b/test/message/vm_dont_display_syntax_error.js index bff0433a144b09..76c3043330946d 100644 --- a/test/message/vm_dont_display_syntax_error.js +++ b/test/message/vm_dont_display_syntax_error.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var vm = require('vm'); +const vm = require('vm'); console.error('beginning'); diff --git a/test/parallel/test-assert.js b/test/parallel/test-assert.js index 3d2481ef4ec49b..06d328eea4c67b 100644 --- a/test/parallel/test-assert.js +++ b/test/parallel/test-assert.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var a = require('assert'); +const assert = require('assert'); +const a = require('assert'); function makeBlock(f) { var args = Array.prototype.slice.call(arguments, 1); diff --git a/test/parallel/test-beforeexit-event-exit.js b/test/parallel/test-beforeexit-event-exit.js index 67676a7990041f..6878135ce4d6d3 100644 --- a/test/parallel/test-beforeexit-event-exit.js +++ b/test/parallel/test-beforeexit-event-exit.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); process.on('beforeExit', function() { assert(false, 'exit should not allow this to occur'); diff --git a/test/parallel/test-child-process-constructor.js b/test/parallel/test-child-process-constructor.js index 0abf1289f0737d..59277dcabe5ffa 100644 --- a/test/parallel/test-child-process-constructor.js +++ b/test/parallel/test-child-process-constructor.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var child_process = require('child_process'); +const assert = require('assert'); +const child_process = require('child_process'); var ChildProcess = child_process.ChildProcess; assert.strictEqual(typeof ChildProcess, 'function'); diff --git a/test/parallel/test-child-process-default-options.js b/test/parallel/test-child-process-default-options.js index 38a1b291b9967c..2c60e274de51fa 100644 --- a/test/parallel/test-child-process-default-options.js +++ b/test/parallel/test-child-process-default-options.js @@ -1,8 +1,8 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); -var spawn = require('child_process').spawn; +const spawn = require('child_process').spawn; process.env.HELLO = 'WORLD'; diff --git a/test/parallel/test-child-process-env.js b/test/parallel/test-child-process-env.js index 2ebc653e9a067d..cac82b9952a4da 100644 --- a/test/parallel/test-child-process-env.js +++ b/test/parallel/test-child-process-env.js @@ -1,8 +1,8 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); -var spawn = require('child_process').spawn; +const spawn = require('child_process').spawn; var env = { 'HELLO': 'WORLD' diff --git a/test/parallel/test-child-process-exit-code.js b/test/parallel/test-child-process-exit-code.js index 3a393f126fbe13..2bd1256fe273d8 100644 --- a/test/parallel/test-child-process-exit-code.js +++ b/test/parallel/test-child-process-exit-code.js @@ -1,8 +1,8 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var spawn = require('child_process').spawn; -var path = require('path'); +const common = require('../common'); +const assert = require('assert'); +const spawn = require('child_process').spawn; +const path = require('path'); var exitScript = path.join(common.fixturesDir, 'exit.js'); var exitChild = spawn(process.argv[0], [exitScript, 23]); diff --git a/test/parallel/test-child-process-fork-exec-argv.js b/test/parallel/test-child-process-fork-exec-argv.js index 5ccc17fb3fc7c4..2daef37b669fc8 100644 --- a/test/parallel/test-child-process-fork-exec-argv.js +++ b/test/parallel/test-child-process-fork-exec-argv.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var child_process = require('child_process'); +const assert = require('assert'); +const child_process = require('child_process'); var spawn = child_process.spawn; var fork = child_process.fork; diff --git a/test/parallel/test-child-process-fork-exec-path.js b/test/parallel/test-child-process-fork-exec-path.js index e2f7e4b4d20eef..e9938d8ba12767 100644 --- a/test/parallel/test-child-process-fork-exec-path.js +++ b/test/parallel/test-child-process-fork-exec-path.js @@ -1,8 +1,8 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); -var fs = require('fs'); -var path = require('path'); +const assert = require('assert'); +const fs = require('fs'); +const path = require('path'); var msg = {test: 'this'}; var nodePath = process.execPath; var copyPath = path.join(common.tmpDir, 'node-copy.exe'); @@ -25,7 +25,7 @@ if (process.env.FORK) { // slow but simple var envCopy = JSON.parse(JSON.stringify(process.env)); envCopy.FORK = 'true'; - var child = require('child_process').fork(__filename, { + const child = require('child_process').fork(__filename, { execPath: copyPath, env: envCopy }); diff --git a/test/parallel/test-child-process-fork-net2.js b/test/parallel/test-child-process-fork-net2.js index be1ee5d3a4145a..cee5c0a4ca548b 100644 --- a/test/parallel/test-child-process-fork-net2.js +++ b/test/parallel/test-child-process-fork-net2.js @@ -1,8 +1,8 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); -var fork = require('child_process').fork; -var net = require('net'); +const assert = require('assert'); +const fork = require('child_process').fork; +const net = require('net'); var count = 12; if (process.argv[2] === 'child') { diff --git a/test/parallel/test-child-process-fork-ref.js b/test/parallel/test-child-process-fork-ref.js index 50a944e71ba83c..46eaab584f5581 100644 --- a/test/parallel/test-child-process-fork-ref.js +++ b/test/parallel/test-child-process-fork-ref.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var fork = require('child_process').fork; +const assert = require('assert'); +const fork = require('child_process').fork; if (process.argv[2] === 'child') { process.send('1'); diff --git a/test/parallel/test-child-process-fork-ref2.js b/test/parallel/test-child-process-fork-ref2.js index 42c43ed8882b78..6d6c56b6b3a93f 100644 --- a/test/parallel/test-child-process-fork-ref2.js +++ b/test/parallel/test-child-process-fork-ref2.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var fork = require('child_process').fork; +const fork = require('child_process').fork; if (process.argv[2] === 'child') { console.log('child -> call disconnect'); diff --git a/test/parallel/test-child-process-fork.js b/test/parallel/test-child-process-fork.js index a7d4a995a33700..a8548eff5809c5 100644 --- a/test/parallel/test-child-process-fork.js +++ b/test/parallel/test-child-process-fork.js @@ -1,7 +1,7 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); -var fork = require('child_process').fork; +const assert = require('assert'); +const fork = require('child_process').fork; var args = ['foo', 'bar']; var n = fork(common.fixturesDir + '/child-process-spawn-node.js', args); diff --git a/test/parallel/test-child-process-fork3.js b/test/parallel/test-child-process-fork3.js index fe0e68b6a6436e..5588c41422e21b 100644 --- a/test/parallel/test-child-process-fork3.js +++ b/test/parallel/test-child-process-fork3.js @@ -1,5 +1,5 @@ 'use strict'; -var common = require('../common'); -var child_process = require('child_process'); +const common = require('../common'); +const child_process = require('child_process'); child_process.fork(common.fixturesDir + '/empty.js'); // should not hang diff --git a/test/parallel/test-child-process-internal.js b/test/parallel/test-child-process-internal.js index f3e452ef87ea76..5d488f7839bd54 100644 --- a/test/parallel/test-child-process-internal.js +++ b/test/parallel/test-child-process-internal.js @@ -1,6 +1,6 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); +const assert = require('assert'); //messages var PREFIX = 'NODE_'; @@ -18,7 +18,7 @@ if (process.argv[2] === 'child') { } else { - var fork = require('child_process').fork; + const fork = require('child_process').fork; var child = fork(process.argv[1], ['child']); child.once('message', common.mustCall(function(data) { diff --git a/test/parallel/test-child-process-set-blocking.js b/test/parallel/test-child-process-set-blocking.js index fb0b11f433130a..5a542fa97e2b5a 100644 --- a/test/parallel/test-child-process-set-blocking.js +++ b/test/parallel/test-child-process-set-blocking.js @@ -1,7 +1,7 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); -var ch = require('child_process'); +const assert = require('assert'); +const ch = require('child_process'); var SIZE = 100000; diff --git a/test/parallel/test-child-process-silent.js b/test/parallel/test-child-process-silent.js index 50d4ae881ad880..e087ae1cdea14f 100644 --- a/test/parallel/test-child-process-silent.js +++ b/test/parallel/test-child-process-silent.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var childProcess = require('child_process'); +const assert = require('assert'); +const childProcess = require('child_process'); // Child pipe test if (process.argv[2] === 'pipe') { diff --git a/test/parallel/test-child-process-spawnsync-env.js b/test/parallel/test-child-process-spawnsync-env.js index 4455b867e30108..05ef18bf7279a7 100644 --- a/test/parallel/test-child-process-spawnsync-env.js +++ b/test/parallel/test-child-process-spawnsync-env.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var cp = require('child_process'); +const assert = require('assert'); +const cp = require('child_process'); if (process.argv[2] === 'child') { console.log(process.env.foo); diff --git a/test/parallel/test-child-process-spawnsync-timeout.js b/test/parallel/test-child-process-spawnsync-timeout.js index 122a65825949df..207315c531afd0 100644 --- a/test/parallel/test-child-process-spawnsync-timeout.js +++ b/test/parallel/test-child-process-spawnsync-timeout.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); -var spawnSync = require('child_process').spawnSync; +const spawnSync = require('child_process').spawnSync; var TIMER = 200; var SLEEP = 5000; diff --git a/test/parallel/test-child-process-stdin-ipc.js b/test/parallel/test-child-process-stdin-ipc.js index 2ce7c66c2053e0..c4a8064680e69f 100644 --- a/test/parallel/test-child-process-stdin-ipc.js +++ b/test/parallel/test-child-process-stdin-ipc.js @@ -1,8 +1,8 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); +const assert = require('assert'); -var spawn = require('child_process').spawn; +const spawn = require('child_process').spawn; if (process.argv[2] === 'child') { // Just reference stdin, it should start it diff --git a/test/parallel/test-child-process-stdio-inherit.js b/test/parallel/test-child-process-stdio-inherit.js index dc3bb3e9aa9391..f7b992e4e76c26 100644 --- a/test/parallel/test-child-process-stdio-inherit.js +++ b/test/parallel/test-child-process-stdio-inherit.js @@ -1,7 +1,7 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var spawn = require('child_process').spawn; +const common = require('../common'); +const assert = require('assert'); +const spawn = require('child_process').spawn; if (process.argv[2] === 'parent') parent(); diff --git a/test/parallel/test-cluster-disconnect-with-no-workers.js b/test/parallel/test-cluster-disconnect-with-no-workers.js index 4c2425d82d656b..4b38720d71e984 100644 --- a/test/parallel/test-cluster-disconnect-with-no-workers.js +++ b/test/parallel/test-cluster-disconnect-with-no-workers.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var cluster = require('cluster'); +const assert = require('assert'); +const cluster = require('cluster'); var disconnected; diff --git a/test/parallel/test-cluster-eaddrinuse.js b/test/parallel/test-cluster-eaddrinuse.js index 88b6de2dde4230..8b94845635f822 100644 --- a/test/parallel/test-cluster-eaddrinuse.js +++ b/test/parallel/test-cluster-eaddrinuse.js @@ -3,10 +3,10 @@ // leave the master process in a confused state. Releasing the port and // trying again should Just Work[TM]. -var common = require('../common'); -var assert = require('assert'); -var fork = require('child_process').fork; -var net = require('net'); +const common = require('../common'); +const assert = require('assert'); +const fork = require('child_process').fork; +const net = require('net'); var id = '' + process.argv[2]; diff --git a/test/parallel/test-cluster-fork-env.js b/test/parallel/test-cluster-fork-env.js index 17b7af3d061926..735ff73d2a5c16 100644 --- a/test/parallel/test-cluster-fork-env.js +++ b/test/parallel/test-cluster-fork-env.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var cluster = require('cluster'); +const assert = require('assert'); +const cluster = require('cluster'); if (cluster.isWorker) { const result = cluster.worker.send({ diff --git a/test/parallel/test-cluster-listening-port.js b/test/parallel/test-cluster-listening-port.js index b0fbf9499041d2..ce86205c1e792a 100644 --- a/test/parallel/test-cluster-listening-port.js +++ b/test/parallel/test-cluster-listening-port.js @@ -1,8 +1,8 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var cluster = require('cluster'); -var net = require('net'); +const common = require('../common'); +const assert = require('assert'); +const cluster = require('cluster'); +const net = require('net'); if (cluster.isMaster) { cluster.fork(); diff --git a/test/parallel/test-cluster-message.js b/test/parallel/test-cluster-message.js index 0587eecb4dd4b5..a86b469e331dbe 100644 --- a/test/parallel/test-cluster-message.js +++ b/test/parallel/test-cluster-message.js @@ -1,8 +1,8 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var cluster = require('cluster'); -var net = require('net'); +const common = require('../common'); +const assert = require('assert'); +const cluster = require('cluster'); +const net = require('net'); function forEach(obj, fn) { Object.keys(obj).forEach(function(name, index) { diff --git a/test/parallel/test-cluster-rr-domain-listen.js b/test/parallel/test-cluster-rr-domain-listen.js index 1328483abb72df..0f39c47ed2e67d 100644 --- a/test/parallel/test-cluster-rr-domain-listen.js +++ b/test/parallel/test-cluster-rr-domain-listen.js @@ -1,7 +1,7 @@ 'use strict'; -var common = require('../common'); -var cluster = require('cluster'); -var domain = require('domain'); +const common = require('../common'); +const cluster = require('cluster'); +const domain = require('domain'); // RR is the default for v0.11.9+ so the following line is redundant: // cluster.schedulingPolicy = cluster.SCHED_RR; @@ -10,7 +10,7 @@ if (cluster.isWorker) { var d = domain.create(); d.run(function() { }); - var http = require('http'); + const http = require('http'); http.Server(function() { }).listen(common.PORT, '127.0.0.1'); } else if (cluster.isMaster) { diff --git a/test/parallel/test-cluster-send-deadlock.js b/test/parallel/test-cluster-send-deadlock.js index fa3e1138248221..062ebf2b131911 100644 --- a/test/parallel/test-cluster-send-deadlock.js +++ b/test/parallel/test-cluster-send-deadlock.js @@ -2,10 +2,10 @@ // Testing mutual send of handles: from master to worker, and from worker to // master. -var common = require('../common'); -var assert = require('assert'); -var cluster = require('cluster'); -var net = require('net'); +const common = require('../common'); +const assert = require('assert'); +const cluster = require('cluster'); +const net = require('net'); if (cluster.isMaster) { var worker = cluster.fork(); diff --git a/test/parallel/test-cluster-setup-master-cumulative.js b/test/parallel/test-cluster-setup-master-cumulative.js index 6a55df29d4411f..977c89a56aa573 100644 --- a/test/parallel/test-cluster-setup-master-cumulative.js +++ b/test/parallel/test-cluster-setup-master-cumulative.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var cluster = require('cluster'); +const assert = require('assert'); +const cluster = require('cluster'); assert(cluster.isMaster); diff --git a/test/parallel/test-cluster-setup-master-emit.js b/test/parallel/test-cluster-setup-master-emit.js index aad1cea75eda97..5b828e7b8e360f 100644 --- a/test/parallel/test-cluster-setup-master-emit.js +++ b/test/parallel/test-cluster-setup-master-emit.js @@ -1,7 +1,7 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); -var cluster = require('cluster'); +const assert = require('assert'); +const cluster = require('cluster'); assert(cluster.isMaster); diff --git a/test/parallel/test-cluster-setup-master-multiple.js b/test/parallel/test-cluster-setup-master-multiple.js index 5ceff2bddfaf9d..a7611b3c23ad4d 100644 --- a/test/parallel/test-cluster-setup-master-multiple.js +++ b/test/parallel/test-cluster-setup-master-multiple.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var cluster = require('cluster'); +const assert = require('assert'); +const cluster = require('cluster'); assert(cluster.isMaster); diff --git a/test/parallel/test-cluster-setup-master.js b/test/parallel/test-cluster-setup-master.js index 66193203fdc665..4590309f936218 100644 --- a/test/parallel/test-cluster-setup-master.js +++ b/test/parallel/test-cluster-setup-master.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var cluster = require('cluster'); +const assert = require('assert'); +const cluster = require('cluster'); if (cluster.isWorker) { diff --git a/test/parallel/test-cluster-worker-death.js b/test/parallel/test-cluster-worker-death.js index ac32705106e03c..6435232a8103af 100644 --- a/test/parallel/test-cluster-worker-death.js +++ b/test/parallel/test-cluster-worker-death.js @@ -1,7 +1,7 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); -var cluster = require('cluster'); +const assert = require('assert'); +const cluster = require('cluster'); if (!cluster.isMaster) { process.exit(42); diff --git a/test/parallel/test-cluster-worker-destroy.js b/test/parallel/test-cluster-worker-destroy.js index ca3ac77e7b25cc..30da5954b23971 100644 --- a/test/parallel/test-cluster-worker-destroy.js +++ b/test/parallel/test-cluster-worker-destroy.js @@ -9,7 +9,7 @@ const common = require('../common'); const assert = require('assert'); -var cluster = require('cluster'); +const cluster = require('cluster'); var worker1, worker2; if (cluster.isMaster) { diff --git a/test/parallel/test-cluster-worker-events.js b/test/parallel/test-cluster-worker-events.js index 08bf456a735b7d..b77a32353b3ce6 100644 --- a/test/parallel/test-cluster-worker-events.js +++ b/test/parallel/test-cluster-worker-events.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var cluster = require('cluster'); +const assert = require('assert'); +const cluster = require('cluster'); var OK = 2; diff --git a/test/parallel/test-cluster-worker-forced-exit.js b/test/parallel/test-cluster-worker-forced-exit.js index 3e1f7905ee50d1..1d553a9269b332 100644 --- a/test/parallel/test-cluster-worker-forced-exit.js +++ b/test/parallel/test-cluster-worker-forced-exit.js @@ -1,7 +1,7 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); -var cluster = require('cluster'); +const assert = require('assert'); +const cluster = require('cluster'); var SENTINEL = 42; diff --git a/test/parallel/test-cluster-worker-isconnected.js b/test/parallel/test-cluster-worker-isconnected.js index 985d15ce6475e6..3b17b53e8ae1ae 100644 --- a/test/parallel/test-cluster-worker-isconnected.js +++ b/test/parallel/test-cluster-worker-isconnected.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var cluster = require('cluster'); -var assert = require('assert'); +const cluster = require('cluster'); +const assert = require('assert'); if (cluster.isMaster) { var worker = cluster.fork(); diff --git a/test/parallel/test-cluster-worker-isdead.js b/test/parallel/test-cluster-worker-isdead.js index 90454cb86089a7..a80f8410b11a4f 100644 --- a/test/parallel/test-cluster-worker-isdead.js +++ b/test/parallel/test-cluster-worker-isdead.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var cluster = require('cluster'); -var assert = require('assert'); +const cluster = require('cluster'); +const assert = require('assert'); if (cluster.isMaster) { var worker = cluster.fork(); diff --git a/test/parallel/test-cluster-worker-no-exit.js b/test/parallel/test-cluster-worker-no-exit.js index 0cec652b68648c..9921256c4a74d0 100644 --- a/test/parallel/test-cluster-worker-no-exit.js +++ b/test/parallel/test-cluster-worker-no-exit.js @@ -1,8 +1,8 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); -var cluster = require('cluster'); -var net = require('net'); +const assert = require('assert'); +const cluster = require('cluster'); +const net = require('net'); var destroyed; var success; diff --git a/test/parallel/test-cluster-worker-wait-server-close.js b/test/parallel/test-cluster-worker-wait-server-close.js index bdf60971fee5c1..cb925822a06f6b 100644 --- a/test/parallel/test-cluster-worker-wait-server-close.js +++ b/test/parallel/test-cluster-worker-wait-server-close.js @@ -1,9 +1,9 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var cluster = require('cluster'); -var net = require('net'); +const common = require('../common'); +const assert = require('assert'); +const cluster = require('cluster'); +const net = require('net'); var serverClosed = false; diff --git a/test/parallel/test-common.js b/test/parallel/test-common.js index 59485eec4a327f..17f41840e4ffa5 100644 --- a/test/parallel/test-common.js +++ b/test/parallel/test-common.js @@ -1,6 +1,6 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); common.globalCheck = false; global.gc = 42; // Not a valid global unless --expose_gc is set. diff --git a/test/parallel/test-console-not-call-toString.js b/test/parallel/test-console-not-call-toString.js index f152e33e98f087..bf8a59072f965b 100644 --- a/test/parallel/test-console-not-call-toString.js +++ b/test/parallel/test-console-not-call-toString.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); var func = function() {}; var toStringCalled = false; diff --git a/test/parallel/test-crypto-certificate.js b/test/parallel/test-crypto-certificate.js index 1dfb2c73b0eca5..24c3163e3b2d90 100644 --- a/test/parallel/test-crypto-certificate.js +++ b/test/parallel/test-crypto-certificate.js @@ -1,16 +1,16 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var crypto = require('crypto'); +const crypto = require('crypto'); crypto.DEFAULT_ENCODING = 'buffer'; -var fs = require('fs'); +const fs = require('fs'); // Test Certificates var spkacValid = fs.readFileSync(common.fixturesDir + '/spkac.valid'); diff --git a/test/parallel/test-crypto-dh-odd-key.js b/test/parallel/test-crypto-dh-odd-key.js index cb8757efff0bde..92fab2b8c2a178 100644 --- a/test/parallel/test-crypto-dh-odd-key.js +++ b/test/parallel/test-crypto-dh-odd-key.js @@ -1,12 +1,12 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var crypto = require('crypto'); +const crypto = require('crypto'); function test() { var odd = Buffer.alloc(39, 'A'); diff --git a/test/parallel/test-crypto-domain.js b/test/parallel/test-crypto-domain.js index ec9985719933d3..fcbbcb8e0524f2 100644 --- a/test/parallel/test-crypto-domain.js +++ b/test/parallel/test-crypto-domain.js @@ -1,13 +1,13 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var domain = require('domain'); +const common = require('../common'); +const assert = require('assert'); +const domain = require('domain'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var crypto = require('crypto'); +const crypto = require('crypto'); function test(fn) { var ex = new Error('BAM'); diff --git a/test/parallel/test-crypto-domains.js b/test/parallel/test-crypto-domains.js index 5d8caf37ee2f41..738ed15323ba01 100644 --- a/test/parallel/test-crypto-domains.js +++ b/test/parallel/test-crypto-domains.js @@ -1,7 +1,7 @@ 'use strict'; -var common = require('../common'); -var domain = require('domain'); -var assert = require('assert'); +const common = require('../common'); +const domain = require('domain'); +const assert = require('assert'); var d = domain.create(); var expect = ['pbkdf2', 'randomBytes', 'pseudoRandomBytes']; @@ -9,7 +9,7 @@ if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var crypto = require('crypto'); +const crypto = require('crypto'); d.on('error', common.mustCall(function(e) { assert.equal(e.message, expect.shift()); diff --git a/test/parallel/test-crypto-fips.js b/test/parallel/test-crypto-fips.js index 24b1af70b70329..51ff8ef759850f 100644 --- a/test/parallel/test-crypto-fips.js +++ b/test/parallel/test-crypto-fips.js @@ -1,8 +1,8 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var spawnSync = require('child_process').spawnSync; -var path = require('path'); +const common = require('../common'); +const assert = require('assert'); +const spawnSync = require('child_process').spawnSync; +const path = require('path'); if (!common.hasCrypto) { common.skip('missing crypto'); diff --git a/test/parallel/test-crypto-from-binary.js b/test/parallel/test-crypto-from-binary.js index 0889541ef6e144..ec39606506b7b7 100644 --- a/test/parallel/test-crypto-from-binary.js +++ b/test/parallel/test-crypto-from-binary.js @@ -3,14 +3,14 @@ // to use buffers by default. -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var crypto = require('crypto'); +const crypto = require('crypto'); var EXTERN_APEX = 0xFBEE9; diff --git a/test/parallel/test-crypto-hash.js b/test/parallel/test-crypto-hash.js index 79353ede3b49dc..473f01269db0a0 100644 --- a/test/parallel/test-crypto-hash.js +++ b/test/parallel/test-crypto-hash.js @@ -1,14 +1,14 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var fs = require('fs'); -var path = require('path'); +const common = require('../common'); +const assert = require('assert'); +const fs = require('fs'); +const path = require('path'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var crypto = require('crypto'); +const crypto = require('crypto'); // Test hashing var a1 = crypto.createHash('sha1').update('Test123').digest('hex'); diff --git a/test/parallel/test-crypto-hmac.js b/test/parallel/test-crypto-hmac.js index eeb8cd152567f8..ef4e59a1dd944c 100644 --- a/test/parallel/test-crypto-hmac.js +++ b/test/parallel/test-crypto-hmac.js @@ -1,12 +1,12 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var crypto = require('crypto'); +const crypto = require('crypto'); // Test for binding layer robustness { diff --git a/test/parallel/test-crypto-padding-aes256.js b/test/parallel/test-crypto-padding-aes256.js index 7fd2e98de617cf..40bbfed0f2824f 100644 --- a/test/parallel/test-crypto-padding-aes256.js +++ b/test/parallel/test-crypto-padding-aes256.js @@ -1,12 +1,12 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var crypto = require('crypto'); +const crypto = require('crypto'); crypto.DEFAULT_ENCODING = 'buffer'; diff --git a/test/parallel/test-crypto-rsa-dsa.js b/test/parallel/test-crypto-rsa-dsa.js index 118117547cae32..ffa862d6a97569 100644 --- a/test/parallel/test-crypto-rsa-dsa.js +++ b/test/parallel/test-crypto-rsa-dsa.js @@ -1,14 +1,14 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var fs = require('fs'); +const common = require('../common'); +const assert = require('assert'); +const fs = require('fs'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var constants = require('crypto').constants; -var crypto = require('crypto'); +const constants = require('crypto').constants; +const crypto = require('crypto'); // Test certificates var certPem = fs.readFileSync(common.fixturesDir + '/test_cert.pem', 'ascii'); diff --git a/test/parallel/test-crypto-sign-verify.js b/test/parallel/test-crypto-sign-verify.js index 6df41409f0e6c1..05f29a710466ee 100644 --- a/test/parallel/test-crypto-sign-verify.js +++ b/test/parallel/test-crypto-sign-verify.js @@ -1,13 +1,13 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var fs = require('fs'); +const common = require('../common'); +const assert = require('assert'); +const fs = require('fs'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var crypto = require('crypto'); +const crypto = require('crypto'); // Test certificates var certPem = fs.readFileSync(common.fixturesDir + '/test_cert.pem', 'ascii'); diff --git a/test/parallel/test-crypto-stream.js b/test/parallel/test-crypto-stream.js index 1720cc7c4e0aea..06b483b326279f 100644 --- a/test/parallel/test-crypto-stream.js +++ b/test/parallel/test-crypto-stream.js @@ -1,14 +1,14 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var stream = require('stream'); -var util = require('util'); +const common = require('../common'); +const assert = require('assert'); +const stream = require('stream'); +const util = require('util'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var crypto = require('crypto'); +const crypto = require('crypto'); // Small stream to buffer converter function Stream2buffer(callback) { diff --git a/test/parallel/test-crypto-verify-failure.js b/test/parallel/test-crypto-verify-failure.js index fdc27215027414..f840c017b4b2d4 100644 --- a/test/parallel/test-crypto-verify-failure.js +++ b/test/parallel/test-crypto-verify-failure.js @@ -1,16 +1,16 @@ 'use strict'; -var common = require('../common'); +const common = require('../common'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var crypto = require('crypto'); -var tls = require('tls'); +const crypto = require('crypto'); +const tls = require('tls'); crypto.DEFAULT_ENCODING = 'buffer'; -var fs = require('fs'); +const fs = require('fs'); var certPem = fs.readFileSync(common.fixturesDir + '/test_cert.pem', 'ascii'); diff --git a/test/parallel/test-cwd-enoent-repl.js b/test/parallel/test-cwd-enoent-repl.js index 1d03bd3e9112c1..da7729b286519e 100644 --- a/test/parallel/test-cwd-enoent-repl.js +++ b/test/parallel/test-cwd-enoent-repl.js @@ -1,8 +1,8 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var fs = require('fs'); -var spawn = require('child_process').spawn; +const common = require('../common'); +const assert = require('assert'); +const fs = require('fs'); +const spawn = require('child_process').spawn; // Fails with EINVAL on SmartOS, EBUSY on Windows, EBUSY on AIX. if (common.isSunOS || common.isWindows || common.isAix) { diff --git a/test/parallel/test-cwd-enoent.js b/test/parallel/test-cwd-enoent.js index c671ef2be4619e..bb26a6e879784b 100644 --- a/test/parallel/test-cwd-enoent.js +++ b/test/parallel/test-cwd-enoent.js @@ -1,8 +1,8 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var fs = require('fs'); -var spawn = require('child_process').spawn; +const common = require('../common'); +const assert = require('assert'); +const fs = require('fs'); +const spawn = require('child_process').spawn; // Fails with EINVAL on SmartOS, EBUSY on Windows, EBUSY on AIX. if (common.isSunOS || common.isWindows || common.isAix) { diff --git a/test/parallel/test-debug-port-from-cmdline.js b/test/parallel/test-debug-port-from-cmdline.js index abec53cbd3c83a..f0ff853b16df82 100644 --- a/test/parallel/test-debug-port-from-cmdline.js +++ b/test/parallel/test-debug-port-from-cmdline.js @@ -1,7 +1,7 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var spawn = require('child_process').spawn; +const common = require('../common'); +const assert = require('assert'); +const spawn = require('child_process').spawn; var debugPort = common.PORT; var args = ['--interactive', '--debug-port=' + debugPort]; diff --git a/test/parallel/test-delayed-require.js b/test/parallel/test-delayed-require.js index bc110388fc0380..8e07367eb47366 100644 --- a/test/parallel/test-delayed-require.js +++ b/test/parallel/test-delayed-require.js @@ -1,7 +1,7 @@ 'use strict'; -var common = require('../common'); -var path = require('path'); -var assert = require('assert'); +const common = require('../common'); +const path = require('path'); +const assert = require('assert'); setTimeout(common.mustCall(function() { const a = require(path.join(common.fixturesDir, 'a')); diff --git a/test/parallel/test-dgram-address.js b/test/parallel/test-dgram-address.js index 38729de67098da..03fcdf3446ac83 100644 --- a/test/parallel/test-dgram-address.js +++ b/test/parallel/test-dgram-address.js @@ -1,7 +1,7 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var dgram = require('dgram'); +const common = require('../common'); +const assert = require('assert'); +const dgram = require('dgram'); // IPv4 Test var socket_ipv4 = dgram.createSocket('udp4'); diff --git a/test/parallel/test-dgram-bind.js b/test/parallel/test-dgram-bind.js index 0bca97fb294f79..6df102b32d09e1 100644 --- a/test/parallel/test-dgram-bind.js +++ b/test/parallel/test-dgram-bind.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var dgram = require('dgram'); +const assert = require('assert'); +const dgram = require('dgram'); var socket = dgram.createSocket('udp4'); diff --git a/test/parallel/test-dgram-bytes-length.js b/test/parallel/test-dgram-bytes-length.js index 8e2233e9c4daad..da686d850ee129 100644 --- a/test/parallel/test-dgram-bytes-length.js +++ b/test/parallel/test-dgram-bytes-length.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var dgram = require('dgram'); +const assert = require('assert'); +const dgram = require('dgram'); var message = Buffer.from('Some bytes'); var client = dgram.createSocket('udp4'); diff --git a/test/parallel/test-dgram-close-is-not-callback.js b/test/parallel/test-dgram-close-is-not-callback.js index 61e08200360452..beccc2420d36bc 100644 --- a/test/parallel/test-dgram-close-is-not-callback.js +++ b/test/parallel/test-dgram-close-is-not-callback.js @@ -1,6 +1,6 @@ 'use strict'; -var common = require('../common'); -var dgram = require('dgram'); +const common = require('../common'); +const dgram = require('dgram'); var buf = Buffer.alloc(1024, 42); diff --git a/test/parallel/test-dgram-implicit-bind.js b/test/parallel/test-dgram-implicit-bind.js index 8cbb3f771e2d47..25c61903e884de 100644 --- a/test/parallel/test-dgram-implicit-bind.js +++ b/test/parallel/test-dgram-implicit-bind.js @@ -1,6 +1,6 @@ 'use strict'; const common = require('../common'); -var dgram = require('dgram'); +const dgram = require('dgram'); var source = dgram.createSocket('udp4'); var target = dgram.createSocket('udp4'); diff --git a/test/parallel/test-dgram-listen-after-bind.js b/test/parallel/test-dgram-listen-after-bind.js index 498a17a0e5b053..2060a4738012a2 100644 --- a/test/parallel/test-dgram-listen-after-bind.js +++ b/test/parallel/test-dgram-listen-after-bind.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var dgram = require('dgram'); +const assert = require('assert'); +const dgram = require('dgram'); var socket = dgram.createSocket('udp4'); diff --git a/test/parallel/test-dgram-oob-buffer.js b/test/parallel/test-dgram-oob-buffer.js index e52bf7d69b3c6f..0bf302e7e3ce6e 100644 --- a/test/parallel/test-dgram-oob-buffer.js +++ b/test/parallel/test-dgram-oob-buffer.js @@ -3,8 +3,8 @@ // unreachable host. This error can be reported by sendto() and even by // recvfrom(). Node should not propagate this error to the user. -var common = require('../common'); -var dgram = require('dgram'); +const common = require('../common'); +const dgram = require('dgram'); var socket = dgram.createSocket('udp4'); var buf = Buffer.from([1, 2, 3, 4]); diff --git a/test/parallel/test-dgram-ref.js b/test/parallel/test-dgram-ref.js index 6505ce9b1ec886..d8981c0b8ad1db 100644 --- a/test/parallel/test-dgram-ref.js +++ b/test/parallel/test-dgram-ref.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var dgram = require('dgram'); +const dgram = require('dgram'); // should not hang, see #1282 dgram.createSocket('udp4'); diff --git a/test/parallel/test-dgram-regress-4496.js b/test/parallel/test-dgram-regress-4496.js index 4bdd0d6520d7dc..2b509d79076911 100644 --- a/test/parallel/test-dgram-regress-4496.js +++ b/test/parallel/test-dgram-regress-4496.js @@ -2,8 +2,8 @@ // Remove this test once we support sending strings. require('../common'); -var assert = require('assert'); -var dgram = require('dgram'); +const assert = require('assert'); +const dgram = require('dgram'); // Should throw but not crash. var socket = dgram.createSocket('udp4'); diff --git a/test/parallel/test-dgram-send-bad-arguments.js b/test/parallel/test-dgram-send-bad-arguments.js index a3918697addc4e..8505c8bb67e8c0 100644 --- a/test/parallel/test-dgram-send-bad-arguments.js +++ b/test/parallel/test-dgram-send-bad-arguments.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var dgram = require('dgram'); +const assert = require('assert'); +const dgram = require('dgram'); var buf = Buffer.from('test'); var host = '127.0.0.1'; diff --git a/test/parallel/test-dgram-unref.js b/test/parallel/test-dgram-unref.js index e5f26b6f3387b8..1b95487a302cdb 100644 --- a/test/parallel/test-dgram-unref.js +++ b/test/parallel/test-dgram-unref.js @@ -1,6 +1,6 @@ 'use strict'; const common = require('../common'); -var dgram = require('dgram'); +const dgram = require('dgram'); var s = dgram.createSocket('udp4'); s.bind(); diff --git a/test/parallel/test-dh-padding.js b/test/parallel/test-dh-padding.js index a9cd95225abedb..35202f6a5191a8 100644 --- a/test/parallel/test-dh-padding.js +++ b/test/parallel/test-dh-padding.js @@ -1,14 +1,14 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); -try { - var crypto = require('crypto'); -} catch (e) { +if (!common.hasCrypto) { common.skip('node compiled without OpenSSL.'); return; } +const assert = require('assert'); +const crypto = require('crypto'); + /* This test verifies padding with leading zeroes for shared * secrets that are strictly smaller than the modulus (prime). * See: diff --git a/test/parallel/test-domain-abort-on-uncaught.js b/test/parallel/test-domain-abort-on-uncaught.js index d61debc06067f6..d9183af60bc278 100644 --- a/test/parallel/test-domain-abort-on-uncaught.js +++ b/test/parallel/test-domain-abort-on-uncaught.js @@ -90,7 +90,7 @@ const tests = [ }); d.run(function() { - var fs = require('fs'); + const fs = require('fs'); fs.exists('/non/existing/file', function onExists(exists) { throw new Error('boom!'); }); @@ -212,7 +212,7 @@ const tests = [ d.run(function() { d2.run(function() { - var fs = require('fs'); + const fs = require('fs'); fs.exists('/non/existing/file', function onExists(exists) { throw new Error('boom!'); }); diff --git a/test/parallel/test-domain-crypto.js b/test/parallel/test-domain-crypto.js index 1109591fee9631..8293eb82d2bc2c 100644 --- a/test/parallel/test-domain-crypto.js +++ b/test/parallel/test-domain-crypto.js @@ -2,13 +2,13 @@ const common = require('../common'); -try { - var crypto = require('crypto'); -} catch (e) { +if (!common.hasCrypto) { common.skip('node compiled without OpenSSL.'); return; } +const crypto = require('crypto'); + // Pollution of global is intentional as part of test. common.globalCheck = false; // See https://github.com/nodejs/node/commit/d1eff9ab diff --git a/test/parallel/test-domain-enter-exit.js b/test/parallel/test-domain-enter-exit.js index 2973e833f3a1b9..5f12a0bd4ca08c 100644 --- a/test/parallel/test-domain-enter-exit.js +++ b/test/parallel/test-domain-enter-exit.js @@ -2,8 +2,8 @@ // Make sure the domain stack is a stack require('../common'); -var assert = require('assert'); -var domain = require('domain'); +const assert = require('assert'); +const domain = require('domain'); function names(array) { return array.map(function(d) { diff --git a/test/parallel/test-domain-exit-dispose-again.js b/test/parallel/test-domain-exit-dispose-again.js index b1911bb40e0c93..2a4ffd655c3e52 100644 --- a/test/parallel/test-domain-exit-dispose-again.js +++ b/test/parallel/test-domain-exit-dispose-again.js @@ -6,8 +6,8 @@ // the same invocation of listOnTimeout, _are_ called. require('../common'); -var assert = require('assert'); -var domain = require('domain'); +const assert = require('assert'); +const domain = require('domain'); var disposalFailed = false; // Repeatedly schedule a timer with a delay different than the timers attached diff --git a/test/parallel/test-domain-exit-dispose.js b/test/parallel/test-domain-exit-dispose.js index 508cec18dccb7d..c53b840bf556c3 100644 --- a/test/parallel/test-domain-exit-dispose.js +++ b/test/parallel/test-domain-exit-dispose.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var common = require('../common'); -var assert = require('assert'); -var domain = require('domain'); +const common = require('../common'); +const assert = require('assert'); +const domain = require('domain'); // no matter what happens, we should increment a 10 times. var a = 0; diff --git a/test/parallel/test-domain-http-server.js b/test/parallel/test-domain-http-server.js index 26264e8ec987d8..ee0388b3cd7f88 100644 --- a/test/parallel/test-domain-http-server.js +++ b/test/parallel/test-domain-http-server.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var domain = require('domain'); -var http = require('http'); -var assert = require('assert'); +const domain = require('domain'); +const http = require('http'); +const assert = require('assert'); var objects = { foo: 'bar', baz: {}, num: 42, arr: [1, 2, 3] }; objects.baz.asdf = objects; diff --git a/test/parallel/test-domain-implicit-fs.js b/test/parallel/test-domain-implicit-fs.js index 01a7026ac9bad4..7773bc46d76137 100644 --- a/test/parallel/test-domain-implicit-fs.js +++ b/test/parallel/test-domain-implicit-fs.js @@ -2,8 +2,8 @@ // Simple tests of most basic domain functionality. const common = require('../common'); -var assert = require('assert'); -var domain = require('domain'); +const assert = require('assert'); +const domain = require('domain'); var d = new domain.Domain(); @@ -28,7 +28,7 @@ d.on('error', common.mustCall(function(er) { // handles are created. d.run(function() { setTimeout(function() { - var fs = require('fs'); + const fs = require('fs'); fs.readdir(__dirname, function() { fs.open('this file does not exist', 'r', function(er) { assert.ifError(er); diff --git a/test/parallel/test-domain-multi.js b/test/parallel/test-domain-multi.js index cf85dbca460146..2e541ab5e4dc3c 100644 --- a/test/parallel/test-domain-multi.js +++ b/test/parallel/test-domain-multi.js @@ -2,8 +2,8 @@ // Tests of multiple domains happening at once. require('../common'); -var assert = require('assert'); -var domain = require('domain'); +const assert = require('assert'); +const domain = require('domain'); var caughtA = false; var caughtB = false; @@ -19,7 +19,7 @@ a.on('error', function(er) { }); -var http = require('http'); +const http = require('http'); var server = http.createServer(function(req, res) { // child domain of a. var b = domain.create(); diff --git a/test/parallel/test-domain-nested-throw.js b/test/parallel/test-domain-nested-throw.js index 69a80b7ab104d0..008eaaa5f7496f 100644 --- a/test/parallel/test-domain-nested-throw.js +++ b/test/parallel/test-domain-nested-throw.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); -var domain = require('domain'); +const domain = require('domain'); var dispose; switch (process.argv[2]) { @@ -19,7 +19,7 @@ switch (process.argv[2]) { function parent() { var node = process.execPath; - var spawn = require('child_process').spawn; + const spawn = require('child_process').spawn; var opt = { stdio: 'inherit' }; var child = spawn(node, [__filename, 'true'], opt); child.on('exit', function(c) { diff --git a/test/parallel/test-domain-nested.js b/test/parallel/test-domain-nested.js index 68c56d0c3c8b2c..d0618b5bad724b 100644 --- a/test/parallel/test-domain-nested.js +++ b/test/parallel/test-domain-nested.js @@ -2,8 +2,8 @@ // Make sure that the nested domains don't cause the domain stack to grow require('../common'); -var assert = require('assert'); -var domain = require('domain'); +const assert = require('assert'); +const domain = require('domain'); process.on('exit', function(c) { assert.equal(domain._stack.length, 0); diff --git a/test/parallel/test-domain-no-error-handler-abort-on-uncaught-5.js b/test/parallel/test-domain-no-error-handler-abort-on-uncaught-5.js index 78ef3662a20229..ade72147e148e7 100644 --- a/test/parallel/test-domain-no-error-handler-abort-on-uncaught-5.js +++ b/test/parallel/test-domain-no-error-handler-abort-on-uncaught-5.js @@ -7,7 +7,7 @@ function test() { const d = domain.create(); d.run(function() { - var fs = require('fs'); + const fs = require('fs'); fs.exists('/non/existing/file', function onExists() { throw new Error('boom!'); }); diff --git a/test/parallel/test-domain-no-error-handler-abort-on-uncaught-9.js b/test/parallel/test-domain-no-error-handler-abort-on-uncaught-9.js index a4eebd50e96388..2e86a2125e86ee 100644 --- a/test/parallel/test-domain-no-error-handler-abort-on-uncaught-9.js +++ b/test/parallel/test-domain-no-error-handler-abort-on-uncaught-9.js @@ -12,7 +12,7 @@ function test() { d.run(function() { d2.run(function() { - var fs = require('fs'); + const fs = require('fs'); fs.exists('/non/existing/file', function onExists() { throw new Error('boom!'); }); diff --git a/test/parallel/test-domain-safe-exit.js b/test/parallel/test-domain-safe-exit.js index 399ae37bcd94c5..c00aa306f10e7a 100644 --- a/test/parallel/test-domain-safe-exit.js +++ b/test/parallel/test-domain-safe-exit.js @@ -2,8 +2,8 @@ // Make sure the domain stack doesn't get clobbered by un-matched .exit() require('../common'); -var assert = require('assert'); -var domain = require('domain'); +const assert = require('assert'); +const domain = require('domain'); var a = domain.create(); var b = domain.create(); diff --git a/test/parallel/test-domain-stack.js b/test/parallel/test-domain-stack.js index e30d3b21f3af57..5772a56e39b77e 100644 --- a/test/parallel/test-domain-stack.js +++ b/test/parallel/test-domain-stack.js @@ -2,7 +2,7 @@ // Make sure that the domain stack doesn't get out of hand. require('../common'); -var domain = require('domain'); +const domain = require('domain'); var a = domain.create(); a.name = 'a'; diff --git a/test/parallel/test-domain-timers.js b/test/parallel/test-domain-timers.js index d42afa7471791a..6ddec404cd20ac 100644 --- a/test/parallel/test-domain-timers.js +++ b/test/parallel/test-domain-timers.js @@ -1,7 +1,7 @@ 'use strict'; const common = require('../common'); -var domain = require('domain'); -var assert = require('assert'); +const domain = require('domain'); +const assert = require('assert'); var timeout; diff --git a/test/parallel/test-domain-top-level-error-handler-throw.js b/test/parallel/test-domain-top-level-error-handler-throw.js index b65b94012393c6..8062d107367dfe 100644 --- a/test/parallel/test-domain-top-level-error-handler-throw.js +++ b/test/parallel/test-domain-top-level-error-handler-throw.js @@ -13,7 +13,7 @@ const domainErrHandlerExMessage = 'exception from domain error handler'; const internalExMessage = 'You should NOT see me'; if (process.argv[2] === 'child') { - var domain = require('domain'); + const domain = require('domain'); var d = domain.create(); d.on('error', function() { @@ -26,8 +26,8 @@ if (process.argv[2] === 'child') { }); }); } else { - var fork = require('child_process').fork; - var assert = require('assert'); + const fork = require('child_process').fork; + const assert = require('assert'); var child = fork(process.argv[1], ['child'], {silent: true}); var stderrOutput = ''; diff --git a/test/parallel/test-domain-with-abort-on-uncaught-exception.js b/test/parallel/test-domain-with-abort-on-uncaught-exception.js index 6fb3912e5b8d9c..e11935be68704e 100644 --- a/test/parallel/test-domain-with-abort-on-uncaught-exception.js +++ b/test/parallel/test-domain-with-abort-on-uncaught-exception.js @@ -29,7 +29,7 @@ const fs = require('fs'); const domainErrHandlerExMessage = 'exception from domain error handler'; if (process.argv[2] === 'child') { - var domain = require('domain'); + const domain = require('domain'); var d = domain.create(); process.on('uncaughtException', function onUncaughtException() { @@ -80,7 +80,7 @@ if (process.argv[2] === 'child') { throw new Error('Error from domain.run callback'); }); } else { - var exec = require('child_process').exec; + const exec = require('child_process').exec; function testDomainExceptionHandling(cmdLineOption, options) { if (typeof cmdLineOption === 'object') { diff --git a/test/parallel/test-dsa-fips-invalid-key.js b/test/parallel/test-dsa-fips-invalid-key.js index ede3adab66c527..d0716a3e21eb08 100644 --- a/test/parallel/test-dsa-fips-invalid-key.js +++ b/test/parallel/test-dsa-fips-invalid-key.js @@ -1,14 +1,14 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); if (!common.hasFipsCrypto) { common.skip('node compiled without FIPS OpenSSL.'); return; } -var crypto = require('crypto'); -var fs = require('fs'); +const crypto = require('crypto'); +const fs = require('fs'); var input = 'hello'; diff --git a/test/parallel/test-error-reporting.js b/test/parallel/test-error-reporting.js index 62525a5494d5a0..058f99126a7d1b 100644 --- a/test/parallel/test-error-reporting.js +++ b/test/parallel/test-error-reporting.js @@ -1,8 +1,8 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var exec = require('child_process').exec; -var path = require('path'); +const common = require('../common'); +const assert = require('assert'); +const exec = require('child_process').exec; +const path = require('path'); function errExec(script, callback) { var cmd = '"' + process.argv[0] + '" "' + diff --git a/test/parallel/test-event-emitter-errors.js b/test/parallel/test-event-emitter-errors.js index 3effb999b37e8c..e2c9fa2a0c2c1e 100644 --- a/test/parallel/test-event-emitter-errors.js +++ b/test/parallel/test-event-emitter-errors.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var EventEmitter = require('events'); -var assert = require('assert'); +const EventEmitter = require('events'); +const assert = require('assert'); var EE = new EventEmitter(); diff --git a/test/parallel/test-event-emitter-get-max-listeners.js b/test/parallel/test-event-emitter-get-max-listeners.js index 34ffee3600e5e9..13f1dcb97c39c3 100644 --- a/test/parallel/test-event-emitter-get-max-listeners.js +++ b/test/parallel/test-event-emitter-get-max-listeners.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var EventEmitter = require('events'); +const assert = require('assert'); +const EventEmitter = require('events'); var emitter = new EventEmitter(); diff --git a/test/parallel/test-event-emitter-listeners-side-effects.js b/test/parallel/test-event-emitter-listeners-side-effects.js index 906138af2367c3..60d64c6614df80 100644 --- a/test/parallel/test-event-emitter-listeners-side-effects.js +++ b/test/parallel/test-event-emitter-listeners-side-effects.js @@ -1,9 +1,9 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); +const assert = require('assert'); -var EventEmitter = require('events').EventEmitter; +const EventEmitter = require('events').EventEmitter; var e = new EventEmitter(); var fl; // foo listeners diff --git a/test/parallel/test-event-emitter-method-names.js b/test/parallel/test-event-emitter-method-names.js index e268e229b06b5b..27c01b2a0781c5 100644 --- a/test/parallel/test-event-emitter-method-names.js +++ b/test/parallel/test-event-emitter-method-names.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var events = require('events'); +const assert = require('assert'); +const events = require('events'); var E = events.EventEmitter.prototype; assert.strictEqual(E.constructor.name, 'EventEmitter'); diff --git a/test/parallel/test-event-emitter-no-error-provided-to-error-event.js b/test/parallel/test-event-emitter-no-error-provided-to-error-event.js index 0a3ecb33d6e697..99bdeea79dc5bb 100644 --- a/test/parallel/test-event-emitter-no-error-provided-to-error-event.js +++ b/test/parallel/test-event-emitter-no-error-provided-to-error-event.js @@ -1,8 +1,8 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); -var events = require('events'); -var domain = require('domain'); +const assert = require('assert'); +const events = require('events'); +const domain = require('domain'); var e = new events.EventEmitter(); var d = domain.create(); diff --git a/test/parallel/test-event-emitter-num-args.js b/test/parallel/test-event-emitter-num-args.js index d858692aad338e..a5660b259ef483 100644 --- a/test/parallel/test-event-emitter-num-args.js +++ b/test/parallel/test-event-emitter-num-args.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var events = require('events'); +const assert = require('assert'); +const events = require('events'); const e = new events.EventEmitter(); const num_args_emited = []; diff --git a/test/parallel/test-event-emitter-set-max-listeners-side-effects.js b/test/parallel/test-event-emitter-set-max-listeners-side-effects.js index cadaf3adc36014..64f7420fb2cfe6 100644 --- a/test/parallel/test-event-emitter-set-max-listeners-side-effects.js +++ b/test/parallel/test-event-emitter-set-max-listeners-side-effects.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var events = require('events'); +const assert = require('assert'); +const events = require('events'); var e = new events.EventEmitter(); diff --git a/test/parallel/test-event-emitter-subclass.js b/test/parallel/test-event-emitter-subclass.js index d2651defeeaa23..27532dae46e4e4 100644 --- a/test/parallel/test-event-emitter-subclass.js +++ b/test/parallel/test-event-emitter-subclass.js @@ -1,8 +1,8 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); -var EventEmitter = require('events').EventEmitter; -var util = require('util'); +const assert = require('assert'); +const EventEmitter = require('events').EventEmitter; +const util = require('util'); util.inherits(MyEE, EventEmitter); diff --git a/test/parallel/test-exception-handler.js b/test/parallel/test-exception-handler.js index e0e1b0086d9a7f..1e2b2b89010d4e 100644 --- a/test/parallel/test-exception-handler.js +++ b/test/parallel/test-exception-handler.js @@ -1,6 +1,6 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); +const assert = require('assert'); var MESSAGE = 'catch me if you can'; diff --git a/test/parallel/test-fs-access.js b/test/parallel/test-fs-access.js index 6da26fe47beb92..36268351fa16a2 100644 --- a/test/parallel/test-fs-access.js +++ b/test/parallel/test-fs-access.js @@ -1,8 +1,8 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var fs = require('fs'); -var path = require('path'); +const common = require('../common'); +const assert = require('assert'); +const fs = require('fs'); +const path = require('path'); var doesNotExist = path.join(common.tmpDir, '__this_should_not_exist'); var readOnlyFile = path.join(common.tmpDir, 'read_only_file'); var readWriteFile = path.join(common.tmpDir, 'read_write_file'); diff --git a/test/parallel/test-fs-exists.js b/test/parallel/test-fs-exists.js index 83e6adaf1100f7..5f9e9f50bf5d2f 100644 --- a/test/parallel/test-fs-exists.js +++ b/test/parallel/test-fs-exists.js @@ -1,7 +1,7 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); -var fs = require('fs'); +const assert = require('assert'); +const fs = require('fs'); var f = __filename; fs.exists(f, common.mustCall(function(y) { diff --git a/test/parallel/test-fs-long-path.js b/test/parallel/test-fs-long-path.js index 64585467ed6a77..63b00118217288 100644 --- a/test/parallel/test-fs-long-path.js +++ b/test/parallel/test-fs-long-path.js @@ -1,7 +1,7 @@ 'use strict'; -var common = require('../common'); -var fs = require('fs'); -var path = require('path'); +const common = require('../common'); +const fs = require('fs'); +const path = require('path'); if (!common.isWindows) { common.skip('this test is Windows-specific.'); diff --git a/test/parallel/test-fs-mkdir.js b/test/parallel/test-fs-mkdir.js index 2b8e8b8f026637..620231102273e3 100644 --- a/test/parallel/test-fs-mkdir.js +++ b/test/parallel/test-fs-mkdir.js @@ -1,7 +1,7 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var fs = require('fs'); +const common = require('../common'); +const assert = require('assert'); +const fs = require('fs'); function unlink(pathname) { try { diff --git a/test/parallel/test-fs-null-bytes.js b/test/parallel/test-fs-null-bytes.js index e04aa1cb76cb6f..fa29e64c9b2382 100644 --- a/test/parallel/test-fs-null-bytes.js +++ b/test/parallel/test-fs-null-bytes.js @@ -1,7 +1,7 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var fs = require('fs'); +const common = require('../common'); +const assert = require('assert'); +const fs = require('fs'); function check(async, sync) { const expected = /Path must be a string without null bytes/; diff --git a/test/parallel/test-fs-open-flags.js b/test/parallel/test-fs-open-flags.js index 2002d5a448a830..6c2fa9d2806dde 100644 --- a/test/parallel/test-fs-open-flags.js +++ b/test/parallel/test-fs-open-flags.js @@ -1,9 +1,9 @@ // Flags: --expose_internals 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); -var fs = require('fs'); +const fs = require('fs'); var O_APPEND = fs.constants.O_APPEND || 0; var O_CREAT = fs.constants.O_CREAT || 0; diff --git a/test/parallel/test-fs-read-stream-fd.js b/test/parallel/test-fs-read-stream-fd.js index 5af5200e30eb68..3ac432be32f375 100644 --- a/test/parallel/test-fs-read-stream-fd.js +++ b/test/parallel/test-fs-read-stream-fd.js @@ -1,8 +1,8 @@ 'use strict'; const common = require('../common'); -var fs = require('fs'); -var assert = require('assert'); -var path = require('path'); +const fs = require('fs'); +const assert = require('assert'); +const path = require('path'); var file = path.join(common.tmpDir, '/read_stream_fd_test.txt'); var input = 'hello world'; var output = ''; diff --git a/test/parallel/test-fs-readfile-zero-byte-liar.js b/test/parallel/test-fs-readfile-zero-byte-liar.js index c3887979bb0b4a..82037a77e62122 100644 --- a/test/parallel/test-fs-readfile-zero-byte-liar.js +++ b/test/parallel/test-fs-readfile-zero-byte-liar.js @@ -1,7 +1,7 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); -var fs = require('fs'); +const assert = require('assert'); +const fs = require('fs'); const dataExpected = fs.readFileSync(__filename, 'utf8'); diff --git a/test/parallel/test-fs-sir-writes-alot.js b/test/parallel/test-fs-sir-writes-alot.js index 8e1385ed4da2a0..85feac59dda321 100644 --- a/test/parallel/test-fs-sir-writes-alot.js +++ b/test/parallel/test-fs-sir-writes-alot.js @@ -1,8 +1,8 @@ 'use strict'; -var common = require('../common'); -var fs = require('fs'); -var assert = require('assert'); -var join = require('path').join; +const common = require('../common'); +const fs = require('fs'); +const assert = require('assert'); +const join = require('path').join; var filename = join(common.tmpDir, 'out.txt'); diff --git a/test/parallel/test-fs-stat.js b/test/parallel/test-fs-stat.js index 2c844452f05540..48e59b884096f5 100644 --- a/test/parallel/test-fs-stat.js +++ b/test/parallel/test-fs-stat.js @@ -1,7 +1,7 @@ /* eslint-disable strict */ const common = require('../common'); -var assert = require('assert'); -var fs = require('fs'); +const assert = require('assert'); +const fs = require('fs'); fs.stat('.', common.mustCall(function(err, stats) { assert.ifError(err); diff --git a/test/parallel/test-fs-stream-double-close.js b/test/parallel/test-fs-stream-double-close.js index df5010293729a3..ae6429a62b4f3c 100644 --- a/test/parallel/test-fs-stream-double-close.js +++ b/test/parallel/test-fs-stream-double-close.js @@ -1,6 +1,6 @@ 'use strict'; -var common = require('../common'); -var fs = require('fs'); +const common = require('../common'); +const fs = require('fs'); common.refreshTmpDir(); diff --git a/test/parallel/test-fs-symlink-dir-junction-relative.js b/test/parallel/test-fs-symlink-dir-junction-relative.js index d4e32c4b7eeb5a..814b0c678eb3ef 100644 --- a/test/parallel/test-fs-symlink-dir-junction-relative.js +++ b/test/parallel/test-fs-symlink-dir-junction-relative.js @@ -1,10 +1,10 @@ 'use strict'; // Test creating and resolving relative junction or symbolic link -var common = require('../common'); -var assert = require('assert'); -var path = require('path'); -var fs = require('fs'); +const common = require('../common'); +const assert = require('assert'); +const path = require('path'); +const fs = require('fs'); var linkPath1 = path.join(common.tmpDir, 'junction1'); var linkPath2 = path.join(common.tmpDir, 'junction2'); diff --git a/test/parallel/test-fs-sync-fd-leak.js b/test/parallel/test-fs-sync-fd-leak.js index f7cfd25f4b9b4c..67150f637dd7cc 100644 --- a/test/parallel/test-fs-sync-fd-leak.js +++ b/test/parallel/test-fs-sync-fd-leak.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var fs = require('fs'); +const assert = require('assert'); +const fs = require('fs'); // ensure that (read|write|append)FileSync() closes the file descriptor fs.openSync = function() { diff --git a/test/parallel/test-fs-truncate-GH-6233.js b/test/parallel/test-fs-truncate-GH-6233.js index acfdd1ccae1259..ee6ca1ca132b03 100644 --- a/test/parallel/test-fs-truncate-GH-6233.js +++ b/test/parallel/test-fs-truncate-GH-6233.js @@ -1,7 +1,7 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var fs = require('fs'); +const common = require('../common'); +const assert = require('assert'); +const fs = require('fs'); var filename = common.tmpDir + '/truncate-file.txt'; diff --git a/test/parallel/test-fs-utimes.js b/test/parallel/test-fs-utimes.js index 108ca7c7d71c03..b28a2b96e2075e 100644 --- a/test/parallel/test-fs-utimes.js +++ b/test/parallel/test-fs-utimes.js @@ -1,8 +1,8 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var util = require('util'); -var fs = require('fs'); +const common = require('../common'); +const assert = require('assert'); +const util = require('util'); +const fs = require('fs'); let tests_ok = 0; let tests_run = 0; diff --git a/test/parallel/test-fs-write-file-buffer.js b/test/parallel/test-fs-write-file-buffer.js index a23ccc21336976..e2c7b1d01e4241 100644 --- a/test/parallel/test-fs-write-file-buffer.js +++ b/test/parallel/test-fs-write-file-buffer.js @@ -1,8 +1,8 @@ 'use strict'; -var common = require('../common'); -var join = require('path').join; -var util = require('util'); -var fs = require('fs'); +const common = require('../common'); +const join = require('path').join; +const util = require('util'); +const fs = require('fs'); var data = [ '/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAUDBAQEAwUEBAQFBQUGBwwIBwcH', diff --git a/test/parallel/test-fs-write-file-sync.js b/test/parallel/test-fs-write-file-sync.js index 7ae9e122cae8be..ece5ba48df754d 100644 --- a/test/parallel/test-fs-write-file-sync.js +++ b/test/parallel/test-fs-write-file-sync.js @@ -1,8 +1,8 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var path = require('path'); -var fs = require('fs'); +const common = require('../common'); +const assert = require('assert'); +const path = require('path'); +const fs = require('fs'); var openCount = 0; var mode; var content; diff --git a/test/parallel/test-fs-write-stream-end.js b/test/parallel/test-fs-write-stream-end.js index ade6777d5f68ac..6329aee4167d7b 100644 --- a/test/parallel/test-fs-write-stream-end.js +++ b/test/parallel/test-fs-write-stream-end.js @@ -1,8 +1,8 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var path = require('path'); -var fs = require('fs'); +const common = require('../common'); +const assert = require('assert'); +const path = require('path'); +const fs = require('fs'); common.refreshTmpDir(); diff --git a/test/parallel/test-fs-write-stream-err.js b/test/parallel/test-fs-write-stream-err.js index c1151b12531f92..22137329bfa181 100644 --- a/test/parallel/test-fs-write-stream-err.js +++ b/test/parallel/test-fs-write-stream-err.js @@ -1,7 +1,7 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var fs = require('fs'); +const common = require('../common'); +const assert = require('assert'); +const fs = require('fs'); common.refreshTmpDir(); diff --git a/test/parallel/test-fs-write-string-coerce.js b/test/parallel/test-fs-write-string-coerce.js index 75f689b94b2c47..4179ba0332121f 100644 --- a/test/parallel/test-fs-write-string-coerce.js +++ b/test/parallel/test-fs-write-string-coerce.js @@ -1,9 +1,9 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var path = require('path'); -var Buffer = require('buffer').Buffer; -var fs = require('fs'); +const common = require('../common'); +const assert = require('assert'); +const path = require('path'); +const Buffer = require('buffer').Buffer; +const fs = require('fs'); common.refreshTmpDir(); diff --git a/test/parallel/test-global.js b/test/parallel/test-global.js index 270faf1b7768a6..d88f0895869997 100644 --- a/test/parallel/test-global.js +++ b/test/parallel/test-global.js @@ -15,8 +15,8 @@ assert.strictEqual('bar', baseBar, // eslint-disable-line no-undef 'global.x -> x in base level not working'); -var module = require(path.join(common.fixturesDir, 'global', 'plain')); -const fooBar = module.fooBar; +const mod = require(path.join(common.fixturesDir, 'global', 'plain')); +const fooBar = mod.fooBar; assert.strictEqual('foo', fooBar.foo, 'x -> global.x in sub level not working'); diff --git a/test/parallel/test-http-1.0-keep-alive.js b/test/parallel/test-http-1.0-keep-alive.js index 383f67c90a31b5..301c054fc9a246 100644 --- a/test/parallel/test-http-1.0-keep-alive.js +++ b/test/parallel/test-http-1.0-keep-alive.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var http = require('http'); -var net = require('net'); +const http = require('http'); +const net = require('net'); // Check that our HTTP server correctly handles HTTP/1.0 keep-alive requests. check([{ diff --git a/test/parallel/test-http-1.0.js b/test/parallel/test-http-1.0.js index d01613de45452d..926497d002e473 100644 --- a/test/parallel/test-http-1.0.js +++ b/test/parallel/test-http-1.0.js @@ -1,8 +1,8 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); -var http = require('http'); +const common = require('../common'); +const assert = require('assert'); +const net = require('net'); +const http = require('http'); var body = 'hello world\n'; diff --git a/test/parallel/test-http-abort-before-end.js b/test/parallel/test-http-abort-before-end.js index ee22dc847b5882..5e0baf3cdfdbd6 100644 --- a/test/parallel/test-http-abort-before-end.js +++ b/test/parallel/test-http-abort-before-end.js @@ -1,7 +1,7 @@ 'use strict'; const common = require('../common'); -var http = require('http'); -var assert = require('assert'); +const http = require('http'); +const assert = require('assert'); var server = http.createServer(common.fail); diff --git a/test/parallel/test-http-abort-client.js b/test/parallel/test-http-abort-client.js index addcec1ef3e9f9..9ee2974c46514d 100644 --- a/test/parallel/test-http-abort-client.js +++ b/test/parallel/test-http-abort-client.js @@ -1,6 +1,6 @@ 'use strict'; const common = require('../common'); -var http = require('http'); +const http = require('http'); var server = http.Server(function(req, res) { console.log('Server accepted request.'); diff --git a/test/parallel/test-http-agent-destroyed-socket.js b/test/parallel/test-http-agent-destroyed-socket.js index a2693637728439..3a6cc5365812f0 100644 --- a/test/parallel/test-http-agent-destroyed-socket.js +++ b/test/parallel/test-http-agent-destroyed-socket.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var http = require('http'); +const assert = require('assert'); +const http = require('http'); var server = http.createServer(function(req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); diff --git a/test/parallel/test-http-agent-error-on-idle.js b/test/parallel/test-http-agent-error-on-idle.js index 59b0109ef1c398..14a058a6f8f2d9 100644 --- a/test/parallel/test-http-agent-error-on-idle.js +++ b/test/parallel/test-http-agent-error-on-idle.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var http = require('http'); +const assert = require('assert'); +const http = require('http'); var Agent = http.Agent; var server = http.createServer(function(req, res) { diff --git a/test/parallel/test-http-agent-false.js b/test/parallel/test-http-agent-false.js index 96606028bf7a45..65da4b836a9fe1 100644 --- a/test/parallel/test-http-agent-false.js +++ b/test/parallel/test-http-agent-false.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var http = require('http'); +const assert = require('assert'); +const http = require('http'); // sending `agent: false` when `port: null` is also passed in (i.e. the result // of a `url.parse()` call with the default port used, 80 or 443), should not diff --git a/test/parallel/test-http-agent-maxsockets.js b/test/parallel/test-http-agent-maxsockets.js index ea443ff9bd1107..b71cbd95c4556c 100644 --- a/test/parallel/test-http-agent-maxsockets.js +++ b/test/parallel/test-http-agent-maxsockets.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var http = require('http'); +const assert = require('assert'); +const http = require('http'); var agent = new http.Agent({ keepAlive: true, diff --git a/test/parallel/test-http-agent-no-protocol.js b/test/parallel/test-http-agent-no-protocol.js index 94fd525b908c30..e2c748b011f545 100644 --- a/test/parallel/test-http-agent-no-protocol.js +++ b/test/parallel/test-http-agent-no-protocol.js @@ -1,7 +1,7 @@ 'use strict'; const common = require('../common'); -var http = require('http'); -var url = require('url'); +const http = require('http'); +const url = require('url'); var server = http.createServer(common.mustCall(function(req, res) { res.end(); diff --git a/test/parallel/test-http-agent-null.js b/test/parallel/test-http-agent-null.js index f1dfeddea8b0e3..426ec3bb762909 100644 --- a/test/parallel/test-http-agent-null.js +++ b/test/parallel/test-http-agent-null.js @@ -1,6 +1,6 @@ 'use strict'; const common = require('../common'); -var http = require('http'); +const http = require('http'); var server = http.createServer(common.mustCall(function(req, res) { res.end(); diff --git a/test/parallel/test-http-agent.js b/test/parallel/test-http-agent.js index dae982ed51a302..443af96215fd92 100644 --- a/test/parallel/test-http-agent.js +++ b/test/parallel/test-http-agent.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var http = require('http'); +const assert = require('assert'); +const http = require('http'); var server = http.Server(function(req, res) { res.writeHead(200); diff --git a/test/parallel/test-http-automatic-headers.js b/test/parallel/test-http-automatic-headers.js index 600be8e43ee23c..b15330342ce0cb 100644 --- a/test/parallel/test-http-automatic-headers.js +++ b/test/parallel/test-http-automatic-headers.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var http = require('http'); +const assert = require('assert'); +const http = require('http'); var server = http.createServer(function(req, res) { res.setHeader('X-Date', 'foo'); diff --git a/test/parallel/test-http-blank-header.js b/test/parallel/test-http-blank-header.js index 13b1a2f3b0d449..863cbed19d790b 100644 --- a/test/parallel/test-http-blank-header.js +++ b/test/parallel/test-http-blank-header.js @@ -1,8 +1,8 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); -var http = require('http'); -var net = require('net'); +const assert = require('assert'); +const http = require('http'); +const net = require('net'); var server = http.createServer(common.mustCall(function(req, res) { assert.equal('GET', req.method); diff --git a/test/parallel/test-http-buffer-sanity.js b/test/parallel/test-http-buffer-sanity.js index 542d4ad5af2cbc..d71f3bdb783267 100644 --- a/test/parallel/test-http-buffer-sanity.js +++ b/test/parallel/test-http-buffer-sanity.js @@ -1,7 +1,7 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); -var http = require('http'); +const assert = require('assert'); +const http = require('http'); var bufferSize = 5 * 1024 * 1024; var measuredSize = 0; diff --git a/test/parallel/test-http-byteswritten.js b/test/parallel/test-http-byteswritten.js index bb914439a76b78..1ef5f2398d77ed 100644 --- a/test/parallel/test-http-byteswritten.js +++ b/test/parallel/test-http-byteswritten.js @@ -1,7 +1,7 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); -var http = require('http'); +const assert = require('assert'); +const http = require('http'); var body = 'hello world\n'; diff --git a/test/parallel/test-http-chunked-304.js b/test/parallel/test-http-chunked-304.js index 82fe138fd926da..b130004d1a83e7 100644 --- a/test/parallel/test-http-chunked-304.js +++ b/test/parallel/test-http-chunked-304.js @@ -1,8 +1,8 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); -var net = require('net'); +const common = require('../common'); +const assert = require('assert'); +const http = require('http'); +const net = require('net'); // RFC 2616, section 10.2.5: // diff --git a/test/parallel/test-http-chunked.js b/test/parallel/test-http-chunked.js index bb91dadd159de5..d8891db6c75aea 100644 --- a/test/parallel/test-http-chunked.js +++ b/test/parallel/test-http-chunked.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var http = require('http'); +const assert = require('assert'); +const http = require('http'); var UTF8_STRING = '南越国是前203年至前111年存在于岭南地区的一个国家,' + '国都位于番禺,疆域包括今天中国的广东、广西两省区的大部份地区,福建省、湖南、' + diff --git a/test/parallel/test-http-client-abort-event.js b/test/parallel/test-http-client-abort-event.js index c0c1f9e4c73c92..00c989ca919dc7 100644 --- a/test/parallel/test-http-client-abort-event.js +++ b/test/parallel/test-http-client-abort-event.js @@ -1,6 +1,6 @@ 'use strict'; const common = require('../common'); -var http = require('http'); +const http = require('http'); var server = http.createServer(function(req, res) { res.end(); }); diff --git a/test/parallel/test-http-client-abort2.js b/test/parallel/test-http-client-abort2.js index 30269a193f0eab..346b781ef08dfd 100644 --- a/test/parallel/test-http-client-abort2.js +++ b/test/parallel/test-http-client-abort2.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var http = require('http'); +const http = require('http'); var server = http.createServer(function(req, res) { res.end('Hello'); diff --git a/test/parallel/test-http-client-agent.js b/test/parallel/test-http-client-agent.js index 36ed24ec526255..8093100fce2b88 100644 --- a/test/parallel/test-http-client-agent.js +++ b/test/parallel/test-http-client-agent.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var http = require('http'); +const assert = require('assert'); +const http = require('http'); var name; var max = 3; diff --git a/test/parallel/test-http-client-default-headers-exist.js b/test/parallel/test-http-client-default-headers-exist.js index 9b73f2db32aad6..3a1f52819335b8 100644 --- a/test/parallel/test-http-client-default-headers-exist.js +++ b/test/parallel/test-http-client-default-headers-exist.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var http = require('http'); +const assert = require('assert'); +const http = require('http'); var expectedHeaders = { 'DELETE': ['host', 'connection'], diff --git a/test/parallel/test-http-client-encoding.js b/test/parallel/test-http-client-encoding.js index b02463aa5188d5..d2aa8fdcbbac46 100644 --- a/test/parallel/test-http-client-encoding.js +++ b/test/parallel/test-http-client-encoding.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var http = require('http'); +const http = require('http'); http.createServer(function(req, res) { res.end('ok\n'); diff --git a/test/parallel/test-http-client-get-url.js b/test/parallel/test-http-client-get-url.js index 51f8413b675244..0fc8cf47da5b3d 100644 --- a/test/parallel/test-http-client-get-url.js +++ b/test/parallel/test-http-client-get-url.js @@ -1,7 +1,7 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); -var http = require('http'); +const assert = require('assert'); +const http = require('http'); var server = http.createServer(common.mustCall(function(req, res) { assert.equal('GET', req.method); diff --git a/test/parallel/test-http-client-parse-error.js b/test/parallel/test-http-client-parse-error.js index cd6f135d889534..c7469c1562566a 100644 --- a/test/parallel/test-http-client-parse-error.js +++ b/test/parallel/test-http-client-parse-error.js @@ -1,9 +1,9 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); -var http = require('http'); -var net = require('net'); +const http = require('http'); +const net = require('net'); var connects = 0; var parseErrors = 0; diff --git a/test/parallel/test-http-client-pipe-end.js b/test/parallel/test-http-client-pipe-end.js index 5b2db49435a1b6..04f308e76d8cc5 100644 --- a/test/parallel/test-http-client-pipe-end.js +++ b/test/parallel/test-http-client-pipe-end.js @@ -1,8 +1,8 @@ 'use strict'; // see https://github.com/joyent/node/issues/3257 -var common = require('../common'); -var http = require('http'); +const common = require('../common'); +const http = require('http'); var server = http.createServer(function(req, res) { req.resume(); diff --git a/test/parallel/test-http-client-race-2.js b/test/parallel/test-http-client-race-2.js index 632b9f4a219a92..80a8252528fb0b 100644 --- a/test/parallel/test-http-client-race-2.js +++ b/test/parallel/test-http-client-race-2.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var http = require('http'); -var url = require('url'); +const assert = require('assert'); +const http = require('http'); +const url = require('url'); // // Slight variation on test-http-client-race to test for another race diff --git a/test/parallel/test-http-client-race.js b/test/parallel/test-http-client-race.js index 30ebb34fc7fcff..af8e18686b83d7 100644 --- a/test/parallel/test-http-client-race.js +++ b/test/parallel/test-http-client-race.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var http = require('http'); -var url = require('url'); +const assert = require('assert'); +const http = require('http'); +const url = require('url'); var body1_s = '1111111111111111'; var body2_s = '22222'; diff --git a/test/parallel/test-http-client-read-in-error.js b/test/parallel/test-http-client-read-in-error.js index 142c0ee3715aed..96085ae51f22b6 100644 --- a/test/parallel/test-http-client-read-in-error.js +++ b/test/parallel/test-http-client-read-in-error.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var net = require('net'); -var http = require('http'); -var util = require('util'); +const net = require('net'); +const http = require('http'); +const util = require('util'); function Agent() { http.Agent.call(this); diff --git a/test/parallel/test-http-client-timeout-agent.js b/test/parallel/test-http-client-timeout-agent.js index 4ed217c171f28a..84db25f7b023c3 100644 --- a/test/parallel/test-http-client-timeout-agent.js +++ b/test/parallel/test-http-client-timeout-agent.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var http = require('http'); +const assert = require('assert'); +const http = require('http'); var requests_sent = 0; var requests_done = 0; diff --git a/test/parallel/test-http-client-timeout.js b/test/parallel/test-http-client-timeout.js index 402736e9b7d47c..e26c93fe0026a8 100644 --- a/test/parallel/test-http-client-timeout.js +++ b/test/parallel/test-http-client-timeout.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var http = require('http'); +const assert = require('assert'); +const http = require('http'); var options = { method: 'GET', diff --git a/test/parallel/test-http-client-upload-buf.js b/test/parallel/test-http-client-upload-buf.js index 512a438ef82115..e17a2c5ee5698b 100644 --- a/test/parallel/test-http-client-upload-buf.js +++ b/test/parallel/test-http-client-upload-buf.js @@ -1,7 +1,7 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); -var http = require('http'); +const assert = require('assert'); +const http = require('http'); var N = 1024; diff --git a/test/parallel/test-http-client-upload.js b/test/parallel/test-http-client-upload.js index a5c8f5b92bc761..ce2608fcfde0f3 100644 --- a/test/parallel/test-http-client-upload.js +++ b/test/parallel/test-http-client-upload.js @@ -1,7 +1,7 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); -var http = require('http'); +const assert = require('assert'); +const http = require('http'); var server = http.createServer(common.mustCall(function(req, res) { assert.equal('POST', req.method); diff --git a/test/parallel/test-http-conn-reset.js b/test/parallel/test-http-conn-reset.js index d7852bf32c9ec3..f244838bc47013 100644 --- a/test/parallel/test-http-conn-reset.js +++ b/test/parallel/test-http-conn-reset.js @@ -1,8 +1,8 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); -var http = require('http'); -var net = require('net'); +const assert = require('assert'); +const http = require('http'); +const net = require('net'); var options = { host: '127.0.0.1', diff --git a/test/parallel/test-http-content-length.js b/test/parallel/test-http-content-length.js index 9104e5ba0d74cb..fd1c8004ffef2d 100644 --- a/test/parallel/test-http-content-length.js +++ b/test/parallel/test-http-content-length.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var http = require('http'); +const assert = require('assert'); +const http = require('http'); var expectedHeadersMultipleWrites = { 'connection': 'close', diff --git a/test/parallel/test-http-contentLength0.js b/test/parallel/test-http-contentLength0.js index 19e90e151382be..c4c8699df7fc47 100644 --- a/test/parallel/test-http-contentLength0.js +++ b/test/parallel/test-http-contentLength0.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var http = require('http'); +const http = require('http'); // Simple test of Node's HTTP Client choking on a response // with a 'Content-Length: 0 ' response header. diff --git a/test/parallel/test-http-date-header.js b/test/parallel/test-http-date-header.js index e0b93c1f8718f5..5b9df4c1747bb0 100644 --- a/test/parallel/test-http-date-header.js +++ b/test/parallel/test-http-date-header.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var http = require('http'); +const assert = require('assert'); +const http = require('http'); var testResBody = 'other stuff!\n'; diff --git a/test/parallel/test-http-default-encoding.js b/test/parallel/test-http-default-encoding.js index 4fb386bf4bb0e8..0026540373c0aa 100644 --- a/test/parallel/test-http-default-encoding.js +++ b/test/parallel/test-http-default-encoding.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var http = require('http'); +const assert = require('assert'); +const http = require('http'); var expected = 'This is a unicode text: سلام'; var result = ''; diff --git a/test/parallel/test-http-default-port.js b/test/parallel/test-http-default-port.js index fcea5aac7b156b..d26150f4a824ed 100644 --- a/test/parallel/test-http-default-port.js +++ b/test/parallel/test-http-default-port.js @@ -1,6 +1,13 @@ 'use strict'; const common = require('../common'); + +if (!common.hasCrypto) { + common.skip('missing crypto'); + return; +} + const http = require('http'); +const https = require('https'); const assert = require('assert'); const hostExpect = 'localhost'; const fs = require('fs'); @@ -13,12 +20,6 @@ const options = { let gotHttpsResp = false; let gotHttpResp = false; -if (common.hasCrypto) { - var https = require('https'); -} else { - common.skip('missing crypto'); -} - process.on('exit', function() { if (common.hasCrypto) { assert(gotHttpsResp); diff --git a/test/parallel/test-http-destroyed-socket-write2.js b/test/parallel/test-http-destroyed-socket-write2.js index 7d2f235a27f7fb..bb3f5d64cbca8b 100644 --- a/test/parallel/test-http-destroyed-socket-write2.js +++ b/test/parallel/test-http-destroyed-socket-write2.js @@ -1,11 +1,11 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); // Verify that ECONNRESET is raised when writing to a http request // where the server has ended the socket. -var http = require('http'); +const http = require('http'); var server = http.createServer(function(req, res) { setImmediate(function() { res.destroy(); diff --git a/test/parallel/test-http-dns-error.js b/test/parallel/test-http-dns-error.js index 5e15ab9a3fa0da..25224902513049 100644 --- a/test/parallel/test-http-dns-error.js +++ b/test/parallel/test-http-dns-error.js @@ -1,15 +1,15 @@ 'use strict'; const common = require('../common'); -const assert = require('assert'); - -const http = require('http'); -if (common.hasCrypto) { - var https = require('https'); -} else { +if (!common.hasCrypto) { common.skip('missing crypto'); + return; } +const assert = require('assert'); +const http = require('http'); +const https = require('https'); + const host = '*'.repeat(256); function do_not_call() { diff --git a/test/parallel/test-http-eof-on-connect.js b/test/parallel/test-http-eof-on-connect.js index 6f70dc239172ee..765d8b35e7cfd3 100644 --- a/test/parallel/test-http-eof-on-connect.js +++ b/test/parallel/test-http-eof-on-connect.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var net = require('net'); -var http = require('http'); +const net = require('net'); +const http = require('http'); // This is a regression test for https://github.com/joyent/node/issues/44 // It is separate from test-http-malformed-request.js because it is only diff --git a/test/parallel/test-http-exceptions.js b/test/parallel/test-http-exceptions.js index b9958007609fd0..8ee46316e98b23 100644 --- a/test/parallel/test-http-exceptions.js +++ b/test/parallel/test-http-exceptions.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var http = require('http'); +const http = require('http'); var server = http.createServer(function(req, res) { intentionally_not_defined(); // eslint-disable-line no-undef diff --git a/test/parallel/test-http-expect-continue.js b/test/parallel/test-http-expect-continue.js index a0ebf83b3301a5..954d6b6211c27e 100644 --- a/test/parallel/test-http-expect-continue.js +++ b/test/parallel/test-http-expect-continue.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var http = require('http'); +const assert = require('assert'); +const http = require('http'); var outstanding_reqs = 0; var test_req_body = 'some stuff...\n'; diff --git a/test/parallel/test-http-extra-response.js b/test/parallel/test-http-extra-response.js index 8364684a1ec23f..1866d88a33cbd5 100644 --- a/test/parallel/test-http-extra-response.js +++ b/test/parallel/test-http-extra-response.js @@ -1,8 +1,8 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); -var http = require('http'); -var net = require('net'); +const assert = require('assert'); +const http = require('http'); +const net = require('net'); // If an HTTP server is broken and sends data after the end of the response, // node should ignore it and drop the connection. diff --git a/test/parallel/test-http-flush.js b/test/parallel/test-http-flush.js index 8b3dacb803d9bd..524965d2d7af5f 100644 --- a/test/parallel/test-http-flush.js +++ b/test/parallel/test-http-flush.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var http = require('http'); +const http = require('http'); http.createServer(function(req, res) { res.end('ok'); diff --git a/test/parallel/test-http-full-response.js b/test/parallel/test-http-full-response.js index e59456a710aac3..be6749cc042f0d 100644 --- a/test/parallel/test-http-full-response.js +++ b/test/parallel/test-http-full-response.js @@ -1,9 +1,9 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); // This test requires the program 'ab' -var http = require('http'); -var exec = require('child_process').exec; +const http = require('http'); +const exec = require('child_process').exec; var bodyLength = 12345; diff --git a/test/parallel/test-http-get-pipeline-problem.js b/test/parallel/test-http-get-pipeline-problem.js index cc681f675a791e..d4e075d229184f 100644 --- a/test/parallel/test-http-get-pipeline-problem.js +++ b/test/parallel/test-http-get-pipeline-problem.js @@ -2,10 +2,10 @@ // In previous versions of Node.js (e.g., 0.6.0), this sort of thing would halt // after http.globalAgent.maxSockets number of files. // See https://groups.google.com/forum/#!topic/nodejs-dev/V5fB69hFa9o -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); -var fs = require('fs'); +const common = require('../common'); +const assert = require('assert'); +const http = require('http'); +const fs = require('fs'); http.globalAgent.maxSockets = 1; diff --git a/test/parallel/test-http-head-request.js b/test/parallel/test-http-head-request.js index e8626b18811bda..eb31930a343c4d 100644 --- a/test/parallel/test-http-head-request.js +++ b/test/parallel/test-http-head-request.js @@ -1,6 +1,6 @@ 'use strict'; const common = require('../common'); -var http = require('http'); +const http = require('http'); var body = 'hello world\n'; diff --git a/test/parallel/test-http-head-response-has-no-body-end.js b/test/parallel/test-http-head-response-has-no-body-end.js index 87ce957df3499f..cd2c22c8fa1926 100644 --- a/test/parallel/test-http-head-response-has-no-body-end.js +++ b/test/parallel/test-http-head-response-has-no-body-end.js @@ -1,6 +1,6 @@ 'use strict'; const common = require('../common'); -var http = require('http'); +const http = require('http'); // This test is to make sure that when the HTTP server // responds to a HEAD request with data to res.end, diff --git a/test/parallel/test-http-head-response-has-no-body.js b/test/parallel/test-http-head-response-has-no-body.js index 445b522b8dea51..17107d3b6743a5 100644 --- a/test/parallel/test-http-head-response-has-no-body.js +++ b/test/parallel/test-http-head-response-has-no-body.js @@ -1,6 +1,6 @@ 'use strict'; const common = require('../common'); -var http = require('http'); +const http = require('http'); // This test is to make sure that when the HTTP server // responds to a HEAD request, it does not send any body. diff --git a/test/parallel/test-http-header-read.js b/test/parallel/test-http-header-read.js index b726fe130f0ee4..42d7e9af5f8566 100644 --- a/test/parallel/test-http-header-read.js +++ b/test/parallel/test-http-header-read.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var http = require('http'); +const assert = require('assert'); +const http = require('http'); // Verify that ServerResponse.getHeader() works correctly even after // the response header has been sent. Issue 752 on github. diff --git a/test/parallel/test-http-hex-write.js b/test/parallel/test-http-hex-write.js index adfe18077a8259..2fcabb0691ec22 100644 --- a/test/parallel/test-http-hex-write.js +++ b/test/parallel/test-http-hex-write.js @@ -1,8 +1,8 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); +const assert = require('assert'); -var http = require('http'); +const http = require('http'); var expect = 'hex\nutf8\n'; diff --git a/test/parallel/test-http-keep-alive-close-on-header.js b/test/parallel/test-http-keep-alive-close-on-header.js index d9396b258e7515..b69e90c03809f2 100644 --- a/test/parallel/test-http-keep-alive-close-on-header.js +++ b/test/parallel/test-http-keep-alive-close-on-header.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var http = require('http'); +const assert = require('assert'); +const http = require('http'); var body = 'hello world\n'; var headers = {'connection': 'keep-alive'}; diff --git a/test/parallel/test-http-keepalive-client.js b/test/parallel/test-http-keepalive-client.js index 955fc006e22d58..55c3342a115f90 100644 --- a/test/parallel/test-http-keepalive-client.js +++ b/test/parallel/test-http-keepalive-client.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); -var http = require('http'); +const http = require('http'); var serverSocket = null; diff --git a/test/parallel/test-http-keepalive-maxsockets.js b/test/parallel/test-http-keepalive-maxsockets.js index 6f1476d0ce3aed..ffe1472a3cba85 100644 --- a/test/parallel/test-http-keepalive-maxsockets.js +++ b/test/parallel/test-http-keepalive-maxsockets.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); -var http = require('http'); +const http = require('http'); var serverSockets = []; diff --git a/test/parallel/test-http-keepalive-request.js b/test/parallel/test-http-keepalive-request.js index daae5aa9944294..102f65bb08526f 100644 --- a/test/parallel/test-http-keepalive-request.js +++ b/test/parallel/test-http-keepalive-request.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); -var http = require('http'); +const http = require('http'); var serverSocket = null; diff --git a/test/parallel/test-http-localaddress-bind-error.js b/test/parallel/test-http-localaddress-bind-error.js index 0b828910f12873..0290c6a584c959 100644 --- a/test/parallel/test-http-localaddress-bind-error.js +++ b/test/parallel/test-http-localaddress-bind-error.js @@ -1,6 +1,6 @@ 'use strict'; const common = require('../common'); -var http = require('http'); +const http = require('http'); var invalidLocalAddress = '1.2.3.4'; diff --git a/test/parallel/test-http-malformed-request.js b/test/parallel/test-http-malformed-request.js index 647b67bcd3ff78..6739a44b6c82f9 100644 --- a/test/parallel/test-http-malformed-request.js +++ b/test/parallel/test-http-malformed-request.js @@ -1,9 +1,9 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var net = require('net'); -var http = require('http'); -var url = require('url'); +const assert = require('assert'); +const net = require('net'); +const http = require('http'); +const url = require('url'); // Make sure no exceptions are thrown when receiving malformed HTTP // requests. diff --git a/test/parallel/test-http-many-ended-pipelines.js b/test/parallel/test-http-many-ended-pipelines.js index 7966f47a9efa19..5fa8e53e01d1d0 100644 --- a/test/parallel/test-http-many-ended-pipelines.js +++ b/test/parallel/test-http-many-ended-pipelines.js @@ -8,8 +8,8 @@ console.trace = function() { throw new Error('no tracing should happen here'); }; -var http = require('http'); -var net = require('net'); +const http = require('http'); +const net = require('net'); var numRequests = 20; var first = false; diff --git a/test/parallel/test-http-max-headers-count.js b/test/parallel/test-http-max-headers-count.js index 2d68ead110fc6c..0abddbd2cbf5c4 100644 --- a/test/parallel/test-http-max-headers-count.js +++ b/test/parallel/test-http-max-headers-count.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var http = require('http'); +const assert = require('assert'); +const http = require('http'); var requests = 0; var responses = 0; diff --git a/test/parallel/test-http-methods.js b/test/parallel/test-http-methods.js index d3d4fedd46361b..6ba02807f8706b 100644 --- a/test/parallel/test-http-methods.js +++ b/test/parallel/test-http-methods.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var http = require('http'); -var util = require('util'); +const assert = require('assert'); +const http = require('http'); +const util = require('util'); assert(Array.isArray(http.METHODS)); assert(http.METHODS.length > 0); diff --git a/test/parallel/test-http-multi-line-headers.js b/test/parallel/test-http-multi-line-headers.js index df333cdd62bf9b..9c0d758ed571ad 100644 --- a/test/parallel/test-http-multi-line-headers.js +++ b/test/parallel/test-http-multi-line-headers.js @@ -1,9 +1,9 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); +const assert = require('assert'); -var http = require('http'); -var net = require('net'); +const http = require('http'); +const net = require('net'); var server = net.createServer(function(conn) { var body = 'Yet another node.js server.'; diff --git a/test/parallel/test-http-mutable-headers.js b/test/parallel/test-http-mutable-headers.js index 0228a4e216ec46..ecb777c09b683d 100644 --- a/test/parallel/test-http-mutable-headers.js +++ b/test/parallel/test-http-mutable-headers.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var http = require('http'); +const assert = require('assert'); +const http = require('http'); // Simple test of Node's HTTP Client mutable headers // OutgoingMessage.prototype.setHeader(name, value) diff --git a/test/parallel/test-http-no-content-length.js b/test/parallel/test-http-no-content-length.js index b27ffda727129e..a393d58d57413f 100644 --- a/test/parallel/test-http-no-content-length.js +++ b/test/parallel/test-http-no-content-length.js @@ -1,8 +1,8 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); -var net = require('net'); -var http = require('http'); +const assert = require('assert'); +const net = require('net'); +const http = require('http'); var server = net.createServer(function(socket) { // Neither Content-Length nor Connection diff --git a/test/parallel/test-http-outgoing-finish.js b/test/parallel/test-http-outgoing-finish.js index 56ce777cb3eaaf..06630e61787e01 100644 --- a/test/parallel/test-http-outgoing-finish.js +++ b/test/parallel/test-http-outgoing-finish.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); -var http = require('http'); +const http = require('http'); http.createServer(function(req, res) { req.resume(); diff --git a/test/parallel/test-http-parser-bad-ref.js b/test/parallel/test-http-parser-bad-ref.js index 73d5f7eb13049c..9eddb2bb3bcd77 100644 --- a/test/parallel/test-http-parser-bad-ref.js +++ b/test/parallel/test-http-parser-bad-ref.js @@ -5,7 +5,7 @@ // Flags: --expose_gc require('../common'); -var assert = require('assert'); +const assert = require('assert'); var HTTPParser = process.binding('http_parser').HTTPParser; var kOnHeaders = HTTPParser.kOnHeaders | 0; diff --git a/test/parallel/test-http-parser-free.js b/test/parallel/test-http-parser-free.js index 125374bbedde63..e9ddfa27e5a5c5 100644 --- a/test/parallel/test-http-parser-free.js +++ b/test/parallel/test-http-parser-free.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var http = require('http'); +const assert = require('assert'); +const http = require('http'); var N = 100; var responses = 0; diff --git a/test/parallel/test-http-parser.js b/test/parallel/test-http-parser.js index abc1d096dff0d8..8617a093fbd311 100644 --- a/test/parallel/test-http-parser.js +++ b/test/parallel/test-http-parser.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); const binding = process.binding('http_parser'); const methods = binding.methods; diff --git a/test/parallel/test-http-pause.js b/test/parallel/test-http-pause.js index f6562b3afc94ae..3c96dc6792fdad 100644 --- a/test/parallel/test-http-pause.js +++ b/test/parallel/test-http-pause.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var http = require('http'); +const assert = require('assert'); +const http = require('http'); var expectedServer = 'Request Body from Client'; var resultServer = ''; diff --git a/test/parallel/test-http-pipe-fs.js b/test/parallel/test-http-pipe-fs.js index 3205802d7ab0f2..5b3eb87a145a0f 100644 --- a/test/parallel/test-http-pipe-fs.js +++ b/test/parallel/test-http-pipe-fs.js @@ -1,8 +1,8 @@ 'use strict'; -var common = require('../common'); -var http = require('http'); -var fs = require('fs'); -var path = require('path'); +const common = require('../common'); +const http = require('http'); +const fs = require('fs'); +const path = require('path'); common.refreshTmpDir(); diff --git a/test/parallel/test-http-proxy.js b/test/parallel/test-http-proxy.js index 48367caaa7d89e..bfa928afb3de8b 100644 --- a/test/parallel/test-http-proxy.js +++ b/test/parallel/test-http-proxy.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var http = require('http'); -var url = require('url'); +const assert = require('assert'); +const http = require('http'); +const url = require('url'); var cookies = [ 'session_token=; path=/; expires=Sun, 15-Sep-2030 13:48:52 GMT', diff --git a/test/parallel/test-http-raw-headers.js b/test/parallel/test-http-raw-headers.js index 2e2e9631490395..0c7cc18415e914 100644 --- a/test/parallel/test-http-raw-headers.js +++ b/test/parallel/test-http-raw-headers.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); -var http = require('http'); +const http = require('http'); http.createServer(function(req, res) { var expectRawHeaders = [ diff --git a/test/parallel/test-http-remove-header-stays-removed.js b/test/parallel/test-http-remove-header-stays-removed.js index 9b8ff35b0fe5d3..bf417597b18244 100644 --- a/test/parallel/test-http-remove-header-stays-removed.js +++ b/test/parallel/test-http-remove-header-stays-removed.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); -var http = require('http'); +const http = require('http'); var server = http.createServer(function(request, response) { // removed headers should stay removed, even if node automatically adds them diff --git a/test/parallel/test-http-request-end-twice.js b/test/parallel/test-http-request-end-twice.js index 230175be8e95c1..5dd21d06dee6a6 100644 --- a/test/parallel/test-http-request-end-twice.js +++ b/test/parallel/test-http-request-end-twice.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var http = require('http'); +const assert = require('assert'); +const http = require('http'); var server = http.Server(function(req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); diff --git a/test/parallel/test-http-request-end.js b/test/parallel/test-http-request-end.js index 6beedae20d9e00..207c3564fb5519 100644 --- a/test/parallel/test-http-request-end.js +++ b/test/parallel/test-http-request-end.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var http = require('http'); +const assert = require('assert'); +const http = require('http'); var expected = 'Post Body For Test'; diff --git a/test/parallel/test-http-request-methods.js b/test/parallel/test-http-request-methods.js index 7f42a9c00a85f3..b24779adf8f1ab 100644 --- a/test/parallel/test-http-request-methods.js +++ b/test/parallel/test-http-request-methods.js @@ -1,8 +1,8 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); -var net = require('net'); -var http = require('http'); +const assert = require('assert'); +const net = require('net'); +const http = require('http'); // Test that the DELETE, PATCH and PURGE verbs get passed through correctly diff --git a/test/parallel/test-http-res-write-after-end.js b/test/parallel/test-http-res-write-after-end.js index 5a91c556340b1c..d01753b88a5da2 100644 --- a/test/parallel/test-http-res-write-after-end.js +++ b/test/parallel/test-http-res-write-after-end.js @@ -1,7 +1,7 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); -var http = require('http'); +const assert = require('assert'); +const http = require('http'); var server = http.Server(common.mustCall(function(req, res) { res.on('error', common.mustCall(function onResError(err) { diff --git a/test/parallel/test-http-res-write-end-dont-take-array.js b/test/parallel/test-http-res-write-end-dont-take-array.js index 5c14b0678520c4..cbae755b4fbc7f 100644 --- a/test/parallel/test-http-res-write-end-dont-take-array.js +++ b/test/parallel/test-http-res-write-end-dont-take-array.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var http = require('http'); +const assert = require('assert'); +const http = require('http'); var test = 1; diff --git a/test/parallel/test-http-response-close.js b/test/parallel/test-http-response-close.js index 54ee61efccf1ea..6b5966735a156e 100644 --- a/test/parallel/test-http-response-close.js +++ b/test/parallel/test-http-response-close.js @@ -1,6 +1,6 @@ 'use strict'; const common = require('../common'); -var http = require('http'); +const http = require('http'); var server = http.createServer(common.mustCall(function(req, res) { res.writeHead(200); diff --git a/test/parallel/test-http-response-no-headers.js b/test/parallel/test-http-response-no-headers.js index 4a3460bc645140..4c261fc2adc7d4 100644 --- a/test/parallel/test-http-response-no-headers.js +++ b/test/parallel/test-http-response-no-headers.js @@ -1,8 +1,8 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); -var http = require('http'); -var net = require('net'); +const assert = require('assert'); +const http = require('http'); +const net = require('net'); var expected = { '0.9': 'I AM THE WALRUS', diff --git a/test/parallel/test-http-response-readable.js b/test/parallel/test-http-response-readable.js index 1d561ca4704808..f8ecd5bab58e6c 100644 --- a/test/parallel/test-http-response-readable.js +++ b/test/parallel/test-http-response-readable.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var http = require('http'); +const assert = require('assert'); +const http = require('http'); var testServer = new http.Server(function(req, res) { res.writeHead(200); diff --git a/test/parallel/test-http-response-status-message.js b/test/parallel/test-http-response-status-message.js index b14c1f2faf0fce..cfc9e6420905ad 100644 --- a/test/parallel/test-http-response-status-message.js +++ b/test/parallel/test-http-response-status-message.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var http = require('http'); -var net = require('net'); +const assert = require('assert'); +const http = require('http'); +const net = require('net'); var testsComplete = 0; diff --git a/test/parallel/test-http-server-multiheaders.js b/test/parallel/test-http-server-multiheaders.js index 5b41ee89d87e50..b978cb3ad4aad9 100644 --- a/test/parallel/test-http-server-multiheaders.js +++ b/test/parallel/test-http-server-multiheaders.js @@ -4,8 +4,8 @@ // that support it, and dropping duplicates for other fields. require('../common'); -var assert = require('assert'); -var http = require('http'); +const assert = require('assert'); +const http = require('http'); var srv = http.createServer(function(req, res) { assert.equal(req.headers.accept, 'abc, def, ghijklmnopqrst'); diff --git a/test/parallel/test-http-server-multiheaders2.js b/test/parallel/test-http-server-multiheaders2.js index 9f6d41e6a10cea..ba0710f70c839a 100644 --- a/test/parallel/test-http-server-multiheaders2.js +++ b/test/parallel/test-http-server-multiheaders2.js @@ -4,8 +4,8 @@ // that support it, and dropping duplicates for other fields. require('../common'); -var assert = require('assert'); -var http = require('http'); +const assert = require('assert'); +const http = require('http'); var multipleAllowed = [ 'Accept', diff --git a/test/parallel/test-http-server-stale-close.js b/test/parallel/test-http-server-stale-close.js index 819f503de547e4..04e9635403614c 100644 --- a/test/parallel/test-http-server-stale-close.js +++ b/test/parallel/test-http-server-stale-close.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var http = require('http'); -var util = require('util'); -var fork = require('child_process').fork; +const http = require('http'); +const util = require('util'); +const fork = require('child_process').fork; if (process.env.NODE_TEST_FORK_PORT) { var req = http.request({ diff --git a/test/parallel/test-http-server-unconsume.js b/test/parallel/test-http-server-unconsume.js index 76238380c7cfde..fd5486a289e590 100644 --- a/test/parallel/test-http-server-unconsume.js +++ b/test/parallel/test-http-server-unconsume.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var http = require('http'); -var net = require('net'); +const assert = require('assert'); +const http = require('http'); +const net = require('net'); var received = ''; diff --git a/test/parallel/test-http-server.js b/test/parallel/test-http-server.js index 1870bcc7170726..c915272af2b9bf 100644 --- a/test/parallel/test-http-server.js +++ b/test/parallel/test-http-server.js @@ -1,10 +1,10 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var net = require('net'); -var http = require('http'); -var url = require('url'); -var qs = require('querystring'); +const assert = require('assert'); +const net = require('net'); +const http = require('http'); +const url = require('url'); +const qs = require('querystring'); var request_number = 0; var requests_sent = 0; diff --git a/test/parallel/test-http-set-cookies.js b/test/parallel/test-http-set-cookies.js index 1f00ebb65e34de..3fa01655b4acdb 100644 --- a/test/parallel/test-http-set-cookies.js +++ b/test/parallel/test-http-set-cookies.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var http = require('http'); +const assert = require('assert'); +const http = require('http'); var nresponses = 0; diff --git a/test/parallel/test-http-set-timeout-server.js b/test/parallel/test-http-set-timeout-server.js index d530503aa1e9aa..03fca8f219300b 100644 --- a/test/parallel/test-http-set-timeout-server.js +++ b/test/parallel/test-http-set-timeout-server.js @@ -1,8 +1,8 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); -var net = require('net'); +const common = require('../common'); +const assert = require('assert'); +const http = require('http'); +const net = require('net'); var tests = []; diff --git a/test/parallel/test-http-set-trailers.js b/test/parallel/test-http-set-trailers.js index b3f331c6d8b172..e34ea889b0bed4 100644 --- a/test/parallel/test-http-set-trailers.js +++ b/test/parallel/test-http-set-trailers.js @@ -1,8 +1,8 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); -var net = require('net'); +const common = require('../common'); +const assert = require('assert'); +const http = require('http'); +const net = require('net'); var outstanding_reqs = 0; diff --git a/test/parallel/test-http-should-keep-alive.js b/test/parallel/test-http-should-keep-alive.js index 3aaa2d3d73acdc..5cfbd51e76ac9e 100644 --- a/test/parallel/test-http-should-keep-alive.js +++ b/test/parallel/test-http-should-keep-alive.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var http = require('http'); -var net = require('net'); +const assert = require('assert'); +const http = require('http'); +const net = require('net'); var SERVER_RESPONSES = [ 'HTTP/1.0 200 ok\r\nContent-Length: 0\r\n\r\n', diff --git a/test/parallel/test-http-status-code.js b/test/parallel/test-http-status-code.js index c0086a3e3d672f..0b3d204c435a2b 100644 --- a/test/parallel/test-http-status-code.js +++ b/test/parallel/test-http-status-code.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var http = require('http'); +const assert = require('assert'); +const http = require('http'); // Simple test of Node's HTTP ServerResponse.statusCode // ServerResponse.prototype.statusCode diff --git a/test/parallel/test-http-status-message.js b/test/parallel/test-http-status-message.js index 6da4b6e4281171..9a086dcd4673fd 100644 --- a/test/parallel/test-http-status-message.js +++ b/test/parallel/test-http-status-message.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var http = require('http'); -var net = require('net'); +const assert = require('assert'); +const http = require('http'); +const net = require('net'); var s = http.createServer(function(req, res) { res.statusCode = 200; diff --git a/test/parallel/test-http-timeout-overflow.js b/test/parallel/test-http-timeout-overflow.js index 49cf3ec0278fca..c045a28ce75df1 100644 --- a/test/parallel/test-http-timeout-overflow.js +++ b/test/parallel/test-http-timeout-overflow.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); -var http = require('http'); +const http = require('http'); var serverRequests = 0; var clientRequests = 0; diff --git a/test/parallel/test-http-timeout.js b/test/parallel/test-http-timeout.js index b8a28fc2c4cf32..128ca148839b6b 100644 --- a/test/parallel/test-http-timeout.js +++ b/test/parallel/test-http-timeout.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var http = require('http'); +const http = require('http'); var server = http.createServer(function(req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); diff --git a/test/parallel/test-http-upgrade-agent.js b/test/parallel/test-http-upgrade-agent.js index 48eaa16f898021..27f21649a7d508 100644 --- a/test/parallel/test-http-upgrade-agent.js +++ b/test/parallel/test-http-upgrade-agent.js @@ -3,11 +3,11 @@ // the HTTP client. This test uses a raw TCP server to better control server // behavior. -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); -var http = require('http'); -var net = require('net'); +const http = require('http'); +const net = require('net'); // Create a TCP server var srv = net.createServer(function(c) { diff --git a/test/parallel/test-http-upgrade-client.js b/test/parallel/test-http-upgrade-client.js index 51c70122b99d87..f5c25f15d4136c 100644 --- a/test/parallel/test-http-upgrade-client.js +++ b/test/parallel/test-http-upgrade-client.js @@ -3,11 +3,11 @@ // the HTTP client. This test uses a raw TCP server to better control server // behavior. -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); -var http = require('http'); -var net = require('net'); +const http = require('http'); +const net = require('net'); // Create a TCP server var srv = net.createServer(function(c) { diff --git a/test/parallel/test-http-upgrade-client2.js b/test/parallel/test-http-upgrade-client2.js index 0c229a354add48..03cb36981ad6d7 100644 --- a/test/parallel/test-http-upgrade-client2.js +++ b/test/parallel/test-http-upgrade-client2.js @@ -1,6 +1,6 @@ 'use strict'; const common = require('../common'); -var http = require('http'); +const http = require('http'); var CRLF = '\r\n'; diff --git a/test/parallel/test-http-upgrade-server.js b/test/parallel/test-http-upgrade-server.js index 8570dec899b672..50183dffe18ae7 100644 --- a/test/parallel/test-http-upgrade-server.js +++ b/test/parallel/test-http-upgrade-server.js @@ -1,10 +1,10 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); -var util = require('util'); -var net = require('net'); -var http = require('http'); +const util = require('util'); +const net = require('net'); +const http = require('http'); var requests_recv = 0; diff --git a/test/parallel/test-http-upgrade-server2.js b/test/parallel/test-http-upgrade-server2.js index 1644f54977af85..e7533b194d0760 100644 --- a/test/parallel/test-http-upgrade-server2.js +++ b/test/parallel/test-http-upgrade-server2.js @@ -1,8 +1,8 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); -var http = require('http'); -var net = require('net'); +const assert = require('assert'); +const http = require('http'); +const net = require('net'); var server = http.createServer(function(req, res) { throw new Error('This shouldn\'t happen.'); diff --git a/test/parallel/test-http-url.parse-auth-with-header-in-request.js b/test/parallel/test-http-url.parse-auth-with-header-in-request.js index fa930bd5ec2e34..9781cefcbdb23a 100644 --- a/test/parallel/test-http-url.parse-auth-with-header-in-request.js +++ b/test/parallel/test-http-url.parse-auth-with-header-in-request.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var http = require('http'); -var url = require('url'); +const assert = require('assert'); +const http = require('http'); +const url = require('url'); function check(request) { // the correct authorization header is be passed diff --git a/test/parallel/test-http-url.parse-auth.js b/test/parallel/test-http-url.parse-auth.js index 0e901ebb599b00..72e69b14a9a3b8 100644 --- a/test/parallel/test-http-url.parse-auth.js +++ b/test/parallel/test-http-url.parse-auth.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var http = require('http'); -var url = require('url'); +const assert = require('assert'); +const http = require('http'); +const url = require('url'); function check(request) { // the correct authorization header is be passed diff --git a/test/parallel/test-http-url.parse-basic.js b/test/parallel/test-http-url.parse-basic.js index b0d1274b594d7e..0fa8f104653162 100644 --- a/test/parallel/test-http-url.parse-basic.js +++ b/test/parallel/test-http-url.parse-basic.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var http = require('http'); -var url = require('url'); +const assert = require('assert'); +const http = require('http'); +const url = require('url'); var testURL; diff --git a/test/parallel/test-http-url.parse-https.request.js b/test/parallel/test-http-url.parse-https.request.js index edd83a2d1306f5..ddd1d5147532b1 100644 --- a/test/parallel/test-http-url.parse-https.request.js +++ b/test/parallel/test-http-url.parse-https.request.js @@ -1,15 +1,15 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var https = require('https'); +const https = require('https'); -var url = require('url'); -var fs = require('fs'); +const url = require('url'); +const fs = require('fs'); // https options var httpsOptions = { diff --git a/test/parallel/test-http-url.parse-only-support-http-https-protocol.js b/test/parallel/test-http-url.parse-only-support-http-https-protocol.js index e7ed82817146ea..b3d7795e72cefa 100644 --- a/test/parallel/test-http-url.parse-only-support-http-https-protocol.js +++ b/test/parallel/test-http-url.parse-only-support-http-https-protocol.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var http = require('http'); -var url = require('url'); +const assert = require('assert'); +const http = require('http'); +const url = require('url'); assert.throws(function() { diff --git a/test/parallel/test-http-url.parse-path.js b/test/parallel/test-http-url.parse-path.js index 73de297d45fca5..e5a1306f8ee077 100644 --- a/test/parallel/test-http-url.parse-path.js +++ b/test/parallel/test-http-url.parse-path.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var http = require('http'); -var url = require('url'); +const assert = require('assert'); +const http = require('http'); +const url = require('url'); function check(request) { // a path should come over diff --git a/test/parallel/test-http-url.parse-post.js b/test/parallel/test-http-url.parse-post.js index 0af482c94a875d..3ea40de6ecca5d 100644 --- a/test/parallel/test-http-url.parse-post.js +++ b/test/parallel/test-http-url.parse-post.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var http = require('http'); -var url = require('url'); +const assert = require('assert'); +const http = require('http'); +const url = require('url'); var testURL; diff --git a/test/parallel/test-http-url.parse-search.js b/test/parallel/test-http-url.parse-search.js index 9a1e7565572fcc..47cc0c03a6cfc5 100644 --- a/test/parallel/test-http-url.parse-search.js +++ b/test/parallel/test-http-url.parse-search.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var http = require('http'); -var url = require('url'); +const assert = require('assert'); +const http = require('http'); +const url = require('url'); function check(request) { // a path should come over with params diff --git a/test/parallel/test-http-wget.js b/test/parallel/test-http-wget.js index f7fb1a3656c623..795f1794777cef 100644 --- a/test/parallel/test-http-wget.js +++ b/test/parallel/test-http-wget.js @@ -1,8 +1,8 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); -var net = require('net'); -var http = require('http'); +const assert = require('assert'); +const net = require('net'); +const http = require('http'); // wget sends an HTTP/1.0 request with Connection: Keep-Alive // diff --git a/test/parallel/test-http-write-callbacks.js b/test/parallel/test-http-write-callbacks.js index b89cdf89af7b90..59010256559144 100644 --- a/test/parallel/test-http-write-callbacks.js +++ b/test/parallel/test-http-write-callbacks.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); -var http = require('http'); +const http = require('http'); var serverEndCb = false; var serverIncoming = ''; diff --git a/test/parallel/test-http-write-empty-string.js b/test/parallel/test-http-write-empty-string.js index 534a55823accee..c659c47fa47bc6 100644 --- a/test/parallel/test-http-write-empty-string.js +++ b/test/parallel/test-http-write-empty-string.js @@ -1,8 +1,8 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); +const assert = require('assert'); -var http = require('http'); +const http = require('http'); var server = http.createServer(function(request, response) { console.log('responding to ' + request.url); diff --git a/test/parallel/test-http-write-head.js b/test/parallel/test-http-write-head.js index 32fff6042e7178..9807dc6943f13c 100644 --- a/test/parallel/test-http-write-head.js +++ b/test/parallel/test-http-write-head.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var http = require('http'); +const assert = require('assert'); +const http = require('http'); // Verify that ServerResponse.writeHead() works as setHeader. // Issue 5036 on github. diff --git a/test/parallel/test-http-zero-length-write.js b/test/parallel/test-http-zero-length-write.js index b928aaeb341a88..b446fd77860e83 100644 --- a/test/parallel/test-http-zero-length-write.js +++ b/test/parallel/test-http-zero-length-write.js @@ -1,10 +1,10 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); -var http = require('http'); +const http = require('http'); -var Stream = require('stream'); +const Stream = require('stream'); function getSrc() { // An old-style readable stream. diff --git a/test/parallel/test-https-agent-servername.js b/test/parallel/test-https-agent-servername.js index 348cf499b65f56..09a0f6bdd6b701 100644 --- a/test/parallel/test-https-agent-servername.js +++ b/test/parallel/test-https-agent-servername.js @@ -1,13 +1,13 @@ 'use strict'; -var common = require('../common'); +const common = require('../common'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var https = require('https'); -var fs = require('fs'); +const https = require('https'); +const fs = require('fs'); var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), diff --git a/test/parallel/test-https-byteswritten.js b/test/parallel/test-https-byteswritten.js index 58dfb12dbe2eda..51f59bc311d0b1 100644 --- a/test/parallel/test-https-byteswritten.js +++ b/test/parallel/test-https-byteswritten.js @@ -1,13 +1,13 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var fs = require('fs'); +const common = require('../common'); +const assert = require('assert'); +const fs = require('fs'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var https = require('https'); +const https = require('https'); var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), diff --git a/test/parallel/test-https-client-checkServerIdentity.js b/test/parallel/test-https-client-checkServerIdentity.js index 053a5630050748..82f03320c4fb5c 100644 --- a/test/parallel/test-https-client-checkServerIdentity.js +++ b/test/parallel/test-https-client-checkServerIdentity.js @@ -1,15 +1,15 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var https = require('https'); +const https = require('https'); -var fs = require('fs'); -var path = require('path'); +const fs = require('fs'); +const path = require('path'); var options = { key: fs.readFileSync(path.join(common.fixturesDir, 'keys/agent3-key.pem')), diff --git a/test/parallel/test-https-client-get-url.js b/test/parallel/test-https-client-get-url.js index 1a9fdf5f3f808e..4e92b6ae881451 100644 --- a/test/parallel/test-https-client-get-url.js +++ b/test/parallel/test-https-client-get-url.js @@ -3,15 +3,15 @@ const common = require('../common'); // disable strict server certificate validation by the client process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; -var assert = require('assert'); +const assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var https = require('https'); +const https = require('https'); -var fs = require('fs'); +const fs = require('fs'); var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), diff --git a/test/parallel/test-https-client-reject.js b/test/parallel/test-https-client-reject.js index b1708f24b10b83..32626b0a05f946 100644 --- a/test/parallel/test-https-client-reject.js +++ b/test/parallel/test-https-client-reject.js @@ -1,15 +1,15 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var https = require('https'); +const https = require('https'); -var fs = require('fs'); -var path = require('path'); +const fs = require('fs'); +const path = require('path'); var options = { key: fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')), diff --git a/test/parallel/test-https-client-resume.js b/test/parallel/test-https-client-resume.js index 734e8069021f78..58a06c70e2a5da 100644 --- a/test/parallel/test-https-client-resume.js +++ b/test/parallel/test-https-client-resume.js @@ -2,17 +2,17 @@ // Create an ssl server. First connection, validate that not resume. // Cache session and close connection. Use session on second connection. // ASSERT resumption. -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var https = require('https'); +const https = require('https'); -var tls = require('tls'); -var fs = require('fs'); +const tls = require('tls'); +const fs = require('fs'); var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'), diff --git a/test/parallel/test-https-connecting-to-http.js b/test/parallel/test-https-connecting-to-http.js index 53158595054714..3bfab5f626efd2 100644 --- a/test/parallel/test-https-connecting-to-http.js +++ b/test/parallel/test-https-connecting-to-http.js @@ -1,14 +1,14 @@ 'use strict'; // This tests the situation where you try to connect a https client // to an http server. You should get an error and exit. -var common = require('../common'); -var http = require('http'); +const common = require('../common'); +const http = require('http'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var https = require('https'); +const https = require('https'); var server = http.createServer(common.fail); diff --git a/test/parallel/test-https-drain.js b/test/parallel/test-https-drain.js index 7648469b0f54a7..0f6501e8ef5603 100644 --- a/test/parallel/test-https-drain.js +++ b/test/parallel/test-https-drain.js @@ -1,15 +1,15 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var https = require('https'); +const https = require('https'); -var fs = require('fs'); -var path = require('path'); +const fs = require('fs'); +const path = require('path'); var options = { key: fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')), diff --git a/test/parallel/test-https-eof-for-eom.js b/test/parallel/test-https-eof-for-eom.js index 1c814714bfef96..81d4e978a87672 100644 --- a/test/parallel/test-https-eof-for-eom.js +++ b/test/parallel/test-https-eof-for-eom.js @@ -7,17 +7,17 @@ // This test is to be sure that the https client is handling this case // correctly. -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var https = require('https'); -var tls = require('tls'); +const https = require('https'); +const tls = require('tls'); -var fs = require('fs'); +const fs = require('fs'); var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), diff --git a/test/parallel/test-https-foafssl.js b/test/parallel/test-https-foafssl.js index 5c9fb613e6fa95..6be850a11ed633 100644 --- a/test/parallel/test-https-foafssl.js +++ b/test/parallel/test-https-foafssl.js @@ -1,22 +1,22 @@ 'use strict'; -var common = require('../common'); +const common = require('../common'); if (!common.opensslCli) { common.skip('node compiled without OpenSSL CLI.'); return; } -var assert = require('assert'); -var join = require('path').join; +const assert = require('assert'); +const join = require('path').join; -var fs = require('fs'); -var spawn = require('child_process').spawn; +const fs = require('fs'); +const spawn = require('child_process').spawn; if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var https = require('https'); +const https = require('https'); var options = { key: fs.readFileSync(common.fixturesDir + '/agent.key'), diff --git a/test/parallel/test-https-host-headers.js b/test/parallel/test-https-host-headers.js index 3e998d470487ef..25de4435ea3b28 100644 --- a/test/parallel/test-https-host-headers.js +++ b/test/parallel/test-https-host-headers.js @@ -1,12 +1,12 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var https = require('https'); +const https = require('https'); const fs = require('fs'); const options = { diff --git a/test/parallel/test-https-localaddress-bind-error.js b/test/parallel/test-https-localaddress-bind-error.js index 91c3062a6e1896..2382d59a7c36af 100644 --- a/test/parallel/test-https-localaddress-bind-error.js +++ b/test/parallel/test-https-localaddress-bind-error.js @@ -1,12 +1,12 @@ 'use strict'; -var common = require('../common'); -var fs = require('fs'); +const common = require('../common'); +const fs = require('fs'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var https = require('https'); +const https = require('https'); var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), diff --git a/test/parallel/test-https-localaddress.js b/test/parallel/test-https-localaddress.js index e6aa0c93a2aaaa..22e96eb4675417 100644 --- a/test/parallel/test-https-localaddress.js +++ b/test/parallel/test-https-localaddress.js @@ -7,7 +7,7 @@ if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var https = require('https'); +const https = require('https'); if (!common.hasMultiLocalhost()) { common.skip('platform-specific test.'); diff --git a/test/parallel/test-https-pfx.js b/test/parallel/test-https-pfx.js index 02715de60da3c8..8d0f51b6a51c82 100644 --- a/test/parallel/test-https-pfx.js +++ b/test/parallel/test-https-pfx.js @@ -1,13 +1,13 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var fs = require('fs'); +const common = require('../common'); +const assert = require('assert'); +const fs = require('fs'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var https = require('https'); +const https = require('https'); var pfx = fs.readFileSync(common.fixturesDir + '/test_cert.pfx'); diff --git a/test/parallel/test-https-req-split.js b/test/parallel/test-https-req-split.js index b49c17f28879be..d0d20a73ad16df 100644 --- a/test/parallel/test-https-req-split.js +++ b/test/parallel/test-https-req-split.js @@ -7,10 +7,10 @@ if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var https = require('https'); +const https = require('https'); -var tls = require('tls'); -var fs = require('fs'); +const tls = require('tls'); +const fs = require('fs'); var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), diff --git a/test/parallel/test-https-resume-after-renew.js b/test/parallel/test-https-resume-after-renew.js index 0efe467932915a..72d77104255beb 100644 --- a/test/parallel/test-https-resume-after-renew.js +++ b/test/parallel/test-https-resume-after-renew.js @@ -5,9 +5,9 @@ if (!common.hasCrypto) { return; } -var fs = require('fs'); -var https = require('https'); -var crypto = require('crypto'); +const fs = require('fs'); +const https = require('https'); +const crypto = require('crypto'); var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), diff --git a/test/parallel/test-https-set-timeout-server.js b/test/parallel/test-https-set-timeout-server.js index fd00a521a03cb5..fbf16a0ce32268 100644 --- a/test/parallel/test-https-set-timeout-server.js +++ b/test/parallel/test-https-set-timeout-server.js @@ -1,15 +1,15 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var https = require('https'); +const https = require('https'); -var tls = require('tls'); -var fs = require('fs'); +const tls = require('tls'); +const fs = require('fs'); var tests = []; diff --git a/test/parallel/test-https-socket-options.js b/test/parallel/test-https-socket-options.js index 70013d1770ff98..337cc264a2587c 100644 --- a/test/parallel/test-https-socket-options.js +++ b/test/parallel/test-https-socket-options.js @@ -1,15 +1,15 @@ 'use strict'; -var common = require('../common'); +const common = require('../common'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var https = require('https'); +const https = require('https'); -var fs = require('fs'); +const fs = require('fs'); -var http = require('http'); +const http = require('http'); var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), diff --git a/test/parallel/test-https-strict.js b/test/parallel/test-https-strict.js index ff9c1790824429..9c650dc6ab3226 100644 --- a/test/parallel/test-https-strict.js +++ b/test/parallel/test-https-strict.js @@ -3,16 +3,16 @@ const common = require('../common'); // disable strict server certificate validation by the client process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; -var assert = require('assert'); +const assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var https = require('https'); +const https = require('https'); -var fs = require('fs'); -var path = require('path'); +const fs = require('fs'); +const path = require('path'); function file(fname) { return path.resolve(common.fixturesDir, 'keys', fname); diff --git a/test/parallel/test-https-timeout-server-2.js b/test/parallel/test-https-timeout-server-2.js index 07b7984f2d644b..a17abec5398ada 100644 --- a/test/parallel/test-https-timeout-server-2.js +++ b/test/parallel/test-https-timeout-server-2.js @@ -1,16 +1,16 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var https = require('https'); +const https = require('https'); -var tls = require('tls'); -var fs = require('fs'); +const tls = require('tls'); +const fs = require('fs'); var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), diff --git a/test/parallel/test-internal-modules-expose.js b/test/parallel/test-internal-modules-expose.js index ed3cecb6f29719..dd3a7f7a3cd0b7 100644 --- a/test/parallel/test-internal-modules-expose.js +++ b/test/parallel/test-internal-modules-expose.js @@ -2,6 +2,6 @@ // Flags: --expose_internals require('../common'); -var assert = require('assert'); +const assert = require('assert'); assert.equal(typeof require('internal/freelist').FreeList, 'function'); diff --git a/test/parallel/test-listen-fd-cluster.js b/test/parallel/test-listen-fd-cluster.js index 606109030b51d0..001eb007f2532c 100644 --- a/test/parallel/test-listen-fd-cluster.js +++ b/test/parallel/test-listen-fd-cluster.js @@ -1,9 +1,9 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); -var net = require('net'); -var cluster = require('cluster'); +const common = require('../common'); +const assert = require('assert'); +const http = require('http'); +const net = require('net'); +const cluster = require('cluster'); console.error('Cluster listen fd test', process.argv[2] || 'runner'); @@ -68,7 +68,7 @@ function test(cb) { const port = this.address().port; console.error('server listening on %d', port); - var spawn = require('child_process').spawn; + const spawn = require('child_process').spawn; var master = spawn(process.execPath, [__filename, 'master'], { stdio: [ 0, 'pipe', 2, server._handle, 'ipc' ], detached: true diff --git a/test/parallel/test-listen-fd-detached-inherit.js b/test/parallel/test-listen-fd-detached-inherit.js index 5dfe346a49f441..9699232d2e0088 100644 --- a/test/parallel/test-listen-fd-detached-inherit.js +++ b/test/parallel/test-listen-fd-detached-inherit.js @@ -1,9 +1,9 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); -var net = require('net'); -var spawn = require('child_process').spawn; +const common = require('../common'); +const assert = require('assert'); +const http = require('http'); +const net = require('net'); +const spawn = require('child_process').spawn; if (common.isWindows) { common.skip('This test is disabled on windows.'); diff --git a/test/parallel/test-listen-fd-detached.js b/test/parallel/test-listen-fd-detached.js index 0629f7ea7970d7..4ec3654a2166cf 100644 --- a/test/parallel/test-listen-fd-detached.js +++ b/test/parallel/test-listen-fd-detached.js @@ -1,9 +1,9 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); -var net = require('net'); -var spawn = require('child_process').spawn; +const common = require('../common'); +const assert = require('assert'); +const http = require('http'); +const net = require('net'); +const spawn = require('child_process').spawn; if (common.isWindows) { common.skip('This test is disabled on windows.'); @@ -66,7 +66,7 @@ function parent() { }).listen(0, function() { console.error('server listening on %d', this.address().port); - var spawn = require('child_process').spawn; + const spawn = require('child_process').spawn; var child = spawn(process.execPath, [__filename, 'child'], { stdio: [ 'ignore', 'ignore', 'ignore', server._handle ], detached: true diff --git a/test/parallel/test-listen-fd-server.js b/test/parallel/test-listen-fd-server.js index eda75e5c723261..87a624f7137562 100644 --- a/test/parallel/test-listen-fd-server.js +++ b/test/parallel/test-listen-fd-server.js @@ -1,8 +1,8 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); -var net = require('net'); +const common = require('../common'); +const assert = require('assert'); +const http = require('http'); +const net = require('net'); if (common.isWindows) { common.skip('This test is disabled on windows.'); @@ -74,7 +74,7 @@ function test(cb) { const port = this.address().port; console.error('server listening on %d', port); - var spawn = require('child_process').spawn; + const spawn = require('child_process').spawn; var child = spawn(process.execPath, [__filename, 'child'], { stdio: [ 0, 1, 2, server._handle, 'ipc' ] }); diff --git a/test/parallel/test-memory-usage-emfile.js b/test/parallel/test-memory-usage-emfile.js index 92c103669a9a85..ce74dd3be3c4e5 100644 --- a/test/parallel/test-memory-usage-emfile.js +++ b/test/parallel/test-memory-usage-emfile.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); -var fs = require('fs'); +const fs = require('fs'); var files = []; diff --git a/test/parallel/test-memory-usage.js b/test/parallel/test-memory-usage.js index c5905c537ac613..400e17aa008a90 100644 --- a/test/parallel/test-memory-usage.js +++ b/test/parallel/test-memory-usage.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); var r = process.memoryUsage(); assert.ok(r.rss > 0); diff --git a/test/parallel/test-microtask-queue-integration-domain.js b/test/parallel/test-microtask-queue-integration-domain.js index 1e07fa5d415ba3..2e865041dfc209 100644 --- a/test/parallel/test-microtask-queue-integration-domain.js +++ b/test/parallel/test-microtask-queue-integration-domain.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); // Requiring the domain module here changes the function that is used by node to // call process.nextTick's callbacks to a variant that specifically handles diff --git a/test/parallel/test-microtask-queue-integration.js b/test/parallel/test-microtask-queue-integration.js index 2cc608d96aec3d..f4f518caa30c93 100644 --- a/test/parallel/test-microtask-queue-integration.js +++ b/test/parallel/test-microtask-queue-integration.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); var implementations = [ function(fn) { diff --git a/test/parallel/test-microtask-queue-run-domain.js b/test/parallel/test-microtask-queue-run-domain.js index fb5139f71d65aa..57ba4543a3f6cd 100644 --- a/test/parallel/test-microtask-queue-run-domain.js +++ b/test/parallel/test-microtask-queue-run-domain.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); // Requiring the domain module here changes the function that is used by node to // call process.nextTick's callbacks to a variant that specifically handles diff --git a/test/parallel/test-microtask-queue-run-immediate-domain.js b/test/parallel/test-microtask-queue-run-immediate-domain.js index 4a7729ab98a062..5241b6c4a91e9d 100644 --- a/test/parallel/test-microtask-queue-run-immediate-domain.js +++ b/test/parallel/test-microtask-queue-run-immediate-domain.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); // Requiring the domain module here changes the function that is used by node to // call process.nextTick's callbacks to a variant that specifically handles diff --git a/test/parallel/test-microtask-queue-run-immediate.js b/test/parallel/test-microtask-queue-run-immediate.js index 479062ad4710f4..b21af670ffdb9d 100644 --- a/test/parallel/test-microtask-queue-run-immediate.js +++ b/test/parallel/test-microtask-queue-run-immediate.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); function enqueueMicrotask(fn) { Promise.resolve().then(fn); diff --git a/test/parallel/test-microtask-queue-run.js b/test/parallel/test-microtask-queue-run.js index ce743d93003249..3150c9ebda514a 100644 --- a/test/parallel/test-microtask-queue-run.js +++ b/test/parallel/test-microtask-queue-run.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); function enqueueMicrotask(fn) { Promise.resolve().then(fn); diff --git a/test/parallel/test-module-globalpaths-nodepath.js b/test/parallel/test-module-globalpaths-nodepath.js index 3369df0676015b..66511e51eddb11 100644 --- a/test/parallel/test-module-globalpaths-nodepath.js +++ b/test/parallel/test-module-globalpaths-nodepath.js @@ -1,8 +1,7 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); - -var module = require('module'); +const common = require('../common'); +const assert = require('assert'); +const mod = require('module'); var partA, partB; var partC = ''; @@ -17,10 +16,10 @@ if (common.isWindows) { process.env['NODE_PATH'] = partA + ':' + partB + ':' + partC; } -module._initPaths(); +mod._initPaths(); -assert.ok(module.globalPaths.indexOf(partA) !== -1); -assert.ok(module.globalPaths.indexOf(partB) !== -1); -assert.ok(module.globalPaths.indexOf(partC) === -1); +assert.ok(mod.globalPaths.indexOf(partA) !== -1); +assert.ok(mod.globalPaths.indexOf(partB) !== -1); +assert.ok(mod.globalPaths.indexOf(partC) === -1); -assert.ok(Array.isArray(module.globalPaths)); +assert.ok(Array.isArray(mod.globalPaths)); diff --git a/test/parallel/test-module-loading-error.js b/test/parallel/test-module-loading-error.js index 145530985401e4..1958fe65242221 100644 --- a/test/parallel/test-module-loading-error.js +++ b/test/parallel/test-module-loading-error.js @@ -1,6 +1,6 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); +const assert = require('assert'); console.error('load test-module-loading-error.js'); diff --git a/test/parallel/test-module-version.js b/test/parallel/test-module-version.js index 7f96e8bb60f0ac..04f011bbfacd8e 100644 --- a/test/parallel/test-module-version.js +++ b/test/parallel/test-module-version.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); // check for existence assert(process.config.variables.hasOwnProperty('node_module_version')); diff --git a/test/parallel/test-net-after-close.js b/test/parallel/test-net-after-close.js index a73663e7da86db..db658bcb03de06 100644 --- a/test/parallel/test-net-after-close.js +++ b/test/parallel/test-net-after-close.js @@ -1,7 +1,7 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); -var net = require('net'); +const assert = require('assert'); +const net = require('net'); var server = net.createServer(function(s) { console.error('SERVER: got connection'); diff --git a/test/parallel/test-net-better-error-messages-path.js b/test/parallel/test-net-better-error-messages-path.js index 9222a1cc758aaa..bf18e14898fbf0 100644 --- a/test/parallel/test-net-better-error-messages-path.js +++ b/test/parallel/test-net-better-error-messages-path.js @@ -1,7 +1,7 @@ 'use strict'; -var common = require('../common'); -var net = require('net'); -var assert = require('assert'); +const common = require('../common'); +const net = require('net'); +const assert = require('assert'); var fp = '/tmp/fadagagsdfgsdf'; var c = net.connect(fp); diff --git a/test/parallel/test-net-bind-twice.js b/test/parallel/test-net-bind-twice.js index 9b9fc7c5db37dd..68e93a75f0154a 100644 --- a/test/parallel/test-net-bind-twice.js +++ b/test/parallel/test-net-bind-twice.js @@ -1,7 +1,7 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); -var net = require('net'); +const assert = require('assert'); +const net = require('net'); var server1 = net.createServer(common.fail); server1.listen(0, '127.0.0.1', common.mustCall(function() { diff --git a/test/parallel/test-net-buffersize.js b/test/parallel/test-net-buffersize.js index 872d8de7b42f3b..dfaf5dd50d6614 100644 --- a/test/parallel/test-net-buffersize.js +++ b/test/parallel/test-net-buffersize.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var net = require('net'); +const assert = require('assert'); +const net = require('net'); var iter = 10; diff --git a/test/parallel/test-net-bytes-stats.js b/test/parallel/test-net-bytes-stats.js index a8643b03b97250..518b2f10ba37d4 100644 --- a/test/parallel/test-net-bytes-stats.js +++ b/test/parallel/test-net-bytes-stats.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var net = require('net'); +const assert = require('assert'); +const net = require('net'); var bytesRead = 0; var bytesWritten = 0; diff --git a/test/parallel/test-net-can-reset-timeout.js b/test/parallel/test-net-can-reset-timeout.js index 7dbd5cad2ae6bb..c5333e2522711e 100644 --- a/test/parallel/test-net-can-reset-timeout.js +++ b/test/parallel/test-net-can-reset-timeout.js @@ -1,6 +1,6 @@ 'use strict'; const common = require('../common'); -var net = require('net'); +const net = require('net'); var server = net.createServer(common.mustCall(function(stream) { stream.setTimeout(100); diff --git a/test/parallel/test-net-connect-buffer.js b/test/parallel/test-net-connect-buffer.js index 3ef5b0ea9f075d..187cbf19426653 100644 --- a/test/parallel/test-net-connect-buffer.js +++ b/test/parallel/test-net-connect-buffer.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var net = require('net'); +const assert = require('assert'); +const net = require('net'); var dataWritten = false; var connectHappened = false; diff --git a/test/parallel/test-net-connect-options.js b/test/parallel/test-net-connect-options.js index 3446790d7b3c4a..727504b06fc7e2 100644 --- a/test/parallel/test-net-connect-options.js +++ b/test/parallel/test-net-connect-options.js @@ -1,7 +1,7 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); -var net = require('net'); +const assert = require('assert'); +const net = require('net'); var server = net.createServer({ allowHalfOpen: true diff --git a/test/parallel/test-net-connect-paused-connection.js b/test/parallel/test-net-connect-paused-connection.js index 8c0e1c93cfb208..a0a90eefc1db3e 100644 --- a/test/parallel/test-net-connect-paused-connection.js +++ b/test/parallel/test-net-connect-paused-connection.js @@ -1,7 +1,7 @@ 'use strict'; const common = require('../common'); -var net = require('net'); +const net = require('net'); net.createServer(function(conn) { conn.unref(); diff --git a/test/parallel/test-net-dns-custom-lookup.js b/test/parallel/test-net-dns-custom-lookup.js index 07eb71c5ed5811..d643910d62e0d4 100644 --- a/test/parallel/test-net-dns-custom-lookup.js +++ b/test/parallel/test-net-dns-custom-lookup.js @@ -1,7 +1,7 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); +const common = require('../common'); +const assert = require('assert'); +const net = require('net'); function check(addressType, cb) { var server = net.createServer(function(client) { diff --git a/test/parallel/test-net-dns-error.js b/test/parallel/test-net-dns-error.js index b36d84d3e9e214..f5a1dcc6b1c2c5 100644 --- a/test/parallel/test-net-dns-error.js +++ b/test/parallel/test-net-dns-error.js @@ -1,8 +1,8 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); +const assert = require('assert'); -var net = require('net'); +const net = require('net'); var host = '*'.repeat(256); diff --git a/test/parallel/test-net-dns-lookup-skip.js b/test/parallel/test-net-dns-lookup-skip.js index 513a6d0422498e..60674053f7a53c 100644 --- a/test/parallel/test-net-dns-lookup-skip.js +++ b/test/parallel/test-net-dns-lookup-skip.js @@ -1,6 +1,6 @@ 'use strict'; -var common = require('../common'); -var net = require('net'); +const common = require('../common'); +const net = require('net'); function check(addressType) { var server = net.createServer(function(client) { diff --git a/test/parallel/test-net-dns-lookup.js b/test/parallel/test-net-dns-lookup.js index 4f3cd2991cf925..c0aebf0ee919c3 100644 --- a/test/parallel/test-net-dns-lookup.js +++ b/test/parallel/test-net-dns-lookup.js @@ -1,7 +1,7 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); -var net = require('net'); +const assert = require('assert'); +const net = require('net'); var server = net.createServer(function(client) { client.end(); diff --git a/test/parallel/test-net-during-close.js b/test/parallel/test-net-during-close.js index 2649995f89a02f..f6a5455ee7b0f1 100644 --- a/test/parallel/test-net-during-close.js +++ b/test/parallel/test-net-during-close.js @@ -1,7 +1,7 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); -var net = require('net'); +const assert = require('assert'); +const net = require('net'); var server = net.createServer(function(socket) { socket.end(); diff --git a/test/parallel/test-net-eaddrinuse.js b/test/parallel/test-net-eaddrinuse.js index 4741c820797154..53ae1a0589262b 100644 --- a/test/parallel/test-net-eaddrinuse.js +++ b/test/parallel/test-net-eaddrinuse.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var net = require('net'); +const assert = require('assert'); +const net = require('net'); var server1 = net.createServer(function(socket) { }); diff --git a/test/parallel/test-net-end-without-connect.js b/test/parallel/test-net-end-without-connect.js index 69abf486316ff2..0bbd2833626df7 100644 --- a/test/parallel/test-net-end-without-connect.js +++ b/test/parallel/test-net-end-without-connect.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var net = require('net'); +const net = require('net'); var sock = new net.Socket(); sock.end(); // Should not throw. diff --git a/test/parallel/test-net-isip.js b/test/parallel/test-net-isip.js index 6b159b59d8c8c0..65d88523fe930e 100644 --- a/test/parallel/test-net-isip.js +++ b/test/parallel/test-net-isip.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var net = require('net'); +const assert = require('assert'); +const net = require('net'); assert.equal(net.isIP('127.0.0.1'), 4); assert.equal(net.isIP('x127.0.0.1'), 0); diff --git a/test/parallel/test-net-large-string.js b/test/parallel/test-net-large-string.js index b469b0289546a1..ba70275eb03e6f 100644 --- a/test/parallel/test-net-large-string.js +++ b/test/parallel/test-net-large-string.js @@ -1,7 +1,7 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); -var net = require('net'); +const assert = require('assert'); +const net = require('net'); var kPoolSize = 40 * 1024; var data = 'あ'.repeat(kPoolSize); diff --git a/test/parallel/test-net-listen-close-server-callback-is-not-function.js b/test/parallel/test-net-listen-close-server-callback-is-not-function.js index 03c08d4f51bf15..18234a816e1b0d 100644 --- a/test/parallel/test-net-listen-close-server-callback-is-not-function.js +++ b/test/parallel/test-net-listen-close-server-callback-is-not-function.js @@ -1,6 +1,6 @@ 'use strict'; const common = require('../common'); -var net = require('net'); +const net = require('net'); var server = net.createServer(common.fail); diff --git a/test/parallel/test-net-listen-close-server.js b/test/parallel/test-net-listen-close-server.js index 92c7274f328918..b6ab99c60e2d51 100644 --- a/test/parallel/test-net-listen-close-server.js +++ b/test/parallel/test-net-listen-close-server.js @@ -1,6 +1,6 @@ 'use strict'; const common = require('../common'); -var net = require('net'); +const net = require('net'); var server = net.createServer(function(socket) { }); diff --git a/test/parallel/test-net-listen-error.js b/test/parallel/test-net-listen-error.js index 9523fcb2e7f456..009d12b09e7aca 100644 --- a/test/parallel/test-net-listen-error.js +++ b/test/parallel/test-net-listen-error.js @@ -1,6 +1,6 @@ 'use strict'; const common = require('../common'); -var net = require('net'); +const net = require('net'); var server = net.createServer(function(socket) { }); diff --git a/test/parallel/test-net-listen-exclusive-random-ports.js b/test/parallel/test-net-listen-exclusive-random-ports.js index f46f9a01d773ce..4c5d056d9dfe54 100644 --- a/test/parallel/test-net-listen-exclusive-random-ports.js +++ b/test/parallel/test-net-listen-exclusive-random-ports.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var cluster = require('cluster'); -var net = require('net'); +const assert = require('assert'); +const cluster = require('cluster'); +const net = require('net'); function noop() {} diff --git a/test/parallel/test-net-listen-shared-ports.js b/test/parallel/test-net-listen-shared-ports.js index 2062dd0ce136bb..4cd26ac330a67c 100644 --- a/test/parallel/test-net-listen-shared-ports.js +++ b/test/parallel/test-net-listen-shared-ports.js @@ -1,8 +1,8 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var cluster = require('cluster'); -var net = require('net'); +const common = require('../common'); +const assert = require('assert'); +const cluster = require('cluster'); +const net = require('net'); function noop() {} diff --git a/test/parallel/test-net-localport.js b/test/parallel/test-net-localport.js index 4af9dcfd08aeca..3c105ff2877544 100644 --- a/test/parallel/test-net-localport.js +++ b/test/parallel/test-net-localport.js @@ -1,7 +1,7 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); +const common = require('../common'); +const assert = require('assert'); +const net = require('net'); var server = net.createServer(function(socket) { console.log(socket.remotePort); diff --git a/test/parallel/test-net-persistent-keepalive.js b/test/parallel/test-net-persistent-keepalive.js index d1dfb370167714..febdc688519ca8 100644 --- a/test/parallel/test-net-persistent-keepalive.js +++ b/test/parallel/test-net-persistent-keepalive.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var net = require('net'); +const assert = require('assert'); +const net = require('net'); var serverConnection; var clientConnection; diff --git a/test/parallel/test-net-persistent-nodelay.js b/test/parallel/test-net-persistent-nodelay.js index e23b8718dfee6d..bd34d303264a64 100644 --- a/test/parallel/test-net-persistent-nodelay.js +++ b/test/parallel/test-net-persistent-nodelay.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var net = require('net'); +const assert = require('assert'); +const net = require('net'); var TCPWrap = process.binding('tcp_wrap').TCP; var echoServer = net.createServer(function(connection) { diff --git a/test/parallel/test-net-persistent-ref-unref.js b/test/parallel/test-net-persistent-ref-unref.js index 32782e7c591444..9034a16f9a2793 100644 --- a/test/parallel/test-net-persistent-ref-unref.js +++ b/test/parallel/test-net-persistent-ref-unref.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var net = require('net'); +const assert = require('assert'); +const net = require('net'); var TCPWrap = process.binding('tcp_wrap').TCP; var echoServer = net.createServer(function(conn) { diff --git a/test/parallel/test-net-reconnect.js b/test/parallel/test-net-reconnect.js index 980de2637b18bf..c0c5589b396ee4 100644 --- a/test/parallel/test-net-reconnect.js +++ b/test/parallel/test-net-reconnect.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); -var net = require('net'); +const net = require('net'); var N = 50; var client_recv_count = 0; diff --git a/test/parallel/test-net-server-bind.js b/test/parallel/test-net-server-bind.js index c77341418c2c6d..623962e3abddca 100644 --- a/test/parallel/test-net-server-bind.js +++ b/test/parallel/test-net-server-bind.js @@ -1,7 +1,7 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); +const common = require('../common'); +const assert = require('assert'); +const net = require('net'); // With only a callback, server should get a port assigned by the OS diff --git a/test/parallel/test-net-server-close.js b/test/parallel/test-net-server-close.js index 006ca529c79ab3..9f920a6a69b194 100644 --- a/test/parallel/test-net-server-close.js +++ b/test/parallel/test-net-server-close.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var net = require('net'); +const assert = require('assert'); +const net = require('net'); var events = []; var sockets = []; diff --git a/test/parallel/test-net-server-connections.js b/test/parallel/test-net-server-connections.js index ae89d9aac7b3f7..ce3087713c3ad7 100644 --- a/test/parallel/test-net-server-connections.js +++ b/test/parallel/test-net-server-connections.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); -var net = require('net'); +const net = require('net'); // test that server.connections property is no longer enumerable now that it // has been marked as deprecated diff --git a/test/parallel/test-net-server-listen-remove-callback.js b/test/parallel/test-net-server-listen-remove-callback.js index 9bdfd628072798..4d2c12102c4448 100644 --- a/test/parallel/test-net-server-listen-remove-callback.js +++ b/test/parallel/test-net-server-listen-remove-callback.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var net = require('net'); +const assert = require('assert'); +const net = require('net'); // Server should only fire listen callback once var server = net.createServer(); diff --git a/test/parallel/test-net-server-max-connections-close-makes-more-available.js b/test/parallel/test-net-server-max-connections-close-makes-more-available.js index fb9831d05b3e50..14a27da8f8cc3d 100644 --- a/test/parallel/test-net-server-max-connections-close-makes-more-available.js +++ b/test/parallel/test-net-server-max-connections-close-makes-more-available.js @@ -1,8 +1,8 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); +const assert = require('assert'); -var net = require('net'); +const net = require('net'); // Sets the server's maxConnections property to 1. // Open 2 connections (connection 0 and connection 1). diff --git a/test/parallel/test-net-server-unref-persistent.js b/test/parallel/test-net-server-unref-persistent.js index d68e94cfbda8c8..e75a4d83052aab 100644 --- a/test/parallel/test-net-server-unref-persistent.js +++ b/test/parallel/test-net-server-unref-persistent.js @@ -1,6 +1,6 @@ 'use strict'; const common = require('../common'); -var net = require('net'); +const net = require('net'); var server = net.createServer(); // unref before listening diff --git a/test/parallel/test-net-server-unref.js b/test/parallel/test-net-server-unref.js index 91b25887a28d3e..bf8a9ef43ab12c 100644 --- a/test/parallel/test-net-server-unref.js +++ b/test/parallel/test-net-server-unref.js @@ -1,6 +1,6 @@ 'use strict'; const common = require('../common'); -var net = require('net'); +const net = require('net'); var s = net.createServer(); s.listen(0); diff --git a/test/parallel/test-net-socket-destroy-twice.js b/test/parallel/test-net-socket-destroy-twice.js index 917e9849999b05..be82d9f2a678b4 100644 --- a/test/parallel/test-net-socket-destroy-twice.js +++ b/test/parallel/test-net-socket-destroy-twice.js @@ -1,6 +1,6 @@ 'use strict'; -var common = require('../common'); -var net = require('net'); +const common = require('../common'); +const net = require('net'); var conn = net.createConnection(common.PORT); diff --git a/test/parallel/test-net-stream.js b/test/parallel/test-net-stream.js index d090038ce753be..12fcc25b0a9563 100644 --- a/test/parallel/test-net-stream.js +++ b/test/parallel/test-net-stream.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var net = require('net'); +const assert = require('assert'); +const net = require('net'); var s = new net.Stream(); diff --git a/test/parallel/test-net-write-after-close.js b/test/parallel/test-net-write-after-close.js index e01aef80f3635b..d8213a9b863b7b 100644 --- a/test/parallel/test-net-write-after-close.js +++ b/test/parallel/test-net-write-after-close.js @@ -1,6 +1,6 @@ 'use strict'; const common = require('../common'); -var net = require('net'); +const net = require('net'); var server = net.createServer(common.mustCall(function(socket) { socket.resume(); diff --git a/test/parallel/test-net-write-connect-write.js b/test/parallel/test-net-write-connect-write.js index 315db6bc02b309..15a30b826e18d9 100644 --- a/test/parallel/test-net-write-connect-write.js +++ b/test/parallel/test-net-write-connect-write.js @@ -1,7 +1,7 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); -var net = require('net'); +const assert = require('assert'); +const net = require('net'); var server = net.createServer(function(socket) { socket.pipe(socket); diff --git a/test/parallel/test-net-write-slow.js b/test/parallel/test-net-write-slow.js index 6054e2b7882ac2..7e183068f174cf 100644 --- a/test/parallel/test-net-write-slow.js +++ b/test/parallel/test-net-write-slow.js @@ -1,7 +1,7 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); -var net = require('net'); +const assert = require('assert'); +const net = require('net'); var SIZE = 2E5; var N = 10; diff --git a/test/parallel/test-next-tick-domain.js b/test/parallel/test-next-tick-domain.js index 8f9d9bb4aa50f7..634e311da7f67b 100644 --- a/test/parallel/test-next-tick-domain.js +++ b/test/parallel/test-next-tick-domain.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); var origNextTick = process.nextTick; diff --git a/test/parallel/test-next-tick-errors.js b/test/parallel/test-next-tick-errors.js index 180b769eaa105b..4f47c3f954d92e 100644 --- a/test/parallel/test-next-tick-errors.js +++ b/test/parallel/test-next-tick-errors.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); const order = []; let exceptionHandled = false; diff --git a/test/parallel/test-next-tick-intentional-starvation.js b/test/parallel/test-next-tick-intentional-starvation.js index 414524e5405ecc..3da32b8ffae15d 100644 --- a/test/parallel/test-next-tick-intentional-starvation.js +++ b/test/parallel/test-next-tick-intentional-starvation.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); // this is the inverse of test-next-tick-starvation. // it verifies that process.nextTick will *always* come before other diff --git a/test/parallel/test-next-tick-ordering.js b/test/parallel/test-next-tick-ordering.js index 63f8d37828e53c..316fdb9f9ae373 100644 --- a/test/parallel/test-next-tick-ordering.js +++ b/test/parallel/test-next-tick-ordering.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); var i; var N = 30; diff --git a/test/parallel/test-next-tick-ordering2.js b/test/parallel/test-next-tick-ordering2.js index 11ac84b5319dda..32c5bd8e8ece51 100644 --- a/test/parallel/test-next-tick-ordering2.js +++ b/test/parallel/test-next-tick-ordering2.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); var order = []; process.nextTick(function() { diff --git a/test/parallel/test-next-tick.js b/test/parallel/test-next-tick.js index 2a98b46da10f17..702d2308ae1f2e 100644 --- a/test/parallel/test-next-tick.js +++ b/test/parallel/test-next-tick.js @@ -1,6 +1,6 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); +const assert = require('assert'); process.nextTick(common.mustCall(function() { process.nextTick(common.mustCall(function() { diff --git a/test/parallel/test-path-makelong.js b/test/parallel/test-path-makelong.js index 50a77e9d87b8dc..9d3c3852cdbc61 100644 --- a/test/parallel/test-path-makelong.js +++ b/test/parallel/test-path-makelong.js @@ -1,7 +1,7 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); -var path = require('path'); +const assert = require('assert'); +const path = require('path'); if (common.isWindows) { var file = path.join(common.fixturesDir, 'a.js'); diff --git a/test/parallel/test-pipe-address.js b/test/parallel/test-pipe-address.js index 85e3daa3522e78..d4bb0ffbc5af81 100644 --- a/test/parallel/test-pipe-address.js +++ b/test/parallel/test-pipe-address.js @@ -1,7 +1,7 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); +const common = require('../common'); +const assert = require('assert'); +const net = require('net'); var server = net.createServer(common.fail); common.refreshTmpDir(); diff --git a/test/parallel/test-pipe-return-val.js b/test/parallel/test-pipe-return-val.js index a14f925916bee0..a5f2ff6dfa8fd6 100644 --- a/test/parallel/test-pipe-return-val.js +++ b/test/parallel/test-pipe-return-val.js @@ -2,8 +2,8 @@ // This test ensures SourceStream.pipe(DestStream) returns DestStream require('../common'); -var Stream = require('stream').Stream; -var assert = require('assert'); +const Stream = require('stream').Stream; +const assert = require('assert'); var sourceStream = new Stream(); var destStream = new Stream(); diff --git a/test/parallel/test-pipe-stream.js b/test/parallel/test-pipe-stream.js index 6298495087ac06..8392c8011002aa 100644 --- a/test/parallel/test-pipe-stream.js +++ b/test/parallel/test-pipe-stream.js @@ -1,7 +1,7 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); +const common = require('../common'); +const assert = require('assert'); +const net = require('net'); common.refreshTmpDir(); diff --git a/test/parallel/test-pipe-unref.js b/test/parallel/test-pipe-unref.js index 35c25524b4cfc8..f926dab3e5c98b 100644 --- a/test/parallel/test-pipe-unref.js +++ b/test/parallel/test-pipe-unref.js @@ -1,6 +1,6 @@ 'use strict'; -var common = require('../common'); -var net = require('net'); +const common = require('../common'); +const net = require('net'); common.refreshTmpDir(); diff --git a/test/parallel/test-process-argv-0.js b/test/parallel/test-process-argv-0.js index c3aacb60fa5403..ad078d02b41b03 100644 --- a/test/parallel/test-process-argv-0.js +++ b/test/parallel/test-process-argv-0.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var path = require('path'); -var assert = require('assert'); -var spawn = require('child_process').spawn; +const path = require('path'); +const assert = require('assert'); +const spawn = require('child_process').spawn; if (process.argv[2] !== 'child') { var child = spawn(process.execPath, [__filename, 'child'], { diff --git a/test/parallel/test-process-before-exit.js b/test/parallel/test-process-before-exit.js index 5d8855869a8e4a..01590de0fcf844 100644 --- a/test/parallel/test-process-before-exit.js +++ b/test/parallel/test-process-before-exit.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); var N = 5; var n = 0; diff --git a/test/parallel/test-process-binding.js b/test/parallel/test-process-binding.js index 722e9333aff60a..475891aa5d30d8 100644 --- a/test/parallel/test-process-binding.js +++ b/test/parallel/test-process-binding.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); assert.throws( function() { diff --git a/test/parallel/test-process-config.js b/test/parallel/test-process-config.js index ab38a48e5aacdd..e692a7bf19ae47 100644 --- a/test/parallel/test-process-config.js +++ b/test/parallel/test-process-config.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var fs = require('fs'); -var path = require('path'); +const assert = require('assert'); +const fs = require('fs'); +const path = require('path'); // check for existence assert(process.hasOwnProperty('config')); diff --git a/test/parallel/test-process-exec-argv.js b/test/parallel/test-process-exec-argv.js index e32971ae81a893..c7de82adae3e97 100644 --- a/test/parallel/test-process-exec-argv.js +++ b/test/parallel/test-process-exec-argv.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var spawn = require('child_process').spawn; +const assert = require('assert'); +const spawn = require('child_process').spawn; if (process.argv[2] === 'child') { process.stdout.write(JSON.stringify(process.execArgv)); diff --git a/test/parallel/test-process-exit-code.js b/test/parallel/test-process-exit-code.js index 8d657528d05561..b93ae443a73eae 100644 --- a/test/parallel/test-process-exit-code.js +++ b/test/parallel/test-process-exit-code.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); switch (process.argv[2]) { case 'child1': @@ -70,7 +70,7 @@ function parent() { } function test(arg, exit) { - var spawn = require('child_process').spawn; + const spawn = require('child_process').spawn; var node = process.execPath; var f = __filename; var option = { stdio: [ 0, 1, 'ignore' ] }; diff --git a/test/parallel/test-process-exit-from-before-exit.js b/test/parallel/test-process-exit-from-before-exit.js index b37df0a5bd340d..82458217c6f062 100644 --- a/test/parallel/test-process-exit-from-before-exit.js +++ b/test/parallel/test-process-exit-from-before-exit.js @@ -1,5 +1,5 @@ 'use strict'; -var common = require('../common'); +const common = require('../common'); process.on('beforeExit', common.mustCall(function() { setTimeout(common.fail, 5); diff --git a/test/parallel/test-process-exit-recursive.js b/test/parallel/test-process-exit-recursive.js index 53426a6b1cdaf0..252b282b04886c 100644 --- a/test/parallel/test-process-exit-recursive.js +++ b/test/parallel/test-process-exit-recursive.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); // recursively calling .exit() should not overflow the call stack var nexits = 0; diff --git a/test/parallel/test-process-exit.js b/test/parallel/test-process-exit.js index 0ea36f158eaf9b..9d48ea9eacfe6f 100644 --- a/test/parallel/test-process-exit.js +++ b/test/parallel/test-process-exit.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); // calling .exit() from within "exit" should not overflow the call stack var nexits = 0; diff --git a/test/parallel/test-process-getgroups.js b/test/parallel/test-process-getgroups.js index 1e1bd016966842..9e08892b625f81 100644 --- a/test/parallel/test-process-getgroups.js +++ b/test/parallel/test-process-getgroups.js @@ -1,7 +1,7 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); -var exec = require('child_process').exec; +const assert = require('assert'); +const exec = require('child_process').exec; if (common.isOSX) { common.skip('Output of `id -G` is unreliable on Darwin.'); diff --git a/test/parallel/test-process-hrtime.js b/test/parallel/test-process-hrtime.js index 9280b671f316d6..faa598d0a57362 100644 --- a/test/parallel/test-process-hrtime.js +++ b/test/parallel/test-process-hrtime.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); // the default behavior, return an Array "tuple" of numbers const tuple = process.hrtime(); diff --git a/test/parallel/test-process-kill-null.js b/test/parallel/test-process-kill-null.js index 2516773f08786a..406b2943625365 100644 --- a/test/parallel/test-process-kill-null.js +++ b/test/parallel/test-process-kill-null.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var spawn = require('child_process').spawn; +const assert = require('assert'); +const spawn = require('child_process').spawn; var cat = spawn('cat'); var called; diff --git a/test/parallel/test-process-kill-pid.js b/test/parallel/test-process-kill-pid.js index ee0554c32083f6..9b4a5fa47a87cb 100644 --- a/test/parallel/test-process-kill-pid.js +++ b/test/parallel/test-process-kill-pid.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); // test variants of pid // diff --git a/test/parallel/test-process-raw-debug.js b/test/parallel/test-process-raw-debug.js index ab461902911a93..41774cb87a989f 100644 --- a/test/parallel/test-process-raw-debug.js +++ b/test/parallel/test-process-raw-debug.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var os = require('os'); +const assert = require('assert'); +const os = require('os'); switch (process.argv[2]) { case 'child': @@ -13,7 +13,7 @@ switch (process.argv[2]) { } function parent() { - var spawn = require('child_process').spawn; + const spawn = require('child_process').spawn; var child = spawn(process.execPath, [__filename, 'child']); var output = ''; diff --git a/test/parallel/test-process-wrap.js b/test/parallel/test-process-wrap.js index b5d4dc35e4fe00..08e1b152ed9e07 100644 --- a/test/parallel/test-process-wrap.js +++ b/test/parallel/test-process-wrap.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); var Process = process.binding('process_wrap').Process; var Pipe = process.binding('pipe_wrap').Pipe; var pipe = new Pipe(); diff --git a/test/parallel/test-promises-unhandled-rejections.js b/test/parallel/test-promises-unhandled-rejections.js index b827dd9e368a94..e275dac238cffc 100644 --- a/test/parallel/test-promises-unhandled-rejections.js +++ b/test/parallel/test-promises-unhandled-rejections.js @@ -1,7 +1,7 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var domain = require('domain'); +const common = require('../common'); +const assert = require('assert'); +const domain = require('domain'); var asyncTest = (function() { var asyncTestsEnabled = false; diff --git a/test/parallel/test-querystring.js b/test/parallel/test-querystring.js index ced2b3a3e6d9c3..7192ac6a1bbff0 100644 --- a/test/parallel/test-querystring.js +++ b/test/parallel/test-querystring.js @@ -1,9 +1,9 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); // test using assert -var qs = require('querystring'); +const qs = require('querystring'); function createWithNoPrototype(properties) { const noProto = Object.create(null); @@ -87,7 +87,7 @@ var qsWeirdObjects = [ ]; // }}} -var vm = require('vm'); +const vm = require('vm'); var foreignObject = vm.runInNewContext('({"foo": ["bar", "baz"]})'); var qsNoMungeTestCases = [ diff --git a/test/parallel/test-readline-keys.js b/test/parallel/test-readline-keys.js index 6bbbb2e918470d..eae4ba55b73e6e 100644 --- a/test/parallel/test-readline-keys.js +++ b/test/parallel/test-readline-keys.js @@ -1,10 +1,10 @@ 'use strict'; require('../common'); -var PassThrough = require('stream').PassThrough; -var assert = require('assert'); -var inherits = require('util').inherits; -var extend = require('util')._extend; -var Interface = require('readline').Interface; +const PassThrough = require('stream').PassThrough; +const assert = require('assert'); +const inherits = require('util').inherits; +const extend = require('util')._extend; +const Interface = require('readline').Interface; function FakeInput() { diff --git a/test/parallel/test-readline-set-raw-mode.js b/test/parallel/test-readline-set-raw-mode.js index acf0dc44a631c7..e9e0ff4b4d05f0 100644 --- a/test/parallel/test-readline-set-raw-mode.js +++ b/test/parallel/test-readline-set-raw-mode.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var readline = require('readline'); -var Stream = require('stream'); +const assert = require('assert'); +const readline = require('readline'); +const Stream = require('stream'); var stream = new Stream(); var expectedRawMode = true; diff --git a/test/parallel/test-ref-unref-return.js b/test/parallel/test-ref-unref-return.js index 89ac52d2bcaa50..aec2fff5ce2271 100644 --- a/test/parallel/test-ref-unref-return.js +++ b/test/parallel/test-ref-unref-return.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var net = require('net'); -var dgram = require('dgram'); +const assert = require('assert'); +const net = require('net'); +const dgram = require('dgram'); assert.ok((new net.Server()).ref() instanceof net.Server); assert.ok((new net.Server()).unref() instanceof net.Server); diff --git a/test/parallel/test-regress-GH-1531.js b/test/parallel/test-regress-GH-1531.js index fa0781c2e2fa72..0ca1186d019183 100644 --- a/test/parallel/test-regress-GH-1531.js +++ b/test/parallel/test-regress-GH-1531.js @@ -1,13 +1,13 @@ 'use strict'; -var common = require('../common'); +const common = require('../common'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var https = require('https'); +const https = require('https'); -var fs = require('fs'); +const fs = require('fs'); var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), diff --git a/test/parallel/test-regress-GH-1899.js b/test/parallel/test-regress-GH-1899.js index 7ce83e00092449..1c98b30a8d66fc 100644 --- a/test/parallel/test-regress-GH-1899.js +++ b/test/parallel/test-regress-GH-1899.js @@ -1,8 +1,8 @@ 'use strict'; const common = require('../common'); -var path = require('path'); -var assert = require('assert'); -var spawn = require('child_process').spawn; +const path = require('path'); +const assert = require('assert'); +const spawn = require('child_process').spawn; var child = spawn(process.argv[0], [ path.join(common.fixturesDir, 'GH-1899-output.js') diff --git a/test/parallel/test-regress-GH-2245.js b/test/parallel/test-regress-GH-2245.js index 7558529f9fc50c..129b1428d367cf 100644 --- a/test/parallel/test-regress-GH-2245.js +++ b/test/parallel/test-regress-GH-2245.js @@ -1,6 +1,6 @@ /* eslint-disable strict */ require('../common'); -var assert = require('assert'); +const assert = require('assert'); /* In Node.js 0.10, a bug existed that caused strict functions to not capture diff --git a/test/parallel/test-regress-GH-4948.js b/test/parallel/test-regress-GH-4948.js index 0317778787c2e2..69f4e4732470a5 100644 --- a/test/parallel/test-regress-GH-4948.js +++ b/test/parallel/test-regress-GH-4948.js @@ -2,7 +2,7 @@ // https://github.com/joyent/node/issues/4948 require('../common'); -var http = require('http'); +const http = require('http'); var reqCount = 0; var server = http.createServer(function(serverReq, serverRes) { @@ -31,7 +31,7 @@ var server = http.createServer(function(serverReq, serverRes) { serverRes.write('some data'); }).listen(0, function() { // simulate a client request that closes early - var net = require('net'); + const net = require('net'); var sock = new net.Socket(); sock.connect(this.address().port, 'localhost'); diff --git a/test/parallel/test-regress-GH-5927.js b/test/parallel/test-regress-GH-5927.js index a23c947c320cfc..779a2c2c649ed3 100644 --- a/test/parallel/test-regress-GH-5927.js +++ b/test/parallel/test-regress-GH-5927.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var readline = require('readline'); +const assert = require('assert'); +const readline = require('readline'); var rl = readline.createInterface(process.stdin, process.stdout); rl.resume(); diff --git a/test/parallel/test-regress-GH-6235.js b/test/parallel/test-regress-GH-6235.js index 0bf9b8965d1184..10092884670980 100644 --- a/test/parallel/test-regress-GH-6235.js +++ b/test/parallel/test-regress-GH-6235.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); assert.doesNotThrow(function() { require('vm').runInNewContext('"use strict"; var v = 1; v = 2'); diff --git a/test/parallel/test-regress-GH-746.js b/test/parallel/test-regress-GH-746.js index 8bfcb0c3e22f12..a5e0d9d447360e 100644 --- a/test/parallel/test-regress-GH-746.js +++ b/test/parallel/test-regress-GH-746.js @@ -3,7 +3,7 @@ // This is a regression test for GH-746. const common = require('../common'); -var net = require('net'); +const net = require('net'); process.stdin.destroy(); diff --git a/test/parallel/test-regress-GH-819.js b/test/parallel/test-regress-GH-819.js index 20ca75c793ce24..bc2201b614974b 100644 --- a/test/parallel/test-regress-GH-819.js +++ b/test/parallel/test-regress-GH-819.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var net = require('net'); +const net = require('net'); // Connect to something that we need to DNS resolve var c = net.createConnection(80, 'google.com'); diff --git a/test/parallel/test-regress-GH-node-9326.js b/test/parallel/test-regress-GH-node-9326.js index bb55050d2ce55e..920a24e3a12c9a 100644 --- a/test/parallel/test-regress-GH-node-9326.js +++ b/test/parallel/test-regress-GH-node-9326.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var child_process = require('child_process'); +const assert = require('assert'); +const child_process = require('child_process'); // NOTE: Was crashing on FreeBSD var cp = child_process.spawn(process.execPath, [ diff --git a/test/parallel/test-repl-.save.load.js b/test/parallel/test-repl-.save.load.js index 247f359e829d25..98417e0d063d57 100644 --- a/test/parallel/test-repl-.save.load.js +++ b/test/parallel/test-repl-.save.load.js @@ -1,12 +1,12 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); -var join = require('path').join; -var fs = require('fs'); +const assert = require('assert'); +const join = require('path').join; +const fs = require('fs'); common.refreshTmpDir(); -var repl = require('repl'); +const repl = require('repl'); var works = [['inner.one'], 'inner.o']; diff --git a/test/parallel/test-repl-autolibs.js b/test/parallel/test-repl-autolibs.js index 15f779d3b12269..3cc2ba4aa5988f 100644 --- a/test/parallel/test-repl-autolibs.js +++ b/test/parallel/test-repl-autolibs.js @@ -1,8 +1,8 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); -var util = require('util'); -var repl = require('repl'); +const assert = require('assert'); +const util = require('util'); +const repl = require('repl'); // This test adds global variables common.globalCheck = false; diff --git a/test/parallel/test-repl-domain.js b/test/parallel/test-repl-domain.js index 3cc88b75f72428..19c85980cdcc72 100644 --- a/test/parallel/test-repl-domain.js +++ b/test/parallel/test-repl-domain.js @@ -1,7 +1,7 @@ 'use strict'; -var common = require('../common'); +const common = require('../common'); -var repl = require('repl'); +const repl = require('repl'); const putIn = new common.ArrayStream(); repl.start('', putIn); diff --git a/test/parallel/test-repl-harmony.js b/test/parallel/test-repl-harmony.js index a5928800381cfe..b3e25e62ab0a84 100644 --- a/test/parallel/test-repl-harmony.js +++ b/test/parallel/test-repl-harmony.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); -var spawn = require('child_process').spawn; +const spawn = require('child_process').spawn; var args = ['-i']; var child = spawn(process.execPath, args); diff --git a/test/parallel/test-repl-syntax-error-handling.js b/test/parallel/test-repl-syntax-error-handling.js index 10166b4f06a692..2728ffdfe92129 100644 --- a/test/parallel/test-repl-syntax-error-handling.js +++ b/test/parallel/test-repl-syntax-error-handling.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); switch (process.argv[2]) { case 'child': @@ -12,7 +12,7 @@ switch (process.argv[2]) { } function parent() { - var spawn = require('child_process').spawn; + const spawn = require('child_process').spawn; var child = spawn(process.execPath, [__filename, 'child']); child.stderr.setEncoding('utf8'); @@ -38,7 +38,7 @@ function parent() { } function child() { - var vm = require('vm'); + const vm = require('vm'); try { vm.runInThisContext('haf!@##&$!@$*!@', { displayErrors: false }); } catch (er) { diff --git a/test/parallel/test-repl-tab.js b/test/parallel/test-repl-tab.js index c075b8d4f1125f..b41f43c667f666 100644 --- a/test/parallel/test-repl-tab.js +++ b/test/parallel/test-repl-tab.js @@ -1,8 +1,8 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); -var repl = require('repl'); -var zlib = require('zlib'); +const assert = require('assert'); +const repl = require('repl'); +const zlib = require('zlib'); // just use builtin stream inherited from Duplex var putIn = zlib.createGzip(); diff --git a/test/parallel/test-repl-unexpected-token-recoverable.js b/test/parallel/test-repl-unexpected-token-recoverable.js index 84668c8657c453..7ace511d097ef8 100644 --- a/test/parallel/test-repl-unexpected-token-recoverable.js +++ b/test/parallel/test-repl-unexpected-token-recoverable.js @@ -3,9 +3,9 @@ * This is a regression test for https://github.com/joyent/node/issues/8874. */ require('../common'); -var assert = require('assert'); +const assert = require('assert'); -var spawn = require('child_process').spawn; +const spawn = require('child_process').spawn; // use -i to force node into interactive mode, despite stdout not being a TTY var args = [ '-i' ]; var child = spawn(process.execPath, args); diff --git a/test/parallel/test-require-cache.js b/test/parallel/test-require-cache.js index 247590197d6126..437dd80e581e38 100644 --- a/test/parallel/test-require-cache.js +++ b/test/parallel/test-require-cache.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); { const relativePath = '../fixtures/semicolon'; diff --git a/test/parallel/test-require-extensions-same-filename-as-dir-trailing-slash.js b/test/parallel/test-require-extensions-same-filename-as-dir-trailing-slash.js index 1837a17bab0add..0a80a860388de9 100644 --- a/test/parallel/test-require-extensions-same-filename-as-dir-trailing-slash.js +++ b/test/parallel/test-require-extensions-same-filename-as-dir-trailing-slash.js @@ -1,9 +1,9 @@ /* eslint-disable max-len */ 'use strict'; -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); -var content = require(common.fixturesDir + +const content = require(common.fixturesDir + '/json-with-directory-name-module/module-stub/one-trailing-slash/two/three.js'); assert.notEqual(content.rocko, 'artischocko'); diff --git a/test/parallel/test-require-process.js b/test/parallel/test-require-process.js index 4e5821add13183..f2a3ac89a862fe 100644 --- a/test/parallel/test-require-process.js +++ b/test/parallel/test-require-process.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); -var nativeProcess = require('process'); +const nativeProcess = require('process'); assert.strictEqual(nativeProcess, process, 'require("process") should return global process reference'); diff --git a/test/parallel/test-sigint-infinite-loop.js b/test/parallel/test-sigint-infinite-loop.js index ecd64802acb627..aafcd9e41d7394 100644 --- a/test/parallel/test-sigint-infinite-loop.js +++ b/test/parallel/test-sigint-infinite-loop.js @@ -3,8 +3,8 @@ // Ref(http): // groups.google.com/group/nodejs-dev/browse_thread/thread/e20f2f8df0296d3f const common = require('../common'); -var assert = require('assert'); -var spawn = require('child_process').spawn; +const assert = require('assert'); +const spawn = require('child_process').spawn; console.log('start'); diff --git a/test/parallel/test-signal-safety.js b/test/parallel/test-signal-safety.js index 7938ae04d6591b..eb29554b8b29bb 100644 --- a/test/parallel/test-signal-safety.js +++ b/test/parallel/test-signal-safety.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); var Signal = process.binding('signal_wrap').Signal; // Test Signal `this` safety diff --git a/test/parallel/test-socket-write-after-fin-error.js b/test/parallel/test-socket-write-after-fin-error.js index 480d5d2edc321e..8ceb0c65585750 100644 --- a/test/parallel/test-socket-write-after-fin-error.js +++ b/test/parallel/test-socket-write-after-fin-error.js @@ -1,13 +1,13 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); // This is similar to simple/test-socket-write-after-fin, except that // we don't set allowHalfOpen. Then we write after the client has sent // a FIN, and this is an error. However, the standard "write after end" // message is too vague, and doesn't actually tell you what happens. -var net = require('net'); +const net = require('net'); var serverData = ''; var gotServerEnd = false; var clientData = ''; diff --git a/test/parallel/test-socket-write-after-fin.js b/test/parallel/test-socket-write-after-fin.js index 70f0d9bf843f9b..17847f973387f1 100644 --- a/test/parallel/test-socket-write-after-fin.js +++ b/test/parallel/test-socket-write-after-fin.js @@ -1,7 +1,7 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); -var net = require('net'); +const assert = require('assert'); +const net = require('net'); const expected = 'hello1hello2hello3\nTHUNDERMUSCLE!'; var server = net.createServer({ diff --git a/test/parallel/test-stdin-pipe-resume.js b/test/parallel/test-stdin-pipe-resume.js index cb288070450a1f..663649134fe397 100644 --- a/test/parallel/test-stdin-pipe-resume.js +++ b/test/parallel/test-stdin-pipe-resume.js @@ -1,12 +1,12 @@ 'use strict'; // This tests that piping stdin will cause it to resume() as well. require('../common'); -var assert = require('assert'); +const assert = require('assert'); if (process.argv[2] === 'child') { process.stdin.pipe(process.stdout); } else { - var spawn = require('child_process').spawn; + const spawn = require('child_process').spawn; var buffers = []; var child = spawn(process.execPath, [__filename, 'child']); child.stdout.on('data', function(c) { diff --git a/test/parallel/test-stdio-readable-writable.js b/test/parallel/test-stdio-readable-writable.js index 7b9b69d309aec5..0bc7fe269b3303 100644 --- a/test/parallel/test-stdio-readable-writable.js +++ b/test/parallel/test-stdio-readable-writable.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); assert(process.stdout.writable); assert(!process.stdout.readable); diff --git a/test/parallel/test-stdout-cannot-be-closed-child-process-pipe.js b/test/parallel/test-stdout-cannot-be-closed-child-process-pipe.js index a138108fae7e01..bfc7a1ddf4dc8e 100644 --- a/test/parallel/test-stdout-cannot-be-closed-child-process-pipe.js +++ b/test/parallel/test-stdout-cannot-be-closed-child-process-pipe.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); if (process.argv[2] === 'child') process.stdout.end('foo'); @@ -8,7 +8,7 @@ else parent(); function parent() { - var spawn = require('child_process').spawn; + const spawn = require('child_process').spawn; var child = spawn(process.execPath, [__filename, 'child']); var out = ''; var err = ''; diff --git a/test/parallel/test-stdout-stderr-reading.js b/test/parallel/test-stdout-stderr-reading.js index e154d41b6bb8d1..b61edf194fc4ac 100644 --- a/test/parallel/test-stdout-stderr-reading.js +++ b/test/parallel/test-stdout-stderr-reading.js @@ -1,9 +1,9 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); +const assert = require('assert'); // verify that stdout is never read from. -var net = require('net'); +const net = require('net'); var read = net.Socket.prototype.read; net.Socket.prototype.read = function() { @@ -20,7 +20,7 @@ else parent(); function parent() { - var spawn = require('child_process').spawn; + const spawn = require('child_process').spawn; var node = process.execPath; var c1 = spawn(node, [__filename, 'child']); diff --git a/test/parallel/test-stream-pipe-event.js b/test/parallel/test-stream-pipe-event.js index d8601dd04a4d8e..77cd5d26f9fc11 100644 --- a/test/parallel/test-stream-pipe-event.js +++ b/test/parallel/test-stream-pipe-event.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var stream = require('stream'); -var assert = require('assert'); -var util = require('util'); +const stream = require('stream'); +const assert = require('assert'); +const util = require('util'); function Writable() { this.writable = true; diff --git a/test/parallel/test-stream-push-order.js b/test/parallel/test-stream-push-order.js index 22a3156f62f502..4be2ca4a9fbe00 100644 --- a/test/parallel/test-stream-push-order.js +++ b/test/parallel/test-stream-push-order.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var Readable = require('stream').Readable; -var assert = require('assert'); +const Readable = require('stream').Readable; +const assert = require('assert'); var s = new Readable({ highWaterMark: 20, diff --git a/test/parallel/test-stream-push-strings.js b/test/parallel/test-stream-push-strings.js index a5ebe4d3e917f6..85f5a6bf27d4ad 100644 --- a/test/parallel/test-stream-push-strings.js +++ b/test/parallel/test-stream-push-strings.js @@ -1,9 +1,9 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); -var Readable = require('stream').Readable; -var util = require('util'); +const Readable = require('stream').Readable; +const util = require('util'); util.inherits(MyStream, Readable); function MyStream(options) { diff --git a/test/parallel/test-stream-readable-constructor-set-methods.js b/test/parallel/test-stream-readable-constructor-set-methods.js index fb2114f44dad19..86fab5ae54b90c 100644 --- a/test/parallel/test-stream-readable-constructor-set-methods.js +++ b/test/parallel/test-stream-readable-constructor-set-methods.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); -var Readable = require('stream').Readable; +const Readable = require('stream').Readable; var _readCalled = false; function _read(n) { diff --git a/test/parallel/test-stream-readable-flow-recursion.js b/test/parallel/test-stream-readable-flow-recursion.js index 0c0b16e8f5ca7e..48615ed0a95414 100644 --- a/test/parallel/test-stream-readable-flow-recursion.js +++ b/test/parallel/test-stream-readable-flow-recursion.js @@ -1,13 +1,13 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); // this test verifies that passing a huge number to read(size) // will push up the highWaterMark, and cause the stream to read // more data continuously, but without triggering a nextTick // warning or RangeError. -var Readable = require('stream').Readable; +const Readable = require('stream').Readable; // throw an error if we trigger a nextTick warning. process.throwDeprecation = true; diff --git a/test/parallel/test-stream-transform-constructor-set-methods.js b/test/parallel/test-stream-transform-constructor-set-methods.js index 720357a01b9839..c57a633c55441e 100644 --- a/test/parallel/test-stream-transform-constructor-set-methods.js +++ b/test/parallel/test-stream-transform-constructor-set-methods.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); -var Transform = require('stream').Transform; +const Transform = require('stream').Transform; var _transformCalled = false; function _transform(d, e, n) { diff --git a/test/parallel/test-stream-transform-split-objectmode.js b/test/parallel/test-stream-transform-split-objectmode.js index 610f234bead901..10fae6573c5e8f 100644 --- a/test/parallel/test-stream-transform-split-objectmode.js +++ b/test/parallel/test-stream-transform-split-objectmode.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); -var Transform = require('stream').Transform; +const Transform = require('stream').Transform; var parser = new Transform({ readableObjectMode: true }); diff --git a/test/parallel/test-stream-unshift-empty-chunk.js b/test/parallel/test-stream-unshift-empty-chunk.js index 477f5c4be56bac..196a36e7ebdbf1 100644 --- a/test/parallel/test-stream-unshift-empty-chunk.js +++ b/test/parallel/test-stream-unshift-empty-chunk.js @@ -1,10 +1,10 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); // This test verifies that stream.unshift(Buffer.alloc(0)) or // stream.unshift('') does not set state.reading=false. -var Readable = require('stream').Readable; +const Readable = require('stream').Readable; var r = new Readable(); var nChunks = 10; diff --git a/test/parallel/test-stream-writable-change-default-encoding.js b/test/parallel/test-stream-writable-change-default-encoding.js index d1d4af5b824baf..9d527fa9c5e764 100644 --- a/test/parallel/test-stream-writable-change-default-encoding.js +++ b/test/parallel/test-stream-writable-change-default-encoding.js @@ -1,9 +1,9 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); -var stream = require('stream'); -var util = require('util'); +const stream = require('stream'); +const util = require('util'); function MyWritable(fn, options) { stream.Writable.call(this, options); diff --git a/test/parallel/test-stream-writable-constructor-set-methods.js b/test/parallel/test-stream-writable-constructor-set-methods.js index 7d7dfb5f1ccfa0..40f624f293b05e 100644 --- a/test/parallel/test-stream-writable-constructor-set-methods.js +++ b/test/parallel/test-stream-writable-constructor-set-methods.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); -var Writable = require('stream').Writable; +const Writable = require('stream').Writable; var _writeCalled = false; function _write(d, e, n) { diff --git a/test/parallel/test-stream-writable-decoded-encoding.js b/test/parallel/test-stream-writable-decoded-encoding.js index 621e342a3c2d74..4c903a0b012e3e 100644 --- a/test/parallel/test-stream-writable-decoded-encoding.js +++ b/test/parallel/test-stream-writable-decoded-encoding.js @@ -1,9 +1,9 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); -var stream = require('stream'); -var util = require('util'); +const stream = require('stream'); +const util = require('util'); function MyWritable(fn, options) { stream.Writable.call(this, options); diff --git a/test/parallel/test-stream-writev.js b/test/parallel/test-stream-writev.js index d024abbceb7f59..fc3b09985724d8 100644 --- a/test/parallel/test-stream-writev.js +++ b/test/parallel/test-stream-writev.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); -var stream = require('stream'); +const stream = require('stream'); var queue = []; for (var decode = 0; decode < 2; decode++) { diff --git a/test/parallel/test-stream2-base64-single-char-read-end.js b/test/parallel/test-stream2-base64-single-char-read-end.js index 50bafc3737385d..41075334241f7a 100644 --- a/test/parallel/test-stream2-base64-single-char-read-end.js +++ b/test/parallel/test-stream2-base64-single-char-read-end.js @@ -1,8 +1,8 @@ 'use strict'; const common = require('../common'); -var R = require('_stream_readable'); -var W = require('_stream_writable'); -var assert = require('assert'); +const R = require('_stream_readable'); +const W = require('_stream_writable'); +const assert = require('assert'); var src = new R({encoding: 'base64'}); var dst = new W(); diff --git a/test/parallel/test-stream2-compatibility.js b/test/parallel/test-stream2-compatibility.js index 77312456590b25..d4bf32a19922d0 100644 --- a/test/parallel/test-stream2-compatibility.js +++ b/test/parallel/test-stream2-compatibility.js @@ -1,10 +1,10 @@ 'use strict'; require('../common'); -var R = require('_stream_readable'); -var W = require('_stream_writable'); -var assert = require('assert'); +const R = require('_stream_readable'); +const W = require('_stream_writable'); +const assert = require('assert'); -var util = require('util'); +const util = require('util'); var ondataCalled = 0; diff --git a/test/parallel/test-stream2-finish-pipe.js b/test/parallel/test-stream2-finish-pipe.js index fb489978f498ad..ee9ee20bd5237d 100644 --- a/test/parallel/test-stream2-finish-pipe.js +++ b/test/parallel/test-stream2-finish-pipe.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var stream = require('stream'); -var Buffer = require('buffer').Buffer; +const stream = require('stream'); +const Buffer = require('buffer').Buffer; var r = new stream.Readable(); r._read = function(size) { diff --git a/test/parallel/test-stream2-httpclient-response-end.js b/test/parallel/test-stream2-httpclient-response-end.js index d674086055e431..c4570e8b02db43 100644 --- a/test/parallel/test-stream2-httpclient-response-end.js +++ b/test/parallel/test-stream2-httpclient-response-end.js @@ -1,7 +1,7 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); -var http = require('http'); +const assert = require('assert'); +const http = require('http'); var msg = 'Hello'; var server = http.createServer(function(req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); diff --git a/test/parallel/test-stream2-large-read-stall.js b/test/parallel/test-stream2-large-read-stall.js index a2ae3f5174272d..60e4a2873a0945 100644 --- a/test/parallel/test-stream2-large-read-stall.js +++ b/test/parallel/test-stream2-large-read-stall.js @@ -1,6 +1,6 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); +const assert = require('assert'); // If everything aligns so that you do a read(n) of exactly the // remaining buffer, then make sure that 'end' still emits. @@ -10,7 +10,7 @@ var PUSHSIZE = 20; var PUSHCOUNT = 1000; var HWM = 50; -var Readable = require('stream').Readable; +const Readable = require('stream').Readable; var r = new Readable({ highWaterMark: HWM }); diff --git a/test/parallel/test-stream2-objects.js b/test/parallel/test-stream2-objects.js index b18be26dc530fb..6b50ba8436bfa6 100644 --- a/test/parallel/test-stream2-objects.js +++ b/test/parallel/test-stream2-objects.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var Readable = require('_stream_readable'); -var Writable = require('_stream_writable'); -var assert = require('assert'); +const Readable = require('_stream_readable'); +const Writable = require('_stream_writable'); +const assert = require('assert'); // tiny node-tap lookalike. var tests = []; diff --git a/test/parallel/test-stream2-pipe-error-handling.js b/test/parallel/test-stream2-pipe-error-handling.js index bdf7a4a9a33a77..cdd1b1a364e183 100644 --- a/test/parallel/test-stream2-pipe-error-handling.js +++ b/test/parallel/test-stream2-pipe-error-handling.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var stream = require('stream'); +const assert = require('assert'); +const stream = require('stream'); { let count = 1000; diff --git a/test/parallel/test-stream2-pipe-error-once-listener.js b/test/parallel/test-stream2-pipe-error-once-listener.js index c9cfd1d1c80c19..a2ddb7f5d6e720 100644 --- a/test/parallel/test-stream2-pipe-error-once-listener.js +++ b/test/parallel/test-stream2-pipe-error-once-listener.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var util = require('util'); -var stream = require('stream'); +const util = require('util'); +const stream = require('stream'); var Read = function() { diff --git a/test/parallel/test-stream2-push.js b/test/parallel/test-stream2-push.js index 445a186715b659..26f27529071cbf 100644 --- a/test/parallel/test-stream2-push.js +++ b/test/parallel/test-stream2-push.js @@ -1,16 +1,15 @@ 'use strict'; require('../common'); -var stream = require('stream'); -var Readable = stream.Readable; -var Writable = stream.Writable; -var assert = require('assert'); +const Readable = require('stream').Readable; +const Writable = require('stream').Writable; +const assert = require('assert'); -var EE = require('events').EventEmitter; +const EE = require('events').EventEmitter; // a mock thing a bit like the net.Socket/tcp_wrap.handle interaction -stream = new Readable({ +const stream = new Readable({ highWaterMark: 16, encoding: 'utf8' }); diff --git a/test/parallel/test-stream2-read-sync-stack.js b/test/parallel/test-stream2-read-sync-stack.js index b2cfd05f872e30..1ba31a4b31b725 100644 --- a/test/parallel/test-stream2-read-sync-stack.js +++ b/test/parallel/test-stream2-read-sync-stack.js @@ -1,6 +1,6 @@ 'use strict'; const common = require('../common'); -var Readable = require('stream').Readable; +const Readable = require('stream').Readable; var r = new Readable(); var N = 256 * 1024; diff --git a/test/parallel/test-stream2-readable-from-list.js b/test/parallel/test-stream2-readable-from-list.js index 2aa0725f734117..e38200e9d6ab1f 100644 --- a/test/parallel/test-stream2-readable-from-list.js +++ b/test/parallel/test-stream2-readable-from-list.js @@ -1,9 +1,9 @@ // Flags: --expose_internals 'use strict'; require('../common'); -var assert = require('assert'); -var fromList = require('_stream_readable')._fromList; -var BufferList = require('internal/streams/BufferList'); +const assert = require('assert'); +const fromList = require('_stream_readable')._fromList; +const BufferList = require('internal/streams/BufferList'); // tiny node-tap lookalike. var tests = []; diff --git a/test/parallel/test-stream2-readable-legacy-drain.js b/test/parallel/test-stream2-readable-legacy-drain.js index 8a0687a6ebd90c..1b8a4ac1ffeca3 100644 --- a/test/parallel/test-stream2-readable-legacy-drain.js +++ b/test/parallel/test-stream2-readable-legacy-drain.js @@ -1,8 +1,8 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); +const assert = require('assert'); -var Stream = require('stream'); +const Stream = require('stream'); var Readable = Stream.Readable; var r = new Readable(); diff --git a/test/parallel/test-stream2-readable-non-empty-end.js b/test/parallel/test-stream2-readable-non-empty-end.js index dd2cb8d51055c7..0a4eb131c312ab 100644 --- a/test/parallel/test-stream2-readable-non-empty-end.js +++ b/test/parallel/test-stream2-readable-non-empty-end.js @@ -1,7 +1,7 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); -var Readable = require('_stream_readable'); +const assert = require('assert'); +const Readable = require('_stream_readable'); var len = 0; var chunks = new Array(10); diff --git a/test/parallel/test-stream2-readable-wrap-empty.js b/test/parallel/test-stream2-readable-wrap-empty.js index 02de3cf5b4cb23..aa48c20bb83703 100644 --- a/test/parallel/test-stream2-readable-wrap-empty.js +++ b/test/parallel/test-stream2-readable-wrap-empty.js @@ -1,8 +1,8 @@ 'use strict'; const common = require('../common'); -var Readable = require('_stream_readable'); -var EE = require('events').EventEmitter; +const Readable = require('_stream_readable'); +const EE = require('events').EventEmitter; var oldStream = new EE(); oldStream.pause = function() {}; diff --git a/test/parallel/test-stream2-set-encoding.js b/test/parallel/test-stream2-set-encoding.js index 3deb67d48e7156..c7cc7c3c0bfb2f 100644 --- a/test/parallel/test-stream2-set-encoding.js +++ b/test/parallel/test-stream2-set-encoding.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var R = require('_stream_readable'); -var util = require('util'); +const assert = require('assert'); +const R = require('_stream_readable'); +const util = require('util'); // tiny node-tap lookalike. var tests = []; diff --git a/test/parallel/test-stream2-transform.js b/test/parallel/test-stream2-transform.js index 6a4036681f90b7..0777ada97fb376 100644 --- a/test/parallel/test-stream2-transform.js +++ b/test/parallel/test-stream2-transform.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var PassThrough = require('_stream_passthrough'); -var Transform = require('_stream_transform'); +const assert = require('assert'); +const PassThrough = require('_stream_passthrough'); +const Transform = require('_stream_transform'); // tiny node-tap lookalike. var tests = []; diff --git a/test/parallel/test-stream2-unpipe-leak.js b/test/parallel/test-stream2-unpipe-leak.js index d94e39f7667df4..2004a8194c7803 100644 --- a/test/parallel/test-stream2-unpipe-leak.js +++ b/test/parallel/test-stream2-unpipe-leak.js @@ -1,11 +1,11 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var stream = require('stream'); +const assert = require('assert'); +const stream = require('stream'); var chunk = Buffer.from('hallo'); -var util = require('util'); +const util = require('util'); function TestWriter() { stream.Writable.call(this); diff --git a/test/parallel/test-stream2-writable.js b/test/parallel/test-stream2-writable.js index 5ecdd0f76ecb5a..4d98457e7d6eaa 100644 --- a/test/parallel/test-stream2-writable.js +++ b/test/parallel/test-stream2-writable.js @@ -1,10 +1,10 @@ 'use strict'; require('../common'); -var W = require('_stream_writable'); -var D = require('_stream_duplex'); -var assert = require('assert'); +const W = require('_stream_writable'); +const D = require('_stream_duplex'); +const assert = require('assert'); -var util = require('util'); +const util = require('util'); util.inherits(TestWriter, W); function TestWriter() { diff --git a/test/parallel/test-stream3-pause-then-read.js b/test/parallel/test-stream3-pause-then-read.js index 64d25fefc94c86..996f91cf79f9b4 100644 --- a/test/parallel/test-stream3-pause-then-read.js +++ b/test/parallel/test-stream3-pause-then-read.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); -var stream = require('stream'); +const stream = require('stream'); var Readable = stream.Readable; var Writable = stream.Writable; diff --git a/test/parallel/test-string-decoder-end.js b/test/parallel/test-string-decoder-end.js index 33b47a034a93bc..9b6696977c8267 100644 --- a/test/parallel/test-string-decoder-end.js +++ b/test/parallel/test-string-decoder-end.js @@ -4,8 +4,8 @@ // result of the entire buffer. require('../common'); -var assert = require('assert'); -var SD = require('string_decoder').StringDecoder; +const assert = require('assert'); +const SD = require('string_decoder').StringDecoder; var encodings = ['base64', 'hex', 'utf8', 'utf16le', 'ucs2']; var bufs = [ '☃💩', 'asdf' ].map(function(b) { diff --git a/test/parallel/test-string-decoder.js b/test/parallel/test-string-decoder.js index 151ae8b4e0b11a..97c0aafef237ed 100644 --- a/test/parallel/test-string-decoder.js +++ b/test/parallel/test-string-decoder.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var inspect = require('util').inspect; -var StringDecoder = require('string_decoder').StringDecoder; +const assert = require('assert'); +const inspect = require('util').inspect; +const StringDecoder = require('string_decoder').StringDecoder; // Test default encoding var decoder = new StringDecoder(); diff --git a/test/parallel/test-stringbytes-external.js b/test/parallel/test-stringbytes-external.js index a34612f75d71f6..e0d8c4552e02c7 100644 --- a/test/parallel/test-stringbytes-external.js +++ b/test/parallel/test-stringbytes-external.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); // minimum string size to overflow into external string space var EXTERN_APEX = 0xFBEE9; diff --git a/test/parallel/test-sys.js b/test/parallel/test-sys.js index 3e28f020333c20..234744bb118fd7 100644 --- a/test/parallel/test-sys.js +++ b/test/parallel/test-sys.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var sys = require('sys'); // eslint-disable-line no-restricted-modules -var util = require('util'); +const assert = require('assert'); +const sys = require('sys'); // eslint-disable-line no-restricted-modules +const util = require('util'); assert.strictEqual(sys, util); diff --git a/test/parallel/test-tcp-wrap-connect.js b/test/parallel/test-tcp-wrap-connect.js index 7ce88d194cd648..92114bad39dbcd 100644 --- a/test/parallel/test-tcp-wrap-connect.js +++ b/test/parallel/test-tcp-wrap-connect.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); var TCP = process.binding('tcp_wrap').TCP; var TCPConnectWrap = process.binding('tcp_wrap').TCPConnectWrap; var ShutdownWrap = process.binding('stream_wrap').ShutdownWrap; @@ -39,7 +39,7 @@ var connectCount = 0; var endCount = 0; var shutdownCount = 0; -var server = require('net').Server(function(s) { +const server = require('net').Server(function(s) { connectCount++; s.resume(); s.on('end', function() { diff --git a/test/parallel/test-tcp-wrap.js b/test/parallel/test-tcp-wrap.js index 18b8fe401f8902..0d023ebf8d6d0d 100644 --- a/test/parallel/test-tcp-wrap.js +++ b/test/parallel/test-tcp-wrap.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); var TCP = process.binding('tcp_wrap').TCP; var uv = process.binding('uv'); diff --git a/test/parallel/test-timer-close.js b/test/parallel/test-timer-close.js index f13078e5a5bed1..28217ce0397b0f 100644 --- a/test/parallel/test-timer-close.js +++ b/test/parallel/test-timer-close.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); var t = new (process.binding('timer_wrap').Timer)(); var called = 0; diff --git a/test/parallel/test-timers-args.js b/test/parallel/test-timers-args.js index 21eafd1bcd9ea6..4638cb39ccf6b9 100644 --- a/test/parallel/test-timers-args.js +++ b/test/parallel/test-timers-args.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); function range(n) { return 'x'.repeat(n + 1).split('').map(function(_, i) { return i; }); diff --git a/test/parallel/test-timers-immediate-queue.js b/test/parallel/test-timers-immediate-queue.js index 62482d510a6608..fd952301500af9 100644 --- a/test/parallel/test-timers-immediate-queue.js +++ b/test/parallel/test-timers-immediate-queue.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); // setImmediate should run clear its queued cbs once per event loop turn // but immediates queued while processing the current queue should happen diff --git a/test/parallel/test-timers-ordering.js b/test/parallel/test-timers-ordering.js index c23af9d8307e9a..79b16338e65d79 100644 --- a/test/parallel/test-timers-ordering.js +++ b/test/parallel/test-timers-ordering.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); var Timer = process.binding('timer_wrap').Timer; var N = 30; diff --git a/test/parallel/test-timers-uncaught-exception.js b/test/parallel/test-timers-uncaught-exception.js index 6b6dc583715849..84dae65af45c13 100644 --- a/test/parallel/test-timers-uncaught-exception.js +++ b/test/parallel/test-timers-uncaught-exception.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); var exceptions = 0; var timer1 = 0; diff --git a/test/parallel/test-timers-unref-leak.js b/test/parallel/test-timers-unref-leak.js index a1b1265763bf1d..6a1f275ae5dda3 100644 --- a/test/parallel/test-timers-unref-leak.js +++ b/test/parallel/test-timers-unref-leak.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); var called = 0; var closed = 0; diff --git a/test/parallel/test-timers-unref.js b/test/parallel/test-timers-unref.js index 801b34792a1f73..c47931b965fd09 100644 --- a/test/parallel/test-timers-unref.js +++ b/test/parallel/test-timers-unref.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); let interval_fired = false; let timeout_fired = false; diff --git a/test/parallel/test-timers.js b/test/parallel/test-timers.js index 0b379e0eb45ad0..38d8fd86b17cce 100644 --- a/test/parallel/test-timers.js +++ b/test/parallel/test-timers.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); var inputs = [ undefined, diff --git a/test/parallel/test-tls-alert.js b/test/parallel/test-tls-alert.js index db22443918453b..59cd355f35a67a 100644 --- a/test/parallel/test-tls-alert.js +++ b/test/parallel/test-tls-alert.js @@ -1,6 +1,6 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); if (!common.opensslCli) { common.skip('node compiled without OpenSSL CLI.'); @@ -11,10 +11,10 @@ if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var tls = require('tls'); +const tls = require('tls'); -var fs = require('fs'); -var spawn = require('child_process').spawn; +const fs = require('fs'); +const spawn = require('child_process').spawn; var success = false; diff --git a/test/parallel/test-tls-async-cb-after-socket-end.js b/test/parallel/test-tls-async-cb-after-socket-end.js index dcde224e04344c..dc03e74c652ab3 100644 --- a/test/parallel/test-tls-async-cb-after-socket-end.js +++ b/test/parallel/test-tls-async-cb-after-socket-end.js @@ -10,7 +10,7 @@ const path = require('path'); const fs = require('fs'); const SSL_OP_NO_TICKET = require('crypto').constants.SSL_OP_NO_TICKET; -var tls = require('tls'); +const tls = require('tls'); var options = { secureOptions: SSL_OP_NO_TICKET, diff --git a/test/parallel/test-tls-cert-regression.js b/test/parallel/test-tls-cert-regression.js index a26bab7c46e107..e74201bc2e35e5 100644 --- a/test/parallel/test-tls-cert-regression.js +++ b/test/parallel/test-tls-cert-regression.js @@ -1,11 +1,11 @@ 'use strict'; -var common = require('../common'); +const common = require('../common'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var tls = require('tls'); +const tls = require('tls'); var cert = diff --git a/test/parallel/test-tls-client-abort.js b/test/parallel/test-tls-client-abort.js index d2fcf3e687e676..f48d22c4fc48cd 100644 --- a/test/parallel/test-tls-client-abort.js +++ b/test/parallel/test-tls-client-abort.js @@ -1,15 +1,15 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var tls = require('tls'); +const tls = require('tls'); -var fs = require('fs'); -var path = require('path'); +const fs = require('fs'); +const path = require('path'); var cert = fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')); var key = fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')); diff --git a/test/parallel/test-tls-client-abort2.js b/test/parallel/test-tls-client-abort2.js index f3295f6d854a72..dd224be8741abd 100644 --- a/test/parallel/test-tls-client-abort2.js +++ b/test/parallel/test-tls-client-abort2.js @@ -1,12 +1,12 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var tls = require('tls'); +const tls = require('tls'); var conn = tls.connect(common.PORT, common.fail); conn.on('error', common.mustCall(function() { diff --git a/test/parallel/test-tls-client-default-ciphers.js b/test/parallel/test-tls-client-default-ciphers.js index 33766dfd5b13b2..f8fdab1102a795 100644 --- a/test/parallel/test-tls-client-default-ciphers.js +++ b/test/parallel/test-tls-client-default-ciphers.js @@ -1,12 +1,12 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); +const assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var tls = require('tls'); +const tls = require('tls'); function Done() {} diff --git a/test/parallel/test-tls-client-destroy-soon.js b/test/parallel/test-tls-client-destroy-soon.js index 171aa328142e13..3e792305147de2 100644 --- a/test/parallel/test-tls-client-destroy-soon.js +++ b/test/parallel/test-tls-client-destroy-soon.js @@ -3,16 +3,16 @@ // Cache session and close connection. Use session on second connection. // ASSERT resumption. -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var tls = require('tls'); +const tls = require('tls'); -var fs = require('fs'); +const fs = require('fs'); var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'), diff --git a/test/parallel/test-tls-client-mindhsize.js b/test/parallel/test-tls-client-mindhsize.js index 1d812a72093ba9..55a32ad6c2a469 100644 --- a/test/parallel/test-tls-client-mindhsize.js +++ b/test/parallel/test-tls-client-mindhsize.js @@ -1,14 +1,14 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); process.exit(); } -var tls = require('tls'); +const tls = require('tls'); -var fs = require('fs'); +const fs = require('fs'); var key = fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'); var cert = fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem'); diff --git a/test/parallel/test-tls-client-resume.js b/test/parallel/test-tls-client-resume.js index 75524a3a189b3e..029f10d449fe31 100644 --- a/test/parallel/test-tls-client-resume.js +++ b/test/parallel/test-tls-client-resume.js @@ -3,16 +3,16 @@ // Cache session and close connection. Use session on second connection. // ASSERT resumption. -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var tls = require('tls'); +const tls = require('tls'); -var fs = require('fs'); +const fs = require('fs'); var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'), diff --git a/test/parallel/test-tls-close-error.js b/test/parallel/test-tls-close-error.js index 2da7a192c30ebc..6b37d5c1cef00e 100644 --- a/test/parallel/test-tls-close-error.js +++ b/test/parallel/test-tls-close-error.js @@ -1,15 +1,15 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); +const assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var tls = require('tls'); +const tls = require('tls'); -var fs = require('fs'); +const fs = require('fs'); var server = tls.createServer({ key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), diff --git a/test/parallel/test-tls-close-notify.js b/test/parallel/test-tls-close-notify.js index 51b16746e30533..3dd2afbd6e5545 100644 --- a/test/parallel/test-tls-close-notify.js +++ b/test/parallel/test-tls-close-notify.js @@ -1,13 +1,13 @@ 'use strict'; -var common = require('../common'); +const common = require('../common'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var tls = require('tls'); +const tls = require('tls'); -var fs = require('fs'); +const fs = require('fs'); var server = tls.createServer({ key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), diff --git a/test/parallel/test-tls-connect-no-host.js b/test/parallel/test-tls-connect-no-host.js index e2e0238ff8d0ad..2b81698664c4ab 100644 --- a/test/parallel/test-tls-connect-no-host.js +++ b/test/parallel/test-tls-connect-no-host.js @@ -1,15 +1,15 @@ 'use strict'; -var common = require('../common'); +const common = require('../common'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var tls = require('tls'); +const tls = require('tls'); -var assert = require('assert'); -var fs = require('fs'); -var path = require('path'); +const assert = require('assert'); +const fs = require('fs'); +const path = require('path'); var cert = fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')); var key = fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')); diff --git a/test/parallel/test-tls-connect-pipe.js b/test/parallel/test-tls-connect-pipe.js index 6ec218e00366f6..67a53c4ebf78a4 100644 --- a/test/parallel/test-tls-connect-pipe.js +++ b/test/parallel/test-tls-connect-pipe.js @@ -1,13 +1,13 @@ 'use strict'; -var common = require('../common'); +const common = require('../common'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var tls = require('tls'); +const tls = require('tls'); -var fs = require('fs'); +const fs = require('fs'); var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), diff --git a/test/parallel/test-tls-connect.js b/test/parallel/test-tls-connect.js index cd4edd89f7b483..082e2e48a9dcc0 100644 --- a/test/parallel/test-tls-connect.js +++ b/test/parallel/test-tls-connect.js @@ -1,15 +1,15 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var tls = require('tls'); +const tls = require('tls'); -var fs = require('fs'); -var path = require('path'); +const fs = require('fs'); +const path = require('path'); // https://github.com/joyent/node/issues/1218 // uncatchable exception on TLS connection error diff --git a/test/parallel/test-tls-delayed-attach-error.js b/test/parallel/test-tls-delayed-attach-error.js index a5fa91383d7d75..e7cfd4fa6ab557 100644 --- a/test/parallel/test-tls-delayed-attach-error.js +++ b/test/parallel/test-tls-delayed-attach-error.js @@ -1,13 +1,13 @@ 'use strict'; -var common = require('../common'); +const common = require('../common'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var tls = require('tls'); -var fs = require('fs'); -var net = require('net'); +const tls = require('tls'); +const fs = require('fs'); +const net = require('net'); var bonkers = Buffer.alloc(1024, 42); diff --git a/test/parallel/test-tls-delayed-attach.js b/test/parallel/test-tls-delayed-attach.js index b1e4beb2313c9a..867fc5edb88b03 100644 --- a/test/parallel/test-tls-delayed-attach.js +++ b/test/parallel/test-tls-delayed-attach.js @@ -1,15 +1,15 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var tls = require('tls'); +const tls = require('tls'); -var fs = require('fs'); -var net = require('net'); +const fs = require('fs'); +const net = require('net'); var sent = 'hello world'; var received = ''; diff --git a/test/parallel/test-tls-dhe.js b/test/parallel/test-tls-dhe.js index 196f5eb497fc4f..6340833765cd41 100644 --- a/test/parallel/test-tls-dhe.js +++ b/test/parallel/test-tls-dhe.js @@ -1,15 +1,15 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var tls = require('tls'); +const tls = require('tls'); -var spawn = require('child_process').spawn; -var fs = require('fs'); +const spawn = require('child_process').spawn; +const fs = require('fs'); var key = fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'); var cert = fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem'); var nsuccess = 0; diff --git a/test/parallel/test-tls-ecdh-disable.js b/test/parallel/test-tls-ecdh-disable.js index c2a7440a686a10..df51c5d0855d65 100644 --- a/test/parallel/test-tls-ecdh-disable.js +++ b/test/parallel/test-tls-ecdh-disable.js @@ -1,15 +1,15 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var tls = require('tls'); +const tls = require('tls'); -var exec = require('child_process').exec; -var fs = require('fs'); +const exec = require('child_process').exec; +const fs = require('fs'); var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'), diff --git a/test/parallel/test-tls-econnreset.js b/test/parallel/test-tls-econnreset.js index d9f6fffd326409..51f178198f1a0a 100644 --- a/test/parallel/test-tls-econnreset.js +++ b/test/parallel/test-tls-econnreset.js @@ -1,12 +1,12 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var tls = require('tls'); +const tls = require('tls'); var cacert = `-----BEGIN CERTIFICATE----- diff --git a/test/parallel/test-tls-fast-writing.js b/test/parallel/test-tls-fast-writing.js index 034a6296659bdd..33665536ba5bd0 100644 --- a/test/parallel/test-tls-fast-writing.js +++ b/test/parallel/test-tls-fast-writing.js @@ -1,14 +1,14 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var tls = require('tls'); +const tls = require('tls'); -var fs = require('fs'); +const fs = require('fs'); var dir = common.fixturesDir; var options = { key: fs.readFileSync(dir + '/test_key.pem'), diff --git a/test/parallel/test-tls-handshake-error.js b/test/parallel/test-tls-handshake-error.js index e76a0961fb7ad6..4d6a64a150c707 100644 --- a/test/parallel/test-tls-handshake-error.js +++ b/test/parallel/test-tls-handshake-error.js @@ -1,15 +1,15 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); +const assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var tls = require('tls'); +const tls = require('tls'); -var fs = require('fs'); +const fs = require('fs'); var server = tls.createServer({ key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), diff --git a/test/parallel/test-tls-handshake-nohang.js b/test/parallel/test-tls-handshake-nohang.js index 052833a50e3462..039c55b486d6a2 100644 --- a/test/parallel/test-tls-handshake-nohang.js +++ b/test/parallel/test-tls-handshake-nohang.js @@ -1,11 +1,11 @@ 'use strict'; -var common = require('../common'); +const common = require('../common'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var tls = require('tls'); +const tls = require('tls'); // neither should hang tls.createSecurePair(null, false, false, false); diff --git a/test/parallel/test-tls-honorcipherorder.js b/test/parallel/test-tls-honorcipherorder.js index 81c2440fe26d23..883abc199ee321 100644 --- a/test/parallel/test-tls-honorcipherorder.js +++ b/test/parallel/test-tls-honorcipherorder.js @@ -1,14 +1,14 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var tls = require('tls'); +const tls = require('tls'); -var fs = require('fs'); +const fs = require('fs'); var nconns = 0; // We explicitly set TLS version to 1.2 so as to be safe when the diff --git a/test/parallel/test-tls-invoke-queued.js b/test/parallel/test-tls-invoke-queued.js index 4008e5f099e4bc..b37b900d77e300 100644 --- a/test/parallel/test-tls-invoke-queued.js +++ b/test/parallel/test-tls-invoke-queued.js @@ -1,14 +1,14 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var tls = require('tls'); +const tls = require('tls'); -var fs = require('fs'); +const fs = require('fs'); var received = ''; diff --git a/test/parallel/test-tls-js-stream.js b/test/parallel/test-tls-js-stream.js index 08095fa99538cf..2f69a306cfdcec 100644 --- a/test/parallel/test-tls-js-stream.js +++ b/test/parallel/test-tls-js-stream.js @@ -1,16 +1,16 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var tls = require('tls'); +const tls = require('tls'); -var stream = require('stream'); -var fs = require('fs'); -var net = require('net'); +const stream = require('stream'); +const fs = require('fs'); +const net = require('net'); var connected = { client: 0, diff --git a/test/parallel/test-tls-legacy-onselect.js b/test/parallel/test-tls-legacy-onselect.js index 72c748248e448d..392df2e71588aa 100644 --- a/test/parallel/test-tls-legacy-onselect.js +++ b/test/parallel/test-tls-legacy-onselect.js @@ -1,12 +1,12 @@ 'use strict'; -var common = require('../common'); +const common = require('../common'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var tls = require('tls'); -var net = require('net'); +const tls = require('tls'); +const net = require('net'); var server = net.Server(common.mustCall(function(raw) { var pair = tls.createSecurePair(null, true, false, false); diff --git a/test/parallel/test-tls-max-send-fragment.js b/test/parallel/test-tls-max-send-fragment.js index 64dd14698916c8..d96f42e6a2e82f 100644 --- a/test/parallel/test-tls-max-send-fragment.js +++ b/test/parallel/test-tls-max-send-fragment.js @@ -1,14 +1,14 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var tls = require('tls'); +const tls = require('tls'); -var fs = require('fs'); +const fs = require('fs'); var buf = Buffer.allocUnsafe(10000); var received = 0; diff --git a/test/parallel/test-tls-multi-key.js b/test/parallel/test-tls-multi-key.js index e29f5ee522829e..840deb59d4bde6 100644 --- a/test/parallel/test-tls-multi-key.js +++ b/test/parallel/test-tls-multi-key.js @@ -1,13 +1,13 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var tls = require('tls'); -var fs = require('fs'); +const tls = require('tls'); +const fs = require('fs'); var options = { key: [ diff --git a/test/parallel/test-tls-no-rsa-key.js b/test/parallel/test-tls-no-rsa-key.js index cc04534bf91973..1e75b21eaba14c 100644 --- a/test/parallel/test-tls-no-rsa-key.js +++ b/test/parallel/test-tls-no-rsa-key.js @@ -1,14 +1,14 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var tls = require('tls'); +const tls = require('tls'); -var fs = require('fs'); +const fs = require('fs'); var options = { key: fs.readFileSync(common.fixturesDir + '/keys/ec-key.pem'), diff --git a/test/parallel/test-tls-no-sslv23.js b/test/parallel/test-tls-no-sslv23.js index 0db61afe0e97ec..ff1214d167e6a0 100644 --- a/test/parallel/test-tls-no-sslv23.js +++ b/test/parallel/test-tls-no-sslv23.js @@ -1,12 +1,12 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var tls = require('tls'); +const tls = require('tls'); assert.throws(function() { tls.createSecureContext({ secureProtocol: 'blargh' }); diff --git a/test/parallel/test-tls-npn-server-client.js b/test/parallel/test-tls-npn-server-client.js index a5fe2da3a2a607..fdd9fcbb328cfb 100644 --- a/test/parallel/test-tls-npn-server-client.js +++ b/test/parallel/test-tls-npn-server-client.js @@ -13,7 +13,7 @@ if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var tls = require('tls'); +const tls = require('tls'); function filenamePEM(n) { diff --git a/test/parallel/test-tls-over-http-tunnel.js b/test/parallel/test-tls-over-http-tunnel.js index c030c7482ff6dd..f55f1c0ac0c450 100644 --- a/test/parallel/test-tls-over-http-tunnel.js +++ b/test/parallel/test-tls-over-http-tunnel.js @@ -1,16 +1,16 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var https = require('https'); +const https = require('https'); -var fs = require('fs'); -var net = require('net'); -var http = require('http'); +const fs = require('fs'); +const net = require('net'); +const http = require('http'); var gotRequest = false; diff --git a/test/parallel/test-tls-pause.js b/test/parallel/test-tls-pause.js index 7f4e02a1bfa96d..aa48c04866654a 100644 --- a/test/parallel/test-tls-pause.js +++ b/test/parallel/test-tls-pause.js @@ -1,15 +1,15 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var tls = require('tls'); +const tls = require('tls'); -var fs = require('fs'); -var path = require('path'); +const fs = require('fs'); +const path = require('path'); var options = { key: fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')), diff --git a/test/parallel/test-tls-peer-certificate-encoding.js b/test/parallel/test-tls-peer-certificate-encoding.js index b59d10faa78bc1..1062dab2af1d2e 100644 --- a/test/parallel/test-tls-peer-certificate-encoding.js +++ b/test/parallel/test-tls-peer-certificate-encoding.js @@ -1,16 +1,16 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var tls = require('tls'); +const tls = require('tls'); -var fs = require('fs'); -var util = require('util'); -var join = require('path').join; +const fs = require('fs'); +const util = require('util'); +const join = require('path').join; var options = { key: fs.readFileSync(join(common.fixturesDir, 'keys', 'agent5-key.pem')), diff --git a/test/parallel/test-tls-peer-certificate-multi-keys.js b/test/parallel/test-tls-peer-certificate-multi-keys.js index 55bc9f40d3a240..6176a34a716096 100644 --- a/test/parallel/test-tls-peer-certificate-multi-keys.js +++ b/test/parallel/test-tls-peer-certificate-multi-keys.js @@ -1,16 +1,16 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var tls = require('tls'); +const tls = require('tls'); -var fs = require('fs'); -var util = require('util'); -var join = require('path').join; +const fs = require('fs'); +const util = require('util'); +const join = require('path').join; var options = { key: fs.readFileSync(join(common.fixturesDir, 'agent.key')), diff --git a/test/parallel/test-tls-request-timeout.js b/test/parallel/test-tls-request-timeout.js index fc793def177f3a..2d1ddf34b32032 100644 --- a/test/parallel/test-tls-request-timeout.js +++ b/test/parallel/test-tls-request-timeout.js @@ -1,14 +1,14 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var tls = require('tls'); +const tls = require('tls'); -var fs = require('fs'); +const fs = require('fs'); var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), diff --git a/test/parallel/test-tls-securepair-server.js b/test/parallel/test-tls-securepair-server.js index 24ac2177c54536..afe76a0139a59d 100644 --- a/test/parallel/test-tls-securepair-server.js +++ b/test/parallel/test-tls-securepair-server.js @@ -1,17 +1,17 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var tls = require('tls'); +const tls = require('tls'); -var join = require('path').join; -var net = require('net'); -var fs = require('fs'); -var spawn = require('child_process').spawn; +const join = require('path').join; +const net = require('net'); +const fs = require('fs'); +const spawn = require('child_process').spawn; var key = fs.readFileSync(join(common.fixturesDir, 'agent.key')).toString(); var cert = fs.readFileSync(join(common.fixturesDir, 'agent.crt')).toString(); diff --git a/test/parallel/test-tls-sni-option.js b/test/parallel/test-tls-sni-option.js index d9823fa3dabdc4..436618379a78e9 100644 --- a/test/parallel/test-tls-sni-option.js +++ b/test/parallel/test-tls-sni-option.js @@ -13,7 +13,7 @@ if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var tls = require('tls'); +const tls = require('tls'); function filenamePEM(n) { return require('path').join(common.fixturesDir, 'keys', n + '.pem'); diff --git a/test/parallel/test-tls-sni-server-client.js b/test/parallel/test-tls-sni-server-client.js index 7a8046c743893d..a22b6a9726a857 100644 --- a/test/parallel/test-tls-sni-server-client.js +++ b/test/parallel/test-tls-sni-server-client.js @@ -13,7 +13,7 @@ if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var tls = require('tls'); +const tls = require('tls'); function filenamePEM(n) { return require('path').join(common.fixturesDir, 'keys', n + '.pem'); diff --git a/test/parallel/test-umask.js b/test/parallel/test-umask.js index 62f9d82b3312ef..397f26ce9013a5 100644 --- a/test/parallel/test-umask.js +++ b/test/parallel/test-umask.js @@ -1,6 +1,6 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); // Note in Windows one can only set the "user" bits. var mask; diff --git a/test/parallel/test-utf8-scripts.js b/test/parallel/test-utf8-scripts.js index 98c26594bb6540..484d3bdefe5eda 100644 --- a/test/parallel/test-utf8-scripts.js +++ b/test/parallel/test-utf8-scripts.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); // üäö diff --git a/test/parallel/test-util-inspect.js b/test/parallel/test-util-inspect.js index b0f89333d25a9b..7df3574a5a5736 100644 --- a/test/parallel/test-util-inspect.js +++ b/test/parallel/test-util-inspect.js @@ -271,7 +271,7 @@ assert.strictEqual(util.inspect(value), '{ 2010-02-14T11:48:40.000Z aprop: 42 }' ); // test the internal isDate implementation -var Date2 = require('vm').runInNewContext('Date'); +const Date2 = vm.runInNewContext('Date'); var d = new Date2(); var orig = util.inspect(d); Date2.prototype.foo = 'bar'; @@ -295,7 +295,7 @@ assert.strictEqual(util.inspect(new Array(5)), '[ , , , , ]'); // test for Array constructor in different context { - const Debug = require('vm').runInDebugContext('Debug'); + const Debug = vm.runInDebugContext('Debug'); const map = new Map(); map.set(1, 2); const mirror = Debug.MakeMirror(map.entries(), true); @@ -309,13 +309,13 @@ assert.strictEqual(util.inspect(new Array(5)), '[ , , , , ]'); } // test for other constructors in different context -var obj = require('vm').runInNewContext('(function(){return {}})()', {}); +let obj = vm.runInNewContext('(function(){return {}})()', {}); assert.strictEqual(util.inspect(obj), '{}'); -obj = require('vm').runInNewContext('var m=new Map();m.set(1,2);m', {}); +obj = vm.runInNewContext('var m=new Map();m.set(1,2);m', {}); assert.strictEqual(util.inspect(obj), 'Map { 1 => 2 }'); -obj = require('vm').runInNewContext('var s=new Set();s.add(1);s.add(2);s', {}); +obj = vm.runInNewContext('var s=new Set();s.add(1);s.add(2);s', {}); assert.strictEqual(util.inspect(obj), 'Set { 1, 2 }'); -obj = require('vm').runInNewContext('fn=function(){};new Promise(fn,fn)', {}); +obj = vm.runInNewContext('fn=function(){};new Promise(fn,fn)', {}); assert.strictEqual(util.inspect(obj), 'Promise { }'); // test for property descriptors diff --git a/test/parallel/test-util-log.js b/test/parallel/test-util-log.js index 91f77d994da847..8480bf83eaf18c 100644 --- a/test/parallel/test-util-log.js +++ b/test/parallel/test-util-log.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var util = require('util'); +const assert = require('assert'); +const util = require('util'); assert.ok(process.stdout.writable); assert.ok(process.stderr.writable); diff --git a/test/parallel/test-v8-flag-type-check.js b/test/parallel/test-v8-flag-type-check.js index 986f37314d605f..b5d4d7c2f12665 100644 --- a/test/parallel/test-v8-flag-type-check.js +++ b/test/parallel/test-v8-flag-type-check.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var v8 = require('v8'); +const assert = require('assert'); +const v8 = require('v8'); assert.throws(function() { v8.setFlagsFromString(1); }, TypeError); assert.throws(function() { v8.setFlagsFromString(); }, TypeError); diff --git a/test/parallel/test-v8-flags.js b/test/parallel/test-v8-flags.js index 50cff9ecefceac..99384080516bb2 100644 --- a/test/parallel/test-v8-flags.js +++ b/test/parallel/test-v8-flags.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var v8 = require('v8'); -var vm = require('vm'); +const assert = require('assert'); +const v8 = require('v8'); +const vm = require('vm'); // Note: changing V8 flags after an isolate started is not guaranteed to work. // Specifically here, V8 may cache compiled scripts between the flip of the diff --git a/test/parallel/test-v8-stats.js b/test/parallel/test-v8-stats.js index 74a9977fbc00c6..dc36beac131446 100644 --- a/test/parallel/test-v8-stats.js +++ b/test/parallel/test-v8-stats.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var v8 = require('v8'); +const assert = require('assert'); +const v8 = require('v8'); var s = v8.getHeapStatistics(); var keys = [ diff --git a/test/parallel/test-vm-basic.js b/test/parallel/test-vm-basic.js index b2b280c21bd173..75163d6cd3218a 100644 --- a/test/parallel/test-vm-basic.js +++ b/test/parallel/test-vm-basic.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var vm = require('vm'); +const assert = require('assert'); +const vm = require('vm'); // Test 1: vm.runInNewContext var sandbox = {}; diff --git a/test/parallel/test-vm-cached-data.js b/test/parallel/test-vm-cached-data.js index aa2dd26ad5a8b7..35ab236ae1eb98 100644 --- a/test/parallel/test-vm-cached-data.js +++ b/test/parallel/test-vm-cached-data.js @@ -15,8 +15,8 @@ function produce(source, count) { const out = spawnSync(process.execPath, [ '-e', ` 'use strict'; - var assert = require('assert'); - var vm = require('vm'); + const assert = require('assert'); + const vm = require('vm'); var data; for (var i = 0; i < ${count}; i++) { diff --git a/test/parallel/test-vm-context-async-script.js b/test/parallel/test-vm-context-async-script.js index b09eda85209807..b4045fbfd3c246 100644 --- a/test/parallel/test-vm-context-async-script.js +++ b/test/parallel/test-vm-context-async-script.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var vm = require('vm'); +const assert = require('assert'); +const vm = require('vm'); var sandbox = { setTimeout: setTimeout }; diff --git a/test/parallel/test-vm-context-property-forwarding.js b/test/parallel/test-vm-context-property-forwarding.js index 4034441615ca9e..03faef596f2872 100644 --- a/test/parallel/test-vm-context-property-forwarding.js +++ b/test/parallel/test-vm-context-property-forwarding.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var vm = require('vm'); +const assert = require('assert'); +const vm = require('vm'); var sandbox = { x: 3 }; diff --git a/test/parallel/test-vm-context.js b/test/parallel/test-vm-context.js index d3269d9035d010..48319be3a9fc58 100644 --- a/test/parallel/test-vm-context.js +++ b/test/parallel/test-vm-context.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); -var vm = require('vm'); +const vm = require('vm'); var Script = vm.Script; var script = new Script('"passed";'); @@ -48,7 +48,7 @@ assert.ok(gh1140Exception, // Issue GH-693: console.error('test RegExp as argument to assert.throws'); -script = vm.createScript('var assert = require(\'assert\'); assert.throws(' + +script = vm.createScript('const assert = require(\'assert\'); assert.throws(' + 'function() { throw "hello world"; }, /hello/);', 'some.js'); script.runInNewContext({ require: require }); diff --git a/test/parallel/test-vm-create-and-run-in-context.js b/test/parallel/test-vm-create-and-run-in-context.js index fc92cf2f6cb6eb..b40491bb611260 100644 --- a/test/parallel/test-vm-create-and-run-in-context.js +++ b/test/parallel/test-vm-create-and-run-in-context.js @@ -1,9 +1,9 @@ 'use strict'; // Flags: --expose-gc require('../common'); -var assert = require('assert'); +const assert = require('assert'); -var vm = require('vm'); +const vm = require('vm'); console.error('run in a new empty context'); var context = vm.createContext(); diff --git a/test/parallel/test-vm-create-context-accessors.js b/test/parallel/test-vm-create-context-accessors.js index 497bab1a57225f..3870b68247d480 100644 --- a/test/parallel/test-vm-create-context-accessors.js +++ b/test/parallel/test-vm-create-context-accessors.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var vm = require('vm'); +const assert = require('assert'); +const vm = require('vm'); var ctx = {}; diff --git a/test/parallel/test-vm-create-context-arg.js b/test/parallel/test-vm-create-context-arg.js index a0c29762330133..76634e5befc3cd 100644 --- a/test/parallel/test-vm-create-context-arg.js +++ b/test/parallel/test-vm-create-context-arg.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var vm = require('vm'); +const assert = require('assert'); +const vm = require('vm'); assert.throws(function() { vm.createContext('string is not supported'); diff --git a/test/parallel/test-vm-create-context-circular-reference.js b/test/parallel/test-vm-create-context-circular-reference.js index 248ef24f69ca07..e6c1ab8b8566f0 100644 --- a/test/parallel/test-vm-create-context-circular-reference.js +++ b/test/parallel/test-vm-create-context-circular-reference.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var vm = require('vm'); +const assert = require('assert'); +const vm = require('vm'); var sbx = {}; sbx.window = sbx; diff --git a/test/parallel/test-vm-cross-context.js b/test/parallel/test-vm-cross-context.js index 5674f582426f1f..c1d115b50beffa 100644 --- a/test/parallel/test-vm-cross-context.js +++ b/test/parallel/test-vm-cross-context.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); -var vm = require('vm'); +const vm = require('vm'); var ctx = vm.createContext(global); assert.doesNotThrow(function() { diff --git a/test/parallel/test-vm-function-declaration.js b/test/parallel/test-vm-function-declaration.js index fd41be7564aab0..976313b5f66b9f 100644 --- a/test/parallel/test-vm-function-declaration.js +++ b/test/parallel/test-vm-function-declaration.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); -var vm = require('vm'); +const vm = require('vm'); var o = vm.createContext({ console: console }); // This triggers the setter callback in node_contextify.cc diff --git a/test/parallel/test-vm-global-define-property.js b/test/parallel/test-vm-global-define-property.js index 73d1520e0dad69..31842ced2ab19c 100644 --- a/test/parallel/test-vm-global-define-property.js +++ b/test/parallel/test-vm-global-define-property.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); -var vm = require('vm'); +const vm = require('vm'); var code = 'Object.defineProperty(this, "f", {\n' + diff --git a/test/parallel/test-vm-global-identity.js b/test/parallel/test-vm-global-identity.js index 7d90408b64c2c7..876318aecec7d9 100644 --- a/test/parallel/test-vm-global-identity.js +++ b/test/parallel/test-vm-global-identity.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var vm = require('vm'); +const assert = require('assert'); +const vm = require('vm'); var ctx = vm.createContext(); ctx.window = ctx; diff --git a/test/parallel/test-vm-harmony-symbols.js b/test/parallel/test-vm-harmony-symbols.js index 1c1274ef3543f6..eeacdaed184562 100644 --- a/test/parallel/test-vm-harmony-symbols.js +++ b/test/parallel/test-vm-harmony-symbols.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var vm = require('vm'); +const assert = require('assert'); +const vm = require('vm'); // The sandbox should have its own Symbol constructor. var sandbox = {}; diff --git a/test/parallel/test-vm-is-context.js b/test/parallel/test-vm-is-context.js index cc106a15fbfc61..474c0686a870eb 100644 --- a/test/parallel/test-vm-is-context.js +++ b/test/parallel/test-vm-is-context.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var vm = require('vm'); +const assert = require('assert'); +const vm = require('vm'); assert.throws(function() { vm.isContext('string is not supported'); diff --git a/test/parallel/test-vm-proxies.js b/test/parallel/test-vm-proxies.js index d908d713748f7f..6532345336fa19 100644 --- a/test/parallel/test-vm-proxies.js +++ b/test/parallel/test-vm-proxies.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var vm = require('vm'); +const assert = require('assert'); +const vm = require('vm'); // src/node_contextify.cc filters out the Proxy object from the parent // context. Make sure that the new context has a Proxy object of its own. diff --git a/test/parallel/test-vm-static-this.js b/test/parallel/test-vm-static-this.js index c4f10c183b6ef2..0f578ac5f8046c 100644 --- a/test/parallel/test-vm-static-this.js +++ b/test/parallel/test-vm-static-this.js @@ -1,7 +1,7 @@ /* eslint-disable strict */ -var common = require('../common'); -var assert = require('assert'); -var vm = require('vm'); +const common = require('../common'); +const assert = require('assert'); +const vm = require('vm'); common.globalCheck = false; diff --git a/test/parallel/test-vm-syntax-error-message.js b/test/parallel/test-vm-syntax-error-message.js index 75748b24e193ee..b4c101d580c4af 100644 --- a/test/parallel/test-vm-syntax-error-message.js +++ b/test/parallel/test-vm-syntax-error-message.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var child_process = require('child_process'); +const assert = require('assert'); +const child_process = require('child_process'); var p = child_process.spawn(process.execPath, [ '-e', diff --git a/test/parallel/test-vm-timeout.js b/test/parallel/test-vm-timeout.js index 0536ae37a1b489..5b78c891e876e1 100644 --- a/test/parallel/test-vm-timeout.js +++ b/test/parallel/test-vm-timeout.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var vm = require('vm'); +const assert = require('assert'); +const vm = require('vm'); // Test 1: Timeout of 100ms executing endless loop assert.throws(function() { diff --git a/test/parallel/test-zerolengthbufferbug.js b/test/parallel/test-zerolengthbufferbug.js index 056fc725ff5593..07113d1e257f65 100644 --- a/test/parallel/test-zerolengthbufferbug.js +++ b/test/parallel/test-zerolengthbufferbug.js @@ -2,7 +2,7 @@ // Serving up a zero-length buffer should work. const common = require('../common'); -var http = require('http'); +const http = require('http'); var server = http.createServer(function(req, res) { var buffer = Buffer.alloc(0); diff --git a/test/pummel/test-abort-fatal-error.js b/test/pummel/test-abort-fatal-error.js index 0bb2cb2c39998e..1fed91d54a6526 100644 --- a/test/pummel/test-abort-fatal-error.js +++ b/test/pummel/test-abort-fatal-error.js @@ -1,13 +1,13 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); +const assert = require('assert'); if (common.isWindows) { common.skip('no RLIMIT_NOFILE on Windows'); return; } -var exec = require('child_process').exec; +const exec = require('child_process').exec; var cmdline = 'ulimit -c 0; ' + process.execPath; cmdline += ' --max-old-space-size=4 --max-semi-space-size=1'; diff --git a/test/pummel/test-child-process-spawn-loop.js b/test/pummel/test-child-process-spawn-loop.js index 7a3cf114b4e8e9..41d9ff1e49c17b 100644 --- a/test/pummel/test-child-process-spawn-loop.js +++ b/test/pummel/test-child-process-spawn-loop.js @@ -1,8 +1,8 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); -var spawn = require('child_process').spawn; +const spawn = require('child_process').spawn; const SIZE = 1000 * 1024; const N = 40; diff --git a/test/pummel/test-dh-regr.js b/test/pummel/test-dh-regr.js index 448319318b44a4..8228332e5dd8e9 100644 --- a/test/pummel/test-dh-regr.js +++ b/test/pummel/test-dh-regr.js @@ -1,12 +1,12 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var crypto = require('crypto'); +const crypto = require('crypto'); var p = crypto.createDiffieHellman(1024).getPrime(); diff --git a/test/pummel/test-dtrace-jsstack.js b/test/pummel/test-dtrace-jsstack.js index 1949045888c138..af9c83bb3ec3c4 100644 --- a/test/pummel/test-dtrace-jsstack.js +++ b/test/pummel/test-dtrace-jsstack.js @@ -1,7 +1,7 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); -var os = require('os'); +const assert = require('assert'); +const os = require('os'); if (!common.isSunOS) { common.skip('no DTRACE support'); @@ -31,7 +31,7 @@ var doogle = function() { bagnoogle('The bfs command', '(almost) like ed(1)'); }; -var spawn = require('child_process').spawn; +const spawn = require('child_process').spawn; /* * We're going to use DTrace to stop us, gcore us, and set us running again diff --git a/test/pummel/test-exec.js b/test/pummel/test-exec.js index 18404373318917..eee3d9286832b2 100644 --- a/test/pummel/test-exec.js +++ b/test/pummel/test-exec.js @@ -1,7 +1,7 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var exec = require('child_process').exec; +const common = require('../common'); +const assert = require('assert'); +const exec = require('child_process').exec; var SLEEP3_COMMAND; if (!common.isWindows) { diff --git a/test/pummel/test-fs-watch-file-slow.js b/test/pummel/test-fs-watch-file-slow.js index 508de487f6dc23..e64e00b32fa602 100644 --- a/test/pummel/test-fs-watch-file-slow.js +++ b/test/pummel/test-fs-watch-file-slow.js @@ -1,8 +1,8 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var path = require('path'); -var fs = require('fs'); +const common = require('../common'); +const assert = require('assert'); +const path = require('path'); +const fs = require('fs'); var FILENAME = path.join(common.tmpDir, 'watch-me'); var TIMEOUT = 1300; diff --git a/test/pummel/test-fs-watch-file.js b/test/pummel/test-fs-watch-file.js index fc291cfe64c618..98199d1e841f4b 100644 --- a/test/pummel/test-fs-watch-file.js +++ b/test/pummel/test-fs-watch-file.js @@ -1,8 +1,8 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var path = require('path'); -var fs = require('fs'); +const common = require('../common'); +const assert = require('assert'); +const path = require('path'); +const fs = require('fs'); var watchSeenOne = 0; var watchSeenTwo = 0; diff --git a/test/pummel/test-fs-watch-non-recursive.js b/test/pummel/test-fs-watch-non-recursive.js index ead7de9e28dc47..7b40ef75accc43 100644 --- a/test/pummel/test-fs-watch-non-recursive.js +++ b/test/pummel/test-fs-watch-non-recursive.js @@ -1,7 +1,7 @@ 'use strict'; -var common = require('../common'); -var path = require('path'); -var fs = require('fs'); +const common = require('../common'); +const path = require('path'); +const fs = require('fs'); var testDir = common.tmpDir; var testsubdir = path.join(testDir, 'testsubdir'); diff --git a/test/pummel/test-http-many-keep-alive-connections.js b/test/pummel/test-http-many-keep-alive-connections.js index 293c6ab748e9c2..a7654f4524835c 100644 --- a/test/pummel/test-http-many-keep-alive-connections.js +++ b/test/pummel/test-http-many-keep-alive-connections.js @@ -1,7 +1,7 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); +const common = require('../common'); +const assert = require('assert'); +const http = require('http'); var expected = 10000; var responses = 0; diff --git a/test/pummel/test-https-ci-reneg-attack.js b/test/pummel/test-https-ci-reneg-attack.js index 8bda7cc10286e9..61e60c2673ed60 100644 --- a/test/pummel/test-https-ci-reneg-attack.js +++ b/test/pummel/test-https-ci-reneg-attack.js @@ -1,16 +1,16 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var spawn = require('child_process').spawn; +const common = require('../common'); +const assert = require('assert'); +const spawn = require('child_process').spawn; if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var tls = require('tls'); -var https = require('https'); +const tls = require('tls'); +const https = require('https'); -var fs = require('fs'); +const fs = require('fs'); if (!common.opensslCli) { common.skip('node compiled without OpenSSL CLI.'); diff --git a/test/pummel/test-https-large-response.js b/test/pummel/test-https-large-response.js index a122e47bc57a57..8a3aa022ea2089 100644 --- a/test/pummel/test-https-large-response.js +++ b/test/pummel/test-https-large-response.js @@ -1,14 +1,14 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); -var fs = require('fs'); +const fs = require('fs'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var https = require('https'); +const https = require('https'); var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), diff --git a/test/pummel/test-https-no-reader.js b/test/pummel/test-https-no-reader.js index fab59591993a69..b6cc32c999fa88 100644 --- a/test/pummel/test-https-no-reader.js +++ b/test/pummel/test-https-no-reader.js @@ -1,16 +1,16 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var https = require('https'); +const https = require('https'); -var Buffer = require('buffer').Buffer; -var fs = require('fs'); -var path = require('path'); +const Buffer = require('buffer').Buffer; +const fs = require('fs'); +const path = require('path'); var options = { key: fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')), diff --git a/test/pummel/test-keep-alive.js b/test/pummel/test-keep-alive.js index 47d529b64082fa..a9e91e201bb19b 100644 --- a/test/pummel/test-keep-alive.js +++ b/test/pummel/test-keep-alive.js @@ -1,11 +1,11 @@ 'use strict'; // This test requires the program 'wrk' -var common = require('../common'); -var assert = require('assert'); -var spawn = require('child_process').spawn; -var http = require('http'); -var url = require('url'); +const common = require('../common'); +const assert = require('assert'); +const spawn = require('child_process').spawn; +const http = require('http'); +const url = require('url'); if (common.isWindows) { common.skip('no `wrk` on windows'); diff --git a/test/pummel/test-net-connect-econnrefused.js b/test/pummel/test-net-connect-econnrefused.js index 2b6dc84f37195c..bd61dabc6bb6a7 100644 --- a/test/pummel/test-net-connect-econnrefused.js +++ b/test/pummel/test-net-connect-econnrefused.js @@ -1,9 +1,9 @@ 'use strict'; // verify that connect reqs are properly cleaned up -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); +const common = require('../common'); +const assert = require('assert'); +const net = require('net'); var ROUNDS = 10; var ATTEMPTS_PER_ROUND = 100; diff --git a/test/pummel/test-net-connect-memleak.js b/test/pummel/test-net-connect-memleak.js index 3b91a110eaa585..a5d8ff47eb7e16 100644 --- a/test/pummel/test-net-connect-memleak.js +++ b/test/pummel/test-net-connect-memleak.js @@ -1,9 +1,9 @@ 'use strict'; // Flags: --expose-gc -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); +const common = require('../common'); +const assert = require('assert'); +const net = require('net'); assert.strictEqual( typeof global.gc, diff --git a/test/pummel/test-net-many-clients.js b/test/pummel/test-net-many-clients.js index 52d05b35cbe2c4..db98e55433753e 100644 --- a/test/pummel/test-net-many-clients.js +++ b/test/pummel/test-net-many-clients.js @@ -1,7 +1,7 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); +const common = require('../common'); +const assert = require('assert'); +const net = require('net'); // settings var bytes = 1024 * 40; diff --git a/test/pummel/test-net-pause.js b/test/pummel/test-net-pause.js index b0c51260436e0c..59749e75fa4307 100644 --- a/test/pummel/test-net-pause.js +++ b/test/pummel/test-net-pause.js @@ -1,7 +1,7 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); +const common = require('../common'); +const assert = require('assert'); +const net = require('net'); var N = 200; var recv = '', chars_recved = 0; diff --git a/test/pummel/test-net-pingpong-delay.js b/test/pummel/test-net-pingpong-delay.js index c9cac778d59f4e..4e478c87a64132 100644 --- a/test/pummel/test-net-pingpong-delay.js +++ b/test/pummel/test-net-pingpong-delay.js @@ -1,7 +1,7 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); +const common = require('../common'); +const assert = require('assert'); +const net = require('net'); function pingPongTest(port, host, on_complete) { var N = 100; diff --git a/test/pummel/test-net-pingpong.js b/test/pummel/test-net-pingpong.js index 85dce02b6cf635..b65d5d4ff94224 100644 --- a/test/pummel/test-net-pingpong.js +++ b/test/pummel/test-net-pingpong.js @@ -1,7 +1,7 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); +const common = require('../common'); +const assert = require('assert'); +const net = require('net'); var tests_run = 0; diff --git a/test/pummel/test-net-timeout.js b/test/pummel/test-net-timeout.js index 415523763eef3c..e4f8664657505e 100644 --- a/test/pummel/test-net-timeout.js +++ b/test/pummel/test-net-timeout.js @@ -1,7 +1,7 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); +const common = require('../common'); +const assert = require('assert'); +const net = require('net'); var exchanges = 0; var starttime = null; diff --git a/test/pummel/test-net-timeout2.js b/test/pummel/test-net-timeout2.js index 7af47a47a8b634..5567b128c7697d 100644 --- a/test/pummel/test-net-timeout2.js +++ b/test/pummel/test-net-timeout2.js @@ -2,8 +2,8 @@ // socket.write was not resetting the timeout timer. See // https://github.com/joyent/node/issues/2002 -var common = require('../common'); -var net = require('net'); +const common = require('../common'); +const net = require('net'); var seconds = 5; var counter = 0; diff --git a/test/pummel/test-net-write-callbacks.js b/test/pummel/test-net-write-callbacks.js index 21eae0f5ab72d0..54f8a67abee3c6 100644 --- a/test/pummel/test-net-write-callbacks.js +++ b/test/pummel/test-net-write-callbacks.js @@ -1,7 +1,7 @@ 'use strict'; -var common = require('../common'); -var net = require('net'); -var assert = require('assert'); +const common = require('../common'); +const net = require('net'); +const assert = require('assert'); var cbcount = 0; var N = 500000; diff --git a/test/pummel/test-process-hrtime.js b/test/pummel/test-process-hrtime.js index 04225bae421b1a..0149ef2bf501cc 100644 --- a/test/pummel/test-process-hrtime.js +++ b/test/pummel/test-process-hrtime.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); var start = process.hrtime(); diff --git a/test/pummel/test-process-uptime.js b/test/pummel/test-process-uptime.js index 8d2d88b74f736f..90343e91a1e09a 100644 --- a/test/pummel/test-process-uptime.js +++ b/test/pummel/test-process-uptime.js @@ -1,6 +1,6 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); console.error(process.uptime()); assert.ok(process.uptime() <= 2); diff --git a/test/pummel/test-regress-GH-814.js b/test/pummel/test-regress-GH-814.js index 7bbd13dd196457..4633844ee1b65a 100644 --- a/test/pummel/test-regress-GH-814.js +++ b/test/pummel/test-regress-GH-814.js @@ -13,8 +13,8 @@ function newBuffer(size, value) { return buffer; } -var fs = require('fs'); -var testFileName = require('path').join(common.tmpDir, 'GH-814_testFile.txt'); +const fs = require('fs'); +const testFileName = require('path').join(common.tmpDir, 'GH-814_testFile.txt'); var testFileFD = fs.openSync(testFileName, 'w'); console.log(testFileName); @@ -25,7 +25,7 @@ var neverWrittenBuffer = newBuffer(kBufSize, 0x2e); //0x2e === '.' var bufPool = []; -var tail = require('child_process').spawn('tail', ['-f', testFileName]); +const tail = require('child_process').spawn('tail', ['-f', testFileName]); tail.stdout.on('data', tailCB); function tailCB(data) { diff --git a/test/pummel/test-regress-GH-814_2.js b/test/pummel/test-regress-GH-814_2.js index 7909a461f37956..31c18529856da9 100644 --- a/test/pummel/test-regress-GH-814_2.js +++ b/test/pummel/test-regress-GH-814_2.js @@ -1,15 +1,15 @@ 'use strict'; // Flags: --expose_gc -var common = require('../common'); +const common = require('../common'); -var fs = require('fs'); -var testFileName = require('path').join(common.tmpDir, 'GH-814_test.txt'); +const fs = require('fs'); +const testFileName = require('path').join(common.tmpDir, 'GH-814_test.txt'); var testFD = fs.openSync(testFileName, 'w'); console.error(testFileName + '\n'); -var tailProc = require('child_process').spawn('tail', ['-f', testFileName]); +const tailProc = require('child_process').spawn('tail', ['-f', testFileName]); tailProc.stdout.on('data', tailCB); function tailCB(data) { diff --git a/test/pummel/test-regress-GH-892.js b/test/pummel/test-regress-GH-892.js index 8bbf3c8f1a0ff4..9a2fce08a7fe3b 100644 --- a/test/pummel/test-regress-GH-892.js +++ b/test/pummel/test-regress-GH-892.js @@ -5,23 +5,24 @@ // to POST a 32mb file to us. A bug in the pause/resume functionality of the // TLS server causes the child process to exit cleanly before having sent // the entire buffer. -var common = require('../common'); -var assert = require('assert'); -var spawn = require('child_process').spawn; +const common = require('../common'); +const assert = require('assert'); +const spawn = require('child_process').spawn; if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var https = require('https'); +const https = require('https'); -var fs = require('fs'); +const fs = require('fs'); var bytesExpected = 1024 * 1024 * 32; var started = false; -var childScript = require('path').join(common.fixturesDir, 'GH-892-request.js'); +const childScript = require('path').join(common.fixturesDir, + 'GH-892-request.js'); function makeRequest() { if (started) return; diff --git a/test/pummel/test-stream-pipe-multi.js b/test/pummel/test-stream-pipe-multi.js index 897b9d6dc27d46..3c62548e5b81bb 100644 --- a/test/pummel/test-stream-pipe-multi.js +++ b/test/pummel/test-stream-pipe-multi.js @@ -3,8 +3,8 @@ // doesn't break anything. require('../common'); -var assert = require('assert'); -var Stream = require('stream').Stream; +const assert = require('assert'); +const Stream = require('stream').Stream; var rr = []; var ww = []; var cnt = 100; diff --git a/test/pummel/test-stream2-basic.js b/test/pummel/test-stream2-basic.js index 6bb2386b0b17dc..3659b267fad162 100644 --- a/test/pummel/test-stream2-basic.js +++ b/test/pummel/test-stream2-basic.js @@ -1,10 +1,10 @@ 'use strict'; require('../common'); -var R = require('_stream_readable'); -var assert = require('assert'); +const R = require('_stream_readable'); +const assert = require('assert'); -var util = require('util'); -var EE = require('events').EventEmitter; +const util = require('util'); +const EE = require('events').EventEmitter; function TestReader(n) { R.apply(this); diff --git a/test/pummel/test-timers.js b/test/pummel/test-timers.js index 588d2327ff37dd..83a8eeffeb43c3 100644 --- a/test/pummel/test-timers.js +++ b/test/pummel/test-timers.js @@ -1,6 +1,6 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); +const assert = require('assert'); var WINDOW = 200; // why is does this need to be so big? diff --git a/test/pummel/test-tls-ci-reneg-attack.js b/test/pummel/test-tls-ci-reneg-attack.js index 5075806c1085b6..c8f78e0609acc6 100644 --- a/test/pummel/test-tls-ci-reneg-attack.js +++ b/test/pummel/test-tls-ci-reneg-attack.js @@ -1,15 +1,15 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var spawn = require('child_process').spawn; +const common = require('../common'); +const assert = require('assert'); +const spawn = require('child_process').spawn; if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var tls = require('tls'); +const tls = require('tls'); -var fs = require('fs'); +const fs = require('fs'); if (!common.opensslCli) { common.skip('node compiled without OpenSSL CLI.'); diff --git a/test/pummel/test-tls-connect-memleak.js b/test/pummel/test-tls-connect-memleak.js index b55e33cee0afc4..46e7f425df5aba 100644 --- a/test/pummel/test-tls-connect-memleak.js +++ b/test/pummel/test-tls-connect-memleak.js @@ -1,16 +1,16 @@ 'use strict'; // Flags: --expose-gc -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var tls = require('tls'); +const tls = require('tls'); -var fs = require('fs'); +const fs = require('fs'); assert.strictEqual( typeof global.gc, diff --git a/test/pummel/test-tls-securepair-client.js b/test/pummel/test-tls-securepair-client.js index 7a1b8770132e96..c47cc60301380f 100644 --- a/test/pummel/test-tls-securepair-client.js +++ b/test/pummel/test-tls-securepair-client.js @@ -1,7 +1,7 @@ 'use strict'; // -var common = require('../common'); +const common = require('../common'); if (!common.opensslCli) { common.skip('node compiled without OpenSSL CLI.'); @@ -13,12 +13,12 @@ if (!common.hasCrypto) { return; } -var join = require('path').join; -var net = require('net'); -var assert = require('assert'); -var fs = require('fs'); -var tls = require('tls'); -var spawn = require('child_process').spawn; +const join = require('path').join; +const net = require('net'); +const assert = require('assert'); +const fs = require('fs'); +const tls = require('tls'); +const spawn = require('child_process').spawn; test1(); diff --git a/test/pummel/test-tls-server-large-request.js b/test/pummel/test-tls-server-large-request.js index 66d700ae4bc6a9..1b43a558353c0f 100644 --- a/test/pummel/test-tls-server-large-request.js +++ b/test/pummel/test-tls-server-large-request.js @@ -1,16 +1,16 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var tls = require('tls'); +const tls = require('tls'); -var fs = require('fs'); -var stream = require('stream'); -var util = require('util'); +const fs = require('fs'); +const stream = require('stream'); +const util = require('util'); var request = Buffer.from(new Array(1024 * 256).join('ABCD')); // 1mb diff --git a/test/pummel/test-tls-session-timeout.js b/test/pummel/test-tls-session-timeout.js index c23a8afcf7fe9a..ffa44a97025002 100644 --- a/test/pummel/test-tls-session-timeout.js +++ b/test/pummel/test-tls-session-timeout.js @@ -1,5 +1,5 @@ 'use strict'; -var common = require('../common'); +const common = require('../common'); if (!common.opensslCli) { common.skip('node compiled without OpenSSL CLI.'); @@ -22,11 +22,11 @@ doTest(); // that we used has expired by now. function doTest() { - var assert = require('assert'); - var tls = require('tls'); - var fs = require('fs'); - var join = require('path').join; - var spawn = require('child_process').spawn; + const assert = require('assert'); + const tls = require('tls'); + const fs = require('fs'); + const join = require('path').join; + const spawn = require('child_process').spawn; var SESSION_TIMEOUT = 1; diff --git a/test/pummel/test-tls-throttle.js b/test/pummel/test-tls-throttle.js index a93793989f0b2b..581355d61b701a 100644 --- a/test/pummel/test-tls-throttle.js +++ b/test/pummel/test-tls-throttle.js @@ -2,15 +2,15 @@ // Server sends a large string. Client counts bytes and pauses every few // seconds. Makes sure that pause and resume work properly. -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var tls = require('tls'); -var fs = require('fs'); +const tls = require('tls'); +const fs = require('fs'); process.stdout.write('build body...'); var body = 'hello world\n'.repeat(1024 * 1024); diff --git a/test/pummel/test-vm-memleak.js b/test/pummel/test-vm-memleak.js index c6623991922da9..6f26c9a590c54d 100644 --- a/test/pummel/test-vm-memleak.js +++ b/test/pummel/test-vm-memleak.js @@ -2,7 +2,7 @@ // Flags: --max_old_space_size=32 require('../common'); -var assert = require('assert'); +const assert = require('assert'); var start = Date.now(); var maxMem = 0; diff --git a/test/pummel/test-watch-file.js b/test/pummel/test-watch-file.js index 8b79ef8ede4a63..90909875d74a15 100644 --- a/test/pummel/test-watch-file.js +++ b/test/pummel/test-watch-file.js @@ -1,9 +1,9 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); -var fs = require('fs'); -var path = require('path'); +const fs = require('fs'); +const path = require('path'); const f = path.join(common.fixturesDir, 'x.txt'); diff --git a/test/sequential/test-child-process-execsync.js b/test/sequential/test-child-process-execsync.js index 137ddbda425f2c..91529ff94de3da 100644 --- a/test/sequential/test-child-process-execsync.js +++ b/test/sequential/test-child-process-execsync.js @@ -1,9 +1,9 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); -var execSync = require('child_process').execSync; -var execFileSync = require('child_process').execFileSync; +const execSync = require('child_process').execSync; +const execFileSync = require('child_process').execFileSync; var TIMER = 200; var SLEEP = 2000; diff --git a/test/sequential/test-debugger-debug-brk.js b/test/sequential/test-debugger-debug-brk.js index 3b54f853bc8de3..85ebe2ad17b53d 100644 --- a/test/sequential/test-debugger-debug-brk.js +++ b/test/sequential/test-debugger-debug-brk.js @@ -1,7 +1,7 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var spawn = require('child_process').spawn; +const common = require('../common'); +const assert = require('assert'); +const spawn = require('child_process').spawn; var script = common.fixturesDir + '/empty.js'; diff --git a/test/sequential/test-module-loading.js b/test/sequential/test-module-loading.js index 61746a282f5eaa..54fcc5c06a7ef4 100644 --- a/test/sequential/test-module-loading.js +++ b/test/sequential/test-module-loading.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var path = require('path'); -var fs = require('fs'); +const assert = require('assert'); +const path = require('path'); +const fs = require('fs'); console.error('load test-module-loading.js'); @@ -15,21 +15,21 @@ assert.strictEqual(process.mainModule, module, require('../fixtures/not-main-module.js'); // require a file with a request that includes the extension -var a_js = require('../fixtures/a.js'); +const a_js = require('../fixtures/a.js'); assert.strictEqual(42, a_js.number); // require a file without any extensions -var foo_no_ext = require('../fixtures/foo'); +const foo_no_ext = require('../fixtures/foo'); assert.strictEqual('ok', foo_no_ext.foo); -var a = require('../fixtures/a'); -var c = require('../fixtures/b/c'); -var d = require('../fixtures/b/d'); -var d2 = require('../fixtures/b/d'); +const a = require('../fixtures/a'); +const c = require('../fixtures/b/c'); +const d = require('../fixtures/b/d'); +const d2 = require('../fixtures/b/d'); // Absolute -var d3 = require(path.join(__dirname, '../fixtures/b/d')); +const d3 = require(path.join(__dirname, '../fixtures/b/d')); // Relative -var d4 = require('../fixtures/b/d'); +const d4 = require('../fixtures/b/d'); assert.strictEqual(false, false, 'testing the test program.'); @@ -96,7 +96,7 @@ require('../fixtures/node_modules/foo'); console.error('test name clashes'); // this one exists and should import the local module -var my_path = require('../fixtures/path'); +const my_path = require('../fixtures/path'); assert.ok(my_path.path_func instanceof Function); // this one does not exist and should throw assert.throws(function() { require('./utils'); }); @@ -175,13 +175,13 @@ assert.strictEqual(require(loadOrder + 'file9').file9, 'file9/index.reg2', msg); // make sure that module.require() is the same as // doing require() inside of that module. -var parent = require('../fixtures/module-require/parent/'); -var child = require('../fixtures/module-require/child/'); +const parent = require('../fixtures/module-require/parent/'); +const child = require('../fixtures/module-require/child/'); assert.strictEqual(child.loaded, parent.loaded); // #1357 Loading JSON files with require() -var json = require('../fixtures/packages/main/package.json'); +const json = require('../fixtures/packages/main/package.json'); assert.deepStrictEqual(json, { name: 'package-name', version: '1.2.3', diff --git a/test/sequential/test-net-GH-5504.js b/test/sequential/test-net-GH-5504.js index 3ebf9db548d4db..b40cfb400bf537 100644 --- a/test/sequential/test-net-GH-5504.js +++ b/test/sequential/test-net-GH-5504.js @@ -1,5 +1,5 @@ 'use strict'; -var common = require('../common'); +const common = require('../common'); // this test only fails with CentOS 6.3 using kernel version 2.6.32 // On other linuxes and darwin, the `read` call gets an ECONNRESET in @@ -18,7 +18,7 @@ switch (process.argv[2]) { } function server() { - var net = require('net'); + const net = require('net'); var content = Buffer.alloc(64 * 1024 * 1024, '#'); net.createServer(function(socket) { this.close(); @@ -35,7 +35,7 @@ function server() { } function client() { - var net = require('net'); + const net = require('net'); var client = net.connect({ host: common.localhostIPv4, port: common.PORT @@ -45,7 +45,7 @@ function client() { } function parent() { - var spawn = require('child_process').spawn; + const spawn = require('child_process').spawn; var node = process.execPath; var s = spawn(node, [__filename, 'server'], { diff --git a/test/sequential/test-regress-GH-1726.js b/test/sequential/test-regress-GH-1726.js index c5f0bba1335264..0097ed913dbd09 100644 --- a/test/sequential/test-regress-GH-1726.js +++ b/test/sequential/test-regress-GH-1726.js @@ -5,8 +5,8 @@ // https://github.com/joyent/node/issues/1726 require('../common'); -var assert = require('assert'); -var ch = require('child_process'); +const assert = require('assert'); +const ch = require('child_process'); var gen = +(process.argv[2] || 0); var maxGen = 5; diff --git a/test/sequential/test-regress-GH-4015.js b/test/sequential/test-regress-GH-4015.js index 7f0e03f9ac08e1..87b2b8561d9389 100644 --- a/test/sequential/test-regress-GH-4015.js +++ b/test/sequential/test-regress-GH-4015.js @@ -1,7 +1,7 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var exec = require('child_process').exec; +const common = require('../common'); +const assert = require('assert'); +const exec = require('child_process').exec; var cmd = '"' + process.execPath + '" ' + '"' + common.fixturesDir + '/test-regress-GH-4015.js"'; diff --git a/test/sequential/test-regress-GH-4027.js b/test/sequential/test-regress-GH-4027.js index aa1ec12c30f609..7653dda182fbe5 100644 --- a/test/sequential/test-regress-GH-4027.js +++ b/test/sequential/test-regress-GH-4027.js @@ -1,8 +1,8 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var path = require('path'); -var fs = require('fs'); +const common = require('../common'); +const assert = require('assert'); +const path = require('path'); +const fs = require('fs'); common.refreshTmpDir(); diff --git a/test/sequential/test-regress-GH-784.js b/test/sequential/test-regress-GH-784.js index 0c70337de7f146..645ffeb6501c37 100644 --- a/test/sequential/test-regress-GH-784.js +++ b/test/sequential/test-regress-GH-784.js @@ -7,9 +7,9 @@ // The next two are made with server on - they should come back successful. // The next two are made with the server off - and so on. Without the fix // we were experiencing parse errors and instead of ECONNREFUSED. -var common = require('../common'); -var http = require('http'); -var assert = require('assert'); +const common = require('../common'); +const http = require('http'); +const assert = require('assert'); var server = http.createServer(function(req, res) { diff --git a/test/sequential/test-regress-GH-877.js b/test/sequential/test-regress-GH-877.js index 5b0aac802e16a3..82229524ceaa9d 100644 --- a/test/sequential/test-regress-GH-877.js +++ b/test/sequential/test-regress-GH-877.js @@ -1,7 +1,7 @@ 'use strict'; -var common = require('../common'); -var http = require('http'); -var assert = require('assert'); +const common = require('../common'); +const http = require('http'); +const assert = require('assert'); var N = 20; var responses = 0; diff --git a/test/sequential/test-repl-timeout-throw.js b/test/sequential/test-repl-timeout-throw.js index 0188b3b8c502d8..344845e0202f1a 100644 --- a/test/sequential/test-repl-timeout-throw.js +++ b/test/sequential/test-repl-timeout-throw.js @@ -37,7 +37,7 @@ child.stdout.once('data', function() { function eeTest() { child.stdin.write('setTimeout(function() {\n' + - ' var events = require("events");\n' + + ' const events = require("events");\n' + ' var e = new events.EventEmitter;\n' + ' process.nextTick(function() {\n' + ' e.on("x", thrower);\n' + diff --git a/test/sequential/test-require-cache-without-stat.js b/test/sequential/test-require-cache-without-stat.js index 2571583f7690b5..0549e5f72ee0ba 100644 --- a/test/sequential/test-require-cache-without-stat.js +++ b/test/sequential/test-require-cache-without-stat.js @@ -2,9 +2,9 @@ // We've experienced a regression where the module loader stats a bunch of // directories on require() even if it's been called before. The require() // should caching the request. -var common = require('../common'); -var fs = require('fs'); -var assert = require('assert'); +const common = require('../common'); +const fs = require('fs'); +const assert = require('assert'); var counter = 0; diff --git a/test/sequential/test-stream2-fs.js b/test/sequential/test-stream2-fs.js index 7baba6e63b81b0..3640749179c539 100644 --- a/test/sequential/test-stream2-fs.js +++ b/test/sequential/test-stream2-fs.js @@ -1,19 +1,19 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); -var fs = require('fs'); +const fs = require('fs'); var FSReadable = fs.ReadStream; -var path = require('path'); +const path = require('path'); var file = path.resolve(common.fixturesDir, 'x1024.txt'); var size = fs.statSync(file).size; var expectLengths = [1024]; -var util = require('util'); -var Stream = require('stream'); +const util = require('util'); +const Stream = require('stream'); util.inherits(TestWriter, Stream); diff --git a/test/sequential/test-stream2-stderr-sync.js b/test/sequential/test-stream2-stderr-sync.js index c7daaa6b083205..2855a5f0970d41 100644 --- a/test/sequential/test-stream2-stderr-sync.js +++ b/test/sequential/test-stream2-stderr-sync.js @@ -4,8 +4,8 @@ require('../common'); function parent() { - var spawn = require('child_process').spawn; - var assert = require('assert'); + const spawn = require('child_process').spawn; + const assert = require('assert'); var i = 0; children.forEach(function(_, c) { var child = spawn(process.execPath, [__filename, '' + c]); @@ -42,7 +42,7 @@ function child1() { // using a net socket function child2() { - var net = require('net'); + const net = require('net'); var socket = new net.Socket({ fd: 2, readable: false, diff --git a/test/sequential/test-util-debug.js b/test/sequential/test-util-debug.js index 1159278efa475d..c0e15c1436084d 100644 --- a/test/sequential/test-util-debug.js +++ b/test/sequential/test-util-debug.js @@ -1,6 +1,6 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); +const assert = require('assert'); if (process.argv[2] === 'child') child(); @@ -24,7 +24,7 @@ function test(environ, shouldWrite) { } var expectOut = 'ok\n'; - var spawn = require('child_process').spawn; + const spawn = require('child_process').spawn; var child = spawn(process.execPath, [__filename, 'child'], { env: Object.assign(process.env, { NODE_DEBUG: environ }) }); @@ -53,7 +53,7 @@ function test(environ, shouldWrite) { function child() { - var util = require('util'); + const util = require('util'); var debug = util.debuglog('tud'); debug('this', { is: 'a' }, /debugging/); debug('number=%d string=%s obj=%j', 1234, 'asdf', { foo: 'bar' }); diff --git a/test/sequential/test-vm-timeout-rethrow.js b/test/sequential/test-vm-timeout-rethrow.js index f0f9c0b9c51063..d55a9b310c15a4 100644 --- a/test/sequential/test-vm-timeout-rethrow.js +++ b/test/sequential/test-vm-timeout-rethrow.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var vm = require('vm'); -var spawn = require('child_process').spawn; +const assert = require('assert'); +const vm = require('vm'); +const spawn = require('child_process').spawn; if (process.argv[2] === 'child') { var code = 'var j = 0;\n' + diff --git a/test/timers/test-timers-reliability.js b/test/timers/test-timers-reliability.js index 0626c45826781b..11dd0a225d9e7f 100644 --- a/test/timers/test-timers-reliability.js +++ b/test/timers/test-timers-reliability.js @@ -4,7 +4,7 @@ require('../common'); var Timer = process.binding('timer_wrap').Timer; -var assert = require('assert'); +const assert = require('assert'); var timerFired = false; var intervalFired = false; From eba9add48eabb9914596fc4b6b1cc522517722ae Mon Sep 17 00:00:00 2001 From: BethGriggs Date: Thu, 29 Dec 2016 10:28:10 +0000 Subject: [PATCH 177/291] test: refactor test-timer-close Refactor and simplify parallel/test-timer-close.js. Add comment to describe the test case. PR-URL: https://github.com/nodejs/node/pull/10517 Reviewed-By: Colin Ihrig Reviewed-By: Santiago Gimeno Reviewed-By: Jeremiah Senkpiel Reviewed-By: James M Snell Reviewed-By: Gibson Fahnestock --- test/parallel/test-timer-close.js | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) diff --git a/test/parallel/test-timer-close.js b/test/parallel/test-timer-close.js index 28217ce0397b0f..aae93f25c55ec0 100644 --- a/test/parallel/test-timer-close.js +++ b/test/parallel/test-timer-close.js @@ -1,16 +1,11 @@ 'use strict'; -require('../common'); -const assert = require('assert'); +const common = require('../common'); -var t = new (process.binding('timer_wrap').Timer)(); -var called = 0; -function onclose() { - called++; -} +// Make sure handle._handle.close(callback) is idempotent by closing a timer +// twice. The first function should be called, the second one should not. -t.close(onclose); -t.close(onclose); +const Timer = process.binding('timer_wrap').Timer; +const t = new Timer(); -process.on('exit', function() { - assert.equal(1, called); -}); +t.close(common.mustCall(function() {})); +t.close(() => common.fail('This should never be called')); From dba8d20ccc0086f1346712d462a8f6fe5fdc29c4 Mon Sep 17 00:00:00 2001 From: Adrian Estrada Date: Mon, 2 Jan 2017 22:22:29 -0500 Subject: [PATCH 178/291] test: improve the code in test-fs-read-stream * use const and let instead of var * use assert.strictEqual instead of assert.equal * use arrow functions PR-URL: https://github.com/nodejs/node/pull/10556 Reviewed-By: Rich Trott Reviewed-By: Evan Lucas Reviewed-By: Italo A. Casas Reviewed-By: Brian White --- test/parallel/test-fs-read-stream-fd.js | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/test/parallel/test-fs-read-stream-fd.js b/test/parallel/test-fs-read-stream-fd.js index 3ac432be32f375..a9ff56ee93fd91 100644 --- a/test/parallel/test-fs-read-stream-fd.js +++ b/test/parallel/test-fs-read-stream-fd.js @@ -3,21 +3,20 @@ const common = require('../common'); const fs = require('fs'); const assert = require('assert'); const path = require('path'); -var file = path.join(common.tmpDir, '/read_stream_fd_test.txt'); -var input = 'hello world'; -var output = ''; -var fd, stream; +const file = path.join(common.tmpDir, '/read_stream_fd_test.txt'); +const input = 'hello world'; +let output = ''; common.refreshTmpDir(); fs.writeFileSync(file, input); -fd = fs.openSync(file, 'r'); -stream = fs.createReadStream(null, { fd: fd, encoding: 'utf8' }); -stream.on('data', function(data) { +const fd = fs.openSync(file, 'r'); +const stream = fs.createReadStream(null, { fd: fd, encoding: 'utf8' }); + +stream.on('data', (data) => { output += data; }); -process.on('exit', function() { - fs.unlinkSync(file); - assert.equal(output, input); +process.on('exit', () => { + assert.strictEqual(output, input); }); From 0a2fb0d3e1072f99d0dc87d4e8ce11c7a7c80125 Mon Sep 17 00:00:00 2001 From: Beth Griggs Date: Thu, 29 Dec 2016 16:55:51 +0000 Subject: [PATCH 179/291] test: refactor several parallel/test-timer tests Change var to const/let. Simplify test-timers-uncaught-exception. PR-URL: https://github.com/nodejs/node/pull/10524 Reviewed-By: James M Snell Reviewed-By: Gibson Fahnestock Reviewed-By: Jeremiah Senkpiel --- test/parallel/test-timers-args.js | 6 +-- test/parallel/test-timers-immediate-queue.js | 12 +++--- .../parallel/test-timers-non-integer-delay.js | 12 +++--- test/parallel/test-timers-ordering.js | 14 +++---- .../test-timers-uncaught-exception.js | 38 ++++--------------- 5 files changed, 29 insertions(+), 53 deletions(-) diff --git a/test/parallel/test-timers-args.js b/test/parallel/test-timers-args.js index 4638cb39ccf6b9..1ba44d8bcf3664 100644 --- a/test/parallel/test-timers-args.js +++ b/test/parallel/test-timers-args.js @@ -7,7 +7,7 @@ function range(n) { } function timeout(nargs) { - var args = range(nargs); + const args = range(nargs); setTimeout.apply(null, [callback, 1].concat(args)); function callback() { @@ -17,8 +17,8 @@ function timeout(nargs) { } function interval(nargs) { - var args = range(nargs); - var timer = setTimeout.apply(null, [callback, 1].concat(args)); + const args = range(nargs); + const timer = setTimeout.apply(null, [callback, 1].concat(args)); function callback() { clearInterval(timer); diff --git a/test/parallel/test-timers-immediate-queue.js b/test/parallel/test-timers-immediate-queue.js index fd952301500af9..f53f18140f46df 100644 --- a/test/parallel/test-timers-immediate-queue.js +++ b/test/parallel/test-timers-immediate-queue.js @@ -6,15 +6,13 @@ const assert = require('assert'); // but immediates queued while processing the current queue should happen // on the next turn of the event loop. -// in v0.10 hit should be 1, because we only process one cb per turn -// in v0.11 and beyond it should be the exact same size of QUEUE -// if we're letting things recursively add to the immediate QUEUE hit will be -// > QUEUE +// hit should be the exact same size of QUEUE, if we're letting things +// recursively add to the immediate QUEUE hit will be > QUEUE -var ticked = false; +let ticked = false; -var hit = 0; -var QUEUE = 1000; +let hit = 0; +const QUEUE = 1000; function run() { if (hit === 0) diff --git a/test/parallel/test-timers-non-integer-delay.js b/test/parallel/test-timers-non-integer-delay.js index b42053db3b1895..cd7fa5e661dc81 100644 --- a/test/parallel/test-timers-non-integer-delay.js +++ b/test/parallel/test-timers-non-integer-delay.js @@ -1,4 +1,6 @@ 'use strict'; +require('../common'); + /* * This test makes sure that non-integer timer delays do not make the process * hang. See https://github.com/joyent/node/issues/8065 and @@ -15,13 +17,11 @@ * it 100%. */ -require('../common'); - -var TIMEOUT_DELAY = 1.1; -var NB_TIMEOUTS_FIRED = 50; +const TIMEOUT_DELAY = 1.1; +const NB_TIMEOUTS_FIRED = 50; -var nbTimeoutFired = 0; -var interval = setInterval(function() { +let nbTimeoutFired = 0; +const interval = setInterval(function() { ++nbTimeoutFired; if (nbTimeoutFired === NB_TIMEOUTS_FIRED) { clearInterval(interval); diff --git a/test/parallel/test-timers-ordering.js b/test/parallel/test-timers-ordering.js index 79b16338e65d79..853f80a66a2384 100644 --- a/test/parallel/test-timers-ordering.js +++ b/test/parallel/test-timers-ordering.js @@ -1,22 +1,22 @@ 'use strict'; require('../common'); const assert = require('assert'); -var Timer = process.binding('timer_wrap').Timer; -var N = 30; +const Timer = process.binding('timer_wrap').Timer; +const N = 30; -var last_i = 0; -var last_ts = 0; +let last_i = 0; +let last_ts = 0; -var f = function(i) { +const f = function(i) { if (i <= N) { // check order - assert.equal(i, last_i + 1, 'order is broken: ' + i + ' != ' + + assert.strictEqual(i, last_i + 1, 'order is broken: ' + i + ' != ' + last_i + ' + 1'); last_i = i; // check that this iteration is fired at least 1ms later than the previous - var now = Timer.now(); + const now = Timer.now(); console.log(i, now); assert(now >= last_ts + 1, 'current ts ' + now + ' < prev ts ' + last_ts + ' + 1'); diff --git a/test/parallel/test-timers-uncaught-exception.js b/test/parallel/test-timers-uncaught-exception.js index 84dae65af45c13..31a2d7eccd8105 100644 --- a/test/parallel/test-timers-uncaught-exception.js +++ b/test/parallel/test-timers-uncaught-exception.js @@ -1,40 +1,18 @@ 'use strict'; -require('../common'); +const common = require('../common'); const assert = require('assert'); - -var exceptions = 0; -var timer1 = 0; -var timer2 = 0; +const errorMsg = 'BAM!'; // the first timer throws... -console.error('set first timer'); -setTimeout(function() { - console.error('first timer'); - timer1++; - throw new Error('BAM!'); -}, 100); +setTimeout(common.mustCall(function() { + throw new Error(errorMsg); +}), 1); // ...but the second one should still run -console.error('set second timer'); -setTimeout(function() { - console.error('second timer'); - assert.equal(timer1, 1); - timer2++; -}, 100); +setTimeout(common.mustCall(function() {}), 1); function uncaughtException(err) { - console.error('uncaught handler'); - assert.equal(err.message, 'BAM!'); - exceptions++; + assert.strictEqual(err.message, errorMsg); } -process.on('uncaughtException', uncaughtException); -var exited = false; -process.on('exit', function() { - assert(!exited); - exited = true; - process.removeListener('uncaughtException', uncaughtException); - assert.equal(exceptions, 1); - assert.equal(timer1, 1); - assert.equal(timer2, 1); -}); +process.on('uncaughtException', common.mustCall(uncaughtException)); From af2bea70e0d2d942ea4de74757929333c66902c6 Mon Sep 17 00:00:00 2001 From: cjihrig Date: Mon, 2 Jan 2017 12:41:18 -0500 Subject: [PATCH 180/291] test: refactor test-beforeexit-event-exit.js PR-URL: https://github.com/nodejs/node/pull/10577 Reviewed-By: Italo A. Casas Reviewed-By: Gibson Fahnestock Reviewed-By: Sakthipriyan Vairamani Reviewed-By: James M Snell --- test/parallel/test-beforeexit-event-exit.js | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/test/parallel/test-beforeexit-event-exit.js b/test/parallel/test-beforeexit-event-exit.js index 6878135ce4d6d3..bd6162a46804bf 100644 --- a/test/parallel/test-beforeexit-event-exit.js +++ b/test/parallel/test-beforeexit-event-exit.js @@ -1,9 +1,8 @@ 'use strict'; -require('../common'); -const assert = require('assert'); +const common = require('../common'); process.on('beforeExit', function() { - assert(false, 'exit should not allow this to occur'); + common.fail('exit should not allow this to occur'); }); process.exit(); From 33851d1e2c333d869174a6342d02056ff2564310 Mon Sep 17 00:00:00 2001 From: "Sakthipriyan Vairamani (thefourtheye)" Date: Wed, 4 Jan 2017 00:54:27 +0530 Subject: [PATCH 181/291] test: fix process.title expectation `process.title` would work properly only in FreeBSD, OSX, and Linux as per test/parallel/test-setproctitle.js. This patch makes sure that the test expects an empty string in other platforms. This patch helps fix the SmartOS failures in https://ci.nodejs.org/job/node-test-commit/6962/ for https://github.com/nodejs/node/pull/10456 PR-URL: https://github.com/nodejs/node/pull/10597 Reviewed-By: James M Snell Reviewed-By: Benjamin Gruenbaum Reviewed-By: Rich Trott Reviewed-By: Evan Lucas --- test/debugger/test-debugger-repl.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/debugger/test-debugger-repl.js b/test/debugger/test-debugger-repl.js index 19060d9690c820..0725348e56e477 100644 --- a/test/debugger/test-debugger-repl.js +++ b/test/debugger/test-debugger-repl.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); const repl = require('./helper-debugger-repl.js'); repl.startDebugger('breakpoints.js'); @@ -57,7 +57,7 @@ addTest('c', [ // Execute addTest('exec process.title', [ - /node/ + common.isFreeBSD || common.isOSX || common.isLinux ? /node/ : '' ]); // Execute From db7b27abb9c4a211716424dac637bd2c36776fbb Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Mon, 2 Jan 2017 17:23:31 -0800 Subject: [PATCH 182/291] test: refactor beforeExit tests Combine and rename tests for the `beforeExit` event on `process`. The naming now more closely follows the de facto conventions of the project. The two tests were very similar and do not seem to benefit from being separate. PR-URL: https://github.com/nodejs/node/pull/10581 Reviewed-By: James M Snell Reviewed-By: Sakthipriyan Vairamani --- test/parallel/test-process-before-exit.js | 14 -------------- ...reexit-event.js => test-process-beforeexit.js} | 15 ++++++++++++++- 2 files changed, 14 insertions(+), 15 deletions(-) delete mode 100644 test/parallel/test-process-before-exit.js rename test/parallel/{test-beforeexit-event.js => test-process-beforeexit.js} (54%) diff --git a/test/parallel/test-process-before-exit.js b/test/parallel/test-process-before-exit.js deleted file mode 100644 index 01590de0fcf844..00000000000000 --- a/test/parallel/test-process-before-exit.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict'; -require('../common'); -const assert = require('assert'); - -var N = 5; -var n = 0; - -function f() { - if (++n < N) setTimeout(f, 5); -} -process.on('beforeExit', f); -process.on('exit', function() { - assert.equal(n, N + 1); // The sixth time we let it through. -}); diff --git a/test/parallel/test-beforeexit-event.js b/test/parallel/test-process-beforeexit.js similarity index 54% rename from test/parallel/test-beforeexit-event.js rename to test/parallel/test-process-beforeexit.js index ef94da76af3883..4557628c42b611 100644 --- a/test/parallel/test-beforeexit-event.js +++ b/test/parallel/test-process-beforeexit.js @@ -21,6 +21,19 @@ function tryListen() { .listen(0) .on('listening', common.mustCall(function() { this.close(); - process.on('beforeExit', common.mustCall(() => {})); + process.once('beforeExit', common.mustCall(tryRepeatedTimer)); })); } + +// test that a function invoked from the beforeExit handler can use a timer +// to keep the event loop open, which can use another timer to keep the event +// loop open, etc. +function tryRepeatedTimer() { + const N = 5; + let n = 0; + const repeatedTimer = common.mustCall(function() { + if (++n < N) + setTimeout(repeatedTimer, 1); + }, N); + setTimeout(repeatedTimer, 1); +} From b1c742e107f9a3da0b9e1cdbc1e042bb9365f649 Mon Sep 17 00:00:00 2001 From: Adrian Estrada Date: Mon, 2 Jan 2017 22:10:40 -0500 Subject: [PATCH 183/291] test: improve test-fs-access * use const and let instead of var * use common.mustCall to control functions execution * use assert.ifError instead of assert.strictEqual for errors * use arrow functions PR-URL: https://github.com/nodejs/node/pull/10542 Reviewed-By: James M Snell Reviewed-By: Colin Ihrig Reviewed-By: Luigi Pinca --- test/parallel/test-fs-access.js | 58 ++++++++++++++++----------------- 1 file changed, 29 insertions(+), 29 deletions(-) diff --git a/test/parallel/test-fs-access.js b/test/parallel/test-fs-access.js index 36268351fa16a2..e3346556cfb7d1 100644 --- a/test/parallel/test-fs-access.js +++ b/test/parallel/test-fs-access.js @@ -3,11 +3,11 @@ const common = require('../common'); const assert = require('assert'); const fs = require('fs'); const path = require('path'); -var doesNotExist = path.join(common.tmpDir, '__this_should_not_exist'); -var readOnlyFile = path.join(common.tmpDir, 'read_only_file'); -var readWriteFile = path.join(common.tmpDir, 'read_write_file'); +const doesNotExist = path.join(common.tmpDir, '__this_should_not_exist'); +const readOnlyFile = path.join(common.tmpDir, 'read_only_file'); +const readWriteFile = path.join(common.tmpDir, 'read_write_file'); -var removeFile = function(file) { +const removeFile = function(file) { try { fs.unlinkSync(file); } catch (err) { @@ -15,7 +15,7 @@ var removeFile = function(file) { } }; -var createFileWithPerms = function(file, mode) { +const createFileWithPerms = function(file, mode) { removeFile(file); fs.writeFileSync(file, ''); fs.chmodSync(file, mode); @@ -48,7 +48,7 @@ createFileWithPerms(readWriteFile, 0o666); * id, but that's fine. In this case, it is the responsability of the * continuous integration platform to take care of that. */ -var hasWriteAccessForReadonlyFile = false; +let hasWriteAccessForReadonlyFile = false; if (!common.isWindows && process.getuid() === 0) { hasWriteAccessForReadonlyFile = true; try { @@ -63,62 +63,62 @@ assert.strictEqual(typeof fs.R_OK, 'number'); assert.strictEqual(typeof fs.W_OK, 'number'); assert.strictEqual(typeof fs.X_OK, 'number'); -fs.access(__filename, function(err) { - assert.strictEqual(err, null, 'error should not exist'); -}); +fs.access(__filename, common.mustCall((err) => { + assert.ifError(err); +})); -fs.access(__filename, fs.R_OK, function(err) { - assert.strictEqual(err, null, 'error should not exist'); -}); +fs.access(__filename, fs.R_OK, common.mustCall((err) => { + assert.ifError(err); +})); -fs.access(doesNotExist, function(err) { +fs.access(doesNotExist, common.mustCall((err) => { assert.notEqual(err, null, 'error should exist'); assert.strictEqual(err.code, 'ENOENT'); assert.strictEqual(err.path, doesNotExist); -}); +})); -fs.access(readOnlyFile, fs.F_OK | fs.R_OK, function(err) { - assert.strictEqual(err, null, 'error should not exist'); -}); +fs.access(readOnlyFile, fs.F_OK | fs.R_OK, common.mustCall((err) => { + assert.ifError(err); +})); -fs.access(readOnlyFile, fs.W_OK, function(err) { +fs.access(readOnlyFile, fs.W_OK, common.mustCall((err) => { if (hasWriteAccessForReadonlyFile) { - assert.equal(err, null, 'error should not exist'); + assert.ifError(err); } else { assert.notEqual(err, null, 'error should exist'); assert.strictEqual(err.path, readOnlyFile); } -}); +})); -assert.throws(function() { - fs.access(100, fs.F_OK, function(err) {}); +assert.throws(() => { + fs.access(100, fs.F_OK, (err) => {}); }, /path must be a string or Buffer/); -assert.throws(function() { +assert.throws(() => { fs.access(__filename, fs.F_OK); }, /"callback" argument must be a function/); -assert.throws(function() { +assert.throws(() => { fs.access(__filename, fs.F_OK, {}); }, /"callback" argument must be a function/); -assert.doesNotThrow(function() { +assert.doesNotThrow(() => { fs.accessSync(__filename); }); -assert.doesNotThrow(function() { +assert.doesNotThrow(() => { var mode = fs.F_OK | fs.R_OK | fs.W_OK; fs.accessSync(readWriteFile, mode); }); -assert.throws(function() { +assert.throws(() => { fs.accessSync(doesNotExist); -}, function(err) { +}, (err) => { return err.code === 'ENOENT' && err.path === doesNotExist; }); -process.on('exit', function() { +process.on('exit', () => { removeFile(readOnlyFile); removeFile(readWriteFile); }); From 44174a52a6c848ab7796c2b57c87b94ef6dac2b4 Mon Sep 17 00:00:00 2001 From: sivaprasanna Date: Fri, 30 Dec 2016 11:01:03 +0530 Subject: [PATCH 184/291] test: refactor the code in test-util-debug.js * use const and let instead of var * use assert.strictEqual instead of assert.equal * use arrow functions * removed unwanted console log PR-URL: https://github.com/nodejs/node/pull/10531 Reviewed-By: Luigi Pinca Reviewed-By: Gibson Fahnestock Reviewed-By: Colin Ihrig Reviewed-By: James M Snell Reviewed-By: Sakthipriyan Vairamani --- test/sequential/test-util-debug.js | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/test/sequential/test-util-debug.js b/test/sequential/test-util-debug.js index c0e15c1436084d..08988997e735a6 100644 --- a/test/sequential/test-util-debug.js +++ b/test/sequential/test-util-debug.js @@ -17,44 +17,43 @@ function parent() { } function test(environ, shouldWrite) { - var expectErr = ''; + let expectErr = ''; if (shouldWrite) { expectErr = 'TUD %PID%: this { is: \'a\' } /debugging/\n' + 'TUD %PID%: number=1234 string=asdf obj={"foo":"bar"}\n'; } - var expectOut = 'ok\n'; + const expectOut = 'ok\n'; const spawn = require('child_process').spawn; - var child = spawn(process.execPath, [__filename, 'child'], { + const child = spawn(process.execPath, [__filename, 'child'], { env: Object.assign(process.env, { NODE_DEBUG: environ }) }); expectErr = expectErr.split('%PID%').join(child.pid); - var err = ''; + let err = ''; child.stderr.setEncoding('utf8'); - child.stderr.on('data', function(c) { + child.stderr.on('data', (c) => { err += c; }); - var out = ''; + let out = ''; child.stdout.setEncoding('utf8'); - child.stdout.on('data', function(c) { + child.stdout.on('data', (c) => { out += c; }); - child.on('close', common.mustCall(function(c) { + child.on('close', common.mustCall((c) => { assert(!c); - assert.equal(err, expectErr); - assert.equal(out, expectOut); - console.log('ok %j %j', environ, shouldWrite); + assert.strictEqual(err, expectErr); + assert.strictEqual(out, expectOut); })); } function child() { const util = require('util'); - var debug = util.debuglog('tud'); + const debug = util.debuglog('tud'); debug('this', { is: 'a' }, /debugging/); debug('number=%d string=%s obj=%j', 1234, 'asdf', { foo: 'bar' }); console.log('ok'); From 50130220dce8f699d0d3c76811fbdbbf8bc1ce4a Mon Sep 17 00:00:00 2001 From: cjihrig Date: Fri, 30 Dec 2016 10:09:13 -0500 Subject: [PATCH 185/291] test: s/assert.notEqual()/assert.notStrictEqual()/ PR-URL: https://github.com/nodejs/node/pull/10541 Reviewed-By: Sam Roberts Reviewed-By: Gibson Fahnestock Reviewed-By: James M Snell Reviewed-By: Rich Trott Reviewed-By: Italo A. Casas --- test/addons/load-long-path/test.js | 2 +- test/disabled/test-setuidgid.js | 4 +-- test/doctool/test-doctool-html.js | 2 +- test/fixtures/not-main-module.js | 6 ++--- .../test-child-process-spawn-shell.js | 2 +- .../test-child-process-spawnsync-shell.js | 2 +- test/parallel/test-console.js | 2 +- test/parallel/test-crypto-fips.js | 4 +-- test/parallel/test-crypto-hash.js | 6 ++--- ...n-throw-from-uncaught-exception-handler.js | 6 ++--- ...test-event-emitter-remove-all-listeners.js | 4 +-- test/parallel/test-fs-access.js | 4 +-- .../test-https-agent-disable-session-reuse.js | 4 +-- .../test-https-agent-session-reuse.js | 16 ++++++------ test/parallel/test-module-loading-error.js | 4 +-- test/parallel/test-net-keepalive.js | 2 +- .../test-net-listen-exclusive-random-ports.js | 2 +- test/parallel/test-net-remote-address-port.js | 26 +++++++++---------- test/parallel/test-process-cpuUsage.js | 2 +- test/parallel/test-regress-GH-7511.js | 2 +- test/parallel/test-regress-GH-node-9326.js | 2 +- ...ons-same-filename-as-dir-trailing-slash.js | 2 +- .../test-socket-write-after-fin-error.js | 2 +- ...emove-other-unref-timers-only-one-fires.js | 2 +- test/parallel/test-tls-handshake-error.js | 2 +- test/parallel/test-tls-set-ciphers.js | 2 +- ...est-whatwg-url-searchparams-constructor.js | 10 +++---- .../test-whatwg-url-searchparams-get.js | 2 +- test/parallel/test-zlib-sync-no-event.js | 2 +- 29 files changed, 64 insertions(+), 64 deletions(-) diff --git a/test/addons/load-long-path/test.js b/test/addons/load-long-path/test.js index 6e540fea559450..ea0783331b058f 100644 --- a/test/addons/load-long-path/test.js +++ b/test/addons/load-long-path/test.js @@ -33,5 +33,5 @@ fs.writeFileSync(addonDestinationPath, contents); // Attempt to load at long path destination const addon = require(addonDestinationPath); -assert.notEqual(addon, null); +assert.notStrictEqual(addon, null); assert.strictEqual(addon.hello(), 'world'); diff --git a/test/disabled/test-setuidgid.js b/test/disabled/test-setuidgid.js index 6b3b578f37991a..3603e9bb421a26 100644 --- a/test/disabled/test-setuidgid.js +++ b/test/disabled/test-setuidgid.js @@ -6,12 +6,12 @@ const assert = require('assert'); var oldgid = process.getgid(); process.setgid('nobody'); var newgid = process.getgid(); -assert.notEqual(newgid, oldgid, 'gids expected to be different'); +assert.notStrictEqual(newgid, oldgid, 'gids expected to be different'); var olduid = process.getuid(); process.setuid('nobody'); var newuid = process.getuid(); -assert.notEqual(newuid, olduid, 'uids expected to be different'); +assert.notStrictEqual(newuid, olduid, 'uids expected to be different'); try { process.setuid('nobody1234'); diff --git a/test/doctool/test-doctool-html.js b/test/doctool/test-doctool-html.js index 1745c8fea3df5c..e5c825aebbb32c 100644 --- a/test/doctool/test-doctool-html.js +++ b/test/doctool/test-doctool-html.js @@ -96,7 +96,7 @@ testData.forEach((item) => { const actual = output.replace(/\s/g, ''); // Assert that the input stripped of all whitespace contains the // expected list - assert.notEqual(actual.indexOf(expected), -1); + assert.notStrictEqual(actual.indexOf(expected), -1); })); })); })); diff --git a/test/fixtures/not-main-module.js b/test/fixtures/not-main-module.js index de024cd92ef942..4897a294eacb73 100644 --- a/test/fixtures/not-main-module.js +++ b/test/fixtures/not-main-module.js @@ -1,4 +1,4 @@ const assert = require('assert'); -assert.notEqual(module, require.main, 'require.main should not == module'); -assert.notEqual(module, process.mainModule, - 'process.mainModule should not === module'); +assert.notStrictEqual(module, require.main, 'require.main should not == module'); +assert.notStrictEqual(module, process.mainModule, + 'process.mainModule should not === module'); diff --git a/test/parallel/test-child-process-spawn-shell.js b/test/parallel/test-child-process-spawn-shell.js index 591fb409cb4cea..01411144bdc48f 100644 --- a/test/parallel/test-child-process-spawn-shell.js +++ b/test/parallel/test-child-process-spawn-shell.js @@ -6,7 +6,7 @@ const cp = require('child_process'); // Verify that a shell is, in fact, executed const doesNotExist = cp.spawn('does-not-exist', {shell: true}); -assert.notEqual(doesNotExist.spawnfile, 'does-not-exist'); +assert.notStrictEqual(doesNotExist.spawnfile, 'does-not-exist'); doesNotExist.on('error', common.fail); doesNotExist.on('exit', common.mustCall((code, signal) => { assert.strictEqual(signal, null); diff --git a/test/parallel/test-child-process-spawnsync-shell.js b/test/parallel/test-child-process-spawnsync-shell.js index fc42d56d105eaf..1d92767a8b5ba5 100644 --- a/test/parallel/test-child-process-spawnsync-shell.js +++ b/test/parallel/test-child-process-spawnsync-shell.js @@ -6,7 +6,7 @@ const cp = require('child_process'); // Verify that a shell is, in fact, executed const doesNotExist = cp.spawnSync('does-not-exist', {shell: true}); -assert.notEqual(doesNotExist.file, 'does-not-exist'); +assert.notStrictEqual(doesNotExist.file, 'does-not-exist'); assert.strictEqual(doesNotExist.error, undefined); assert.strictEqual(doesNotExist.signal, null); diff --git a/test/parallel/test-console.js b/test/parallel/test-console.js index ee7170bd9101ac..0eb7924cb6cbdc 100644 --- a/test/parallel/test-console.js +++ b/test/parallel/test-console.js @@ -115,7 +115,7 @@ assert.strictEqual("{ foo: 'bar', inspect: [Function: inspect] }\n", strings.shift()); assert.strictEqual("{ foo: 'bar', inspect: [Function: inspect] }\n", strings.shift()); -assert.notEqual(-1, strings.shift().indexOf('foo: [Object]')); +assert.ok(strings.shift().includes('foo: [Object]')); assert.strictEqual(-1, strings.shift().indexOf('baz')); assert.ok(/^label: \d+\.\d{3}ms$/.test(strings.shift().trim())); assert.ok(/^__proto__: \d+\.\d{3}ms$/.test(strings.shift().trim())); diff --git a/test/parallel/test-crypto-fips.js b/test/parallel/test-crypto-fips.js index 51ff8ef759850f..f27c59624730d2 100644 --- a/test/parallel/test-crypto-fips.js +++ b/test/parallel/test-crypto-fips.js @@ -47,10 +47,10 @@ function testHelper(stream, args, expectedOutput, cmd, env) { function responseHandler(buffer, expectedOutput) { const response = buffer.toString(); - assert.notEqual(0, response.length); + assert.notStrictEqual(response.length, 0); if (FIPS_ENABLED !== expectedOutput && FIPS_DISABLED !== expectedOutput) { // In the case of expected errors just look for a substring. - assert.notEqual(-1, response.indexOf(expectedOutput)); + assert.ok(response.includes(expectedOutput)); } else { // Normal path where we expect either FIPS enabled or disabled. assert.strictEqual(expectedOutput, Number(response)); diff --git a/test/parallel/test-crypto-hash.js b/test/parallel/test-crypto-hash.js index 473f01269db0a0..10135d2950c212 100644 --- a/test/parallel/test-crypto-hash.js +++ b/test/parallel/test-crypto-hash.js @@ -67,8 +67,8 @@ assert.deepStrictEqual( // stream interface should produce the same result. assert.deepStrictEqual(a5, a3, 'stream interface is consistent'); assert.deepStrictEqual(a6, a3, 'stream interface is consistent'); -assert.notEqual(a7, undefined, 'no data should return data'); -assert.notEqual(a8, undefined, 'empty string should generate data'); +assert.notStrictEqual(a7, undefined, 'no data should return data'); +assert.notStrictEqual(a8, undefined, 'empty string should generate data'); // Test multiple updates to same hash var h1 = crypto.createHash('sha1').update('Test123').digest('hex'); @@ -100,7 +100,7 @@ assert.strictEqual( '4b21bbd1a68e690a730ddcb5a8bc94ead9879ffe82580767ad7ec6fa8ba2dea6' + '43a821af66afa9a45b6a78c712fecf0e56dc7f43aef4bcfc8eb5b4d8dca6ea5b'); -assert.notEqual( +assert.notStrictEqual( hutf8, crypto.createHash('sha512').update('УТФ-8 text', 'latin1').digest('hex')); diff --git a/test/parallel/test-domain-throw-error-then-throw-from-uncaught-exception-handler.js b/test/parallel/test-domain-throw-error-then-throw-from-uncaught-exception-handler.js index a45f7d17a83a2c..d2277cfc0f74b7 100644 --- a/test/parallel/test-domain-throw-error-then-throw-from-uncaught-exception-handler.js +++ b/test/parallel/test-domain-throw-error-then-throw-from-uncaught-exception-handler.js @@ -72,9 +72,9 @@ function runTestWithAbortOnUncaughtException() { child_process.exec(createTestCmdLine({ withAbortOnUncaughtException: true }), function onTestDone(err, stdout, stderr) { - assert.notEqual(err.code, RAN_UNCAUGHT_EXCEPTION_HANDLER_EXIT_CODE, - 'child process should not have run its uncaughtException ' + - 'event handler'); + assert.notStrictEqual(err.code, RAN_UNCAUGHT_EXCEPTION_HANDLER_EXIT_CODE, + 'child process should not have run its ' + + 'uncaughtException event handler'); assert(common.nodeProcessAborted(err.code, err.signal), 'process should have aborted, but did not'); }); diff --git a/test/parallel/test-event-emitter-remove-all-listeners.js b/test/parallel/test-event-emitter-remove-all-listeners.js index e32a0e3f94f5b4..076c1ea1d7b80f 100644 --- a/test/parallel/test-event-emitter-remove-all-listeners.js +++ b/test/parallel/test-event-emitter-remove-all-listeners.js @@ -39,8 +39,8 @@ function listener() {} assert.deepStrictEqual(bazListeners, [listener, listener]); // After calling removeAllListeners(), // new listeners arrays is different from the old. - assert.notEqual(ee.listeners('bar'), barListeners); - assert.notEqual(ee.listeners('baz'), bazListeners); + assert.notStrictEqual(ee.listeners('bar'), barListeners); + assert.notStrictEqual(ee.listeners('baz'), bazListeners); } { diff --git a/test/parallel/test-fs-access.js b/test/parallel/test-fs-access.js index e3346556cfb7d1..a74ad9dccec271 100644 --- a/test/parallel/test-fs-access.js +++ b/test/parallel/test-fs-access.js @@ -72,7 +72,7 @@ fs.access(__filename, fs.R_OK, common.mustCall((err) => { })); fs.access(doesNotExist, common.mustCall((err) => { - assert.notEqual(err, null, 'error should exist'); + assert.notStrictEqual(err, null, 'error should exist'); assert.strictEqual(err.code, 'ENOENT'); assert.strictEqual(err.path, doesNotExist); })); @@ -85,7 +85,7 @@ fs.access(readOnlyFile, fs.W_OK, common.mustCall((err) => { if (hasWriteAccessForReadonlyFile) { assert.ifError(err); } else { - assert.notEqual(err, null, 'error should exist'); + assert.notStrictEqual(err, null, 'error should exist'); assert.strictEqual(err.path, readOnlyFile); } })); diff --git a/test/parallel/test-https-agent-disable-session-reuse.js b/test/parallel/test-https-agent-disable-session-reuse.js index dc9878d4a1c1ed..2f59118e3673ea 100644 --- a/test/parallel/test-https-agent-disable-session-reuse.js +++ b/test/parallel/test-https-agent-disable-session-reuse.js @@ -54,6 +54,6 @@ const server = https.createServer(options, function(req, res) { process.on('exit', function() { assert.equal(serverRequests, TOTAL_REQS); assert.equal(clientSessions.length, TOTAL_REQS); - assert.notEqual(clientSessions[0].toString('hex'), - clientSessions[1].toString('hex')); + assert.notStrictEqual(clientSessions[0].toString('hex'), + clientSessions[1].toString('hex')); }); diff --git a/test/parallel/test-https-agent-session-reuse.js b/test/parallel/test-https-agent-session-reuse.js index 73465aa5a98fb9..3f06d1699f2cde 100644 --- a/test/parallel/test-https-agent-session-reuse.js +++ b/test/parallel/test-https-agent-session-reuse.js @@ -117,14 +117,14 @@ process.on('exit', function() { assert.strictEqual(serverRequests, 6); assert.strictEqual(clientSessions['first'].toString('hex'), clientSessions['first-reuse'].toString('hex')); - assert.notEqual(clientSessions['first'].toString('hex'), - clientSessions['cipher-change'].toString('hex')); - assert.notEqual(clientSessions['first'].toString('hex'), - clientSessions['before-drop'].toString('hex')); - assert.notEqual(clientSessions['cipher-change'].toString('hex'), - clientSessions['before-drop'].toString('hex')); - assert.notEqual(clientSessions['before-drop'].toString('hex'), - clientSessions['after-drop'].toString('hex')); + assert.notStrictEqual(clientSessions['first'].toString('hex'), + clientSessions['cipher-change'].toString('hex')); + assert.notStrictEqual(clientSessions['first'].toString('hex'), + clientSessions['before-drop'].toString('hex')); + assert.notStrictEqual(clientSessions['cipher-change'].toString('hex'), + clientSessions['before-drop'].toString('hex')); + assert.notStrictEqual(clientSessions['before-drop'].toString('hex'), + clientSessions['after-drop'].toString('hex')); assert.strictEqual(clientSessions['after-drop'].toString('hex'), clientSessions['after-drop-reuse'].toString('hex')); }); diff --git a/test/parallel/test-module-loading-error.js b/test/parallel/test-module-loading-error.js index 1958fe65242221..b8454f2ae9ffb0 100644 --- a/test/parallel/test-module-loading-error.js +++ b/test/parallel/test-module-loading-error.js @@ -28,11 +28,11 @@ try { try { require(); } catch (e) { - assert.notEqual(e.toString().indexOf('missing path'), -1); + assert.ok(e.toString().includes('missing path')); } try { require({}); } catch (e) { - assert.notEqual(e.toString().indexOf('path must be a string'), -1); + assert.ok(e.toString().includes('path must be a string')); } diff --git a/test/parallel/test-net-keepalive.js b/test/parallel/test-net-keepalive.js index e466f0ff580d06..8b6998fa831a78 100644 --- a/test/parallel/test-net-keepalive.js +++ b/test/parallel/test-net-keepalive.js @@ -16,7 +16,7 @@ var echoServer = net.createServer(function(connection) { echoServer.close(); }, 1), common.platformTimeout(100)); connection.setTimeout(0); - assert.notEqual(connection.setKeepAlive, undefined); + assert.notStrictEqual(connection.setKeepAlive, undefined); // send a keepalive packet after 50 ms connection.setKeepAlive(true, common.platformTimeout(50)); connection.on('end', function() { diff --git a/test/parallel/test-net-listen-exclusive-random-ports.js b/test/parallel/test-net-listen-exclusive-random-ports.js index 4c5d056d9dfe54..974af6aaa60438 100644 --- a/test/parallel/test-net-listen-exclusive-random-ports.js +++ b/test/parallel/test-net-listen-exclusive-random-ports.js @@ -15,7 +15,7 @@ if (cluster.isMaster) { worker2.on('message', function(port2) { assert.equal(port2, port2 | 0, 'second worker could not listen'); - assert.notEqual(port1, port2, 'ports should not be equal'); + assert.notStrictEqual(port1, port2, 'ports should not be equal'); worker1.kill(); worker2.kill(); }); diff --git a/test/parallel/test-net-remote-address-port.js b/test/parallel/test-net-remote-address-port.js index 62a7ebfe572908..9cdf4ff7f876b8 100644 --- a/test/parallel/test-net-remote-address-port.js +++ b/test/parallel/test-net-remote-address-port.js @@ -13,16 +13,16 @@ var remoteFamilyCandidates = ['IPv4']; if (common.hasIPv6) remoteFamilyCandidates.push('IPv6'); var server = net.createServer(common.mustCall(function(socket) { - assert.notEqual(-1, remoteAddrCandidates.indexOf(socket.remoteAddress)); - assert.notEqual(-1, remoteFamilyCandidates.indexOf(socket.remoteFamily)); + assert.ok(remoteAddrCandidates.includes(socket.remoteAddress)); + assert.ok(remoteFamilyCandidates.includes(socket.remoteFamily)); assert.ok(socket.remotePort); - assert.notEqual(socket.remotePort, this.address().port); + assert.notStrictEqual(socket.remotePort, this.address().port); socket.on('end', function() { if (++conns_closed === 2) server.close(); }); socket.on('close', function() { - assert.notEqual(-1, remoteAddrCandidates.indexOf(socket.remoteAddress)); - assert.notEqual(-1, remoteFamilyCandidates.indexOf(socket.remoteFamily)); + assert.ok(remoteAddrCandidates.includes(socket.remoteAddress)); + assert.ok(remoteFamilyCandidates.includes(socket.remoteFamily)); }); socket.resume(); }, 2)); @@ -31,23 +31,23 @@ server.listen(0, 'localhost', function() { var client = net.createConnection(this.address().port, 'localhost'); var client2 = net.createConnection(this.address().port); client.on('connect', function() { - assert.notEqual(-1, remoteAddrCandidates.indexOf(client.remoteAddress)); - assert.notEqual(-1, remoteFamilyCandidates.indexOf(client.remoteFamily)); + assert.ok(remoteAddrCandidates.includes(client.remoteAddress)); + assert.ok(remoteFamilyCandidates.includes(client.remoteFamily)); assert.strictEqual(client.remotePort, server.address().port); client.end(); }); client.on('close', function() { - assert.notEqual(-1, remoteAddrCandidates.indexOf(client.remoteAddress)); - assert.notEqual(-1, remoteFamilyCandidates.indexOf(client.remoteFamily)); + assert.ok(remoteAddrCandidates.includes(client.remoteAddress)); + assert.ok(remoteFamilyCandidates.includes(client.remoteFamily)); }); client2.on('connect', function() { - assert.notEqual(-1, remoteAddrCandidates.indexOf(client2.remoteAddress)); - assert.notEqual(-1, remoteFamilyCandidates.indexOf(client2.remoteFamily)); + assert.ok(remoteAddrCandidates.includes(client2.remoteAddress)); + assert.ok(remoteFamilyCandidates.includes(client2.remoteFamily)); assert.strictEqual(client2.remotePort, server.address().port); client2.end(); }); client2.on('close', function() { - assert.notEqual(-1, remoteAddrCandidates.indexOf(client2.remoteAddress)); - assert.notEqual(-1, remoteFamilyCandidates.indexOf(client2.remoteFamily)); + assert.ok(remoteAddrCandidates.includes(client2.remoteAddress)); + assert.ok(remoteFamilyCandidates.includes(client2.remoteFamily)); }); }); diff --git a/test/parallel/test-process-cpuUsage.js b/test/parallel/test-process-cpuUsage.js index 0c553c576a1f25..062dac31cf7b5e 100644 --- a/test/parallel/test-process-cpuUsage.js +++ b/test/parallel/test-process-cpuUsage.js @@ -87,7 +87,7 @@ assert.throws(() => { // Ensure that the return value is the expected shape. function validateResult(result) { - assert.notEqual(result, null); + assert.notStrictEqual(result, null); assert(Number.isFinite(result.user)); assert(Number.isFinite(result.system)); diff --git a/test/parallel/test-regress-GH-7511.js b/test/parallel/test-regress-GH-7511.js index d18a3ae02c0d03..97e2fdb8114193 100644 --- a/test/parallel/test-regress-GH-7511.js +++ b/test/parallel/test-regress-GH-7511.js @@ -6,5 +6,5 @@ const vm = require('vm'); assert.doesNotThrow(function() { var context = vm.createContext({ process: process }); var result = vm.runInContext('process.env["PATH"]', context); - assert.notEqual(undefined, result); + assert.notStrictEqual(undefined, result); }); diff --git a/test/parallel/test-regress-GH-node-9326.js b/test/parallel/test-regress-GH-node-9326.js index 920a24e3a12c9a..3dbbe2958b8aef 100644 --- a/test/parallel/test-regress-GH-node-9326.js +++ b/test/parallel/test-regress-GH-node-9326.js @@ -10,5 +10,5 @@ var cp = child_process.spawn(process.execPath, [ ]); cp.on('exit', function(code) { - assert.notEqual(code, 0); + assert.notStrictEqual(code, 0); }); diff --git a/test/parallel/test-require-extensions-same-filename-as-dir-trailing-slash.js b/test/parallel/test-require-extensions-same-filename-as-dir-trailing-slash.js index 0a80a860388de9..aa749591eb553a 100644 --- a/test/parallel/test-require-extensions-same-filename-as-dir-trailing-slash.js +++ b/test/parallel/test-require-extensions-same-filename-as-dir-trailing-slash.js @@ -6,5 +6,5 @@ const assert = require('assert'); const content = require(common.fixturesDir + '/json-with-directory-name-module/module-stub/one-trailing-slash/two/three.js'); -assert.notEqual(content.rocko, 'artischocko'); +assert.notStrictEqual(content.rocko, 'artischocko'); assert.equal(content, 'hello from module-stub!'); diff --git a/test/parallel/test-socket-write-after-fin-error.js b/test/parallel/test-socket-write-after-fin-error.js index 8ceb0c65585750..0d280115a43653 100644 --- a/test/parallel/test-socket-write-after-fin-error.js +++ b/test/parallel/test-socket-write-after-fin-error.js @@ -49,7 +49,7 @@ server.listen(0, function() { assert(gotServerEnd); assert(gotServerError); assert.equal(gotServerError.code, 'EPIPE'); - assert.notEqual(gotServerError.message, 'write after end'); + assert.notStrictEqual(gotServerError.message, 'write after end'); console.log('ok'); }); diff --git a/test/parallel/test-timers-unref-remove-other-unref-timers-only-one-fires.js b/test/parallel/test-timers-unref-remove-other-unref-timers-only-one-fires.js index 971c485a4cf986..03c6cf7fd333a7 100644 --- a/test/parallel/test-timers-unref-remove-other-unref-timers-only-one-fires.js +++ b/test/parallel/test-timers-unref-remove-other-unref-timers-only-one-fires.js @@ -37,5 +37,5 @@ timers.enroll(foo, 1); timers._unrefActive(foo); setTimeout(function() { - assert.notEqual(nbTimersFired, 2); + assert.notStrictEqual(nbTimersFired, 2); }, 20); diff --git a/test/parallel/test-tls-handshake-error.js b/test/parallel/test-tls-handshake-error.js index 4d6a64a150c707..7623f816f3be07 100644 --- a/test/parallel/test-tls-handshake-error.js +++ b/test/parallel/test-tls-handshake-error.js @@ -25,7 +25,7 @@ var server = tls.createServer({ }); c.on('error', common.mustCall(function(err) { - assert.notEqual(err.code, 'ECONNRESET'); + assert.notStrictEqual(err.code, 'ECONNRESET'); })); c.on('close', common.mustCall(function(err) { diff --git a/test/parallel/test-tls-set-ciphers.js b/test/parallel/test-tls-set-ciphers.js index e61f8448be2923..ef08c56460c10d 100644 --- a/test/parallel/test-tls-set-ciphers.js +++ b/test/parallel/test-tls-set-ciphers.js @@ -26,7 +26,7 @@ const reply = 'I AM THE WALRUS'; // something recognizable let response = ''; process.on('exit', function() { - assert.notEqual(response.indexOf(reply), -1); + assert.ok(response.includes(reply)); }); const server = tls.createServer(options, common.mustCall(function(conn) { diff --git a/test/parallel/test-whatwg-url-searchparams-constructor.js b/test/parallel/test-whatwg-url-searchparams-constructor.js index 0b42eca5032d53..9b7ca1e4e9c54a 100644 --- a/test/parallel/test-whatwg-url-searchparams-constructor.js +++ b/test/parallel/test-whatwg-url-searchparams-constructor.js @@ -26,7 +26,7 @@ assert.throws(() => { }); }, TypeError); params = new URLSearchParams(''); -assert.notEqual(params, null, 'constructor returned non-null value.'); +assert.notStrictEqual(params, null, 'constructor returned non-null value.'); // eslint-disable-next-line no-proto assert.strictEqual(params.__proto__, URLSearchParams.prototype, 'expected URLSearchParams.prototype as prototype.'); @@ -36,19 +36,19 @@ assert.strictEqual(params + '', '%5Bobject%20Object%5D='); // URLSearchParams constructor, string. params = new URLSearchParams('a=b'); -assert.notEqual(params, null, 'constructor returned non-null value.'); +assert.notStrictEqual(params, null, 'constructor returned non-null value.'); assert.strictEqual(true, params.has('a'), 'Search params object has name "a"'); assert.strictEqual(false, params.has('b'), 'Search params object has not got name "b"'); params = new URLSearchParams('a=b&c'); -assert.notEqual(params, null, 'constructor returned non-null value.'); +assert.notStrictEqual(params, null, 'constructor returned non-null value.'); assert.strictEqual(true, params.has('a'), 'Search params object has name "a"'); assert.strictEqual(true, params.has('c'), 'Search params object has name "c"'); params = new URLSearchParams('&a&&& &&&&&a+b=& c&m%c3%b8%c3%b8'); -assert.notEqual(params, null, 'constructor returned non-null value.'); +assert.notStrictEqual(params, null, 'constructor returned non-null value.'); assert.strictEqual(true, params.has('a'), 'Search params object has name "a"'); assert.strictEqual(true, params.has('a b'), 'Search params object has name "a b"'); @@ -64,7 +64,7 @@ assert.strictEqual(true, params.has('møø'), // URLSearchParams constructor, object. const seed = new URLSearchParams('a=b&c=d'); params = new URLSearchParams(seed); -assert.notEqual(params, null, 'constructor returned non-null value.'); +assert.notStrictEqual(params, null, 'constructor returned non-null value.'); assert.strictEqual(params.get('a'), 'b'); assert.strictEqual(params.get('c'), 'd'); assert.strictEqual(false, params.has('d')); diff --git a/test/parallel/test-whatwg-url-searchparams-get.js b/test/parallel/test-whatwg-url-searchparams-get.js index aa3a0d9929bf52..7ddfb67e8b8a7b 100644 --- a/test/parallel/test-whatwg-url-searchparams-get.js +++ b/test/parallel/test-whatwg-url-searchparams-get.js @@ -20,7 +20,7 @@ assert.strictEqual(params.get('a'), ''); // More get() basics params = new URLSearchParams('first=second&third&&'); -assert.notEqual(params, null, 'constructor returned non-null value.'); +assert.notStrictEqual(params, null, 'constructor returned non-null value.'); assert.strictEqual(true, params.has('first'), 'Search params object has name "first"'); assert.strictEqual(params.get('first'), 'second', diff --git a/test/parallel/test-zlib-sync-no-event.js b/test/parallel/test-zlib-sync-no-event.js index 46ea97fbf4dd83..d6eb1f3c9df6a3 100644 --- a/test/parallel/test-zlib-sync-no-event.js +++ b/test/parallel/test-zlib-sync-no-event.js @@ -17,5 +17,5 @@ const unzipper = new zlib.Gunzip(); unzipper.on('close', shouldNotBeCalled); const unzipped = unzipper._processChunk(zipped, zlib.constants.Z_FINISH); -assert.notEqual(zipped.toString(), message); +assert.notStrictEqual(zipped.toString(), message); assert.strictEqual(unzipped.toString(), message); From 1c4bf9e8ffb228230a739d908e1e94682c32acc6 Mon Sep 17 00:00:00 2001 From: "Steven R. Loomis" Date: Thu, 29 Dec 2016 16:57:33 -0800 Subject: [PATCH 186/291] deps: cherry-pick 2f5da9a from V8 upstream MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Original commit message: Fix the uppercasing of U+00E7(ç) and U+00F7(÷) Due to a typo in runtime-i18n.js, 'ç'(U+00E7) was not uppercased while '÷'(U+00F7) was incorrectly uppercased to '×'(U+00D7). Add a comprehensive test for Latin-1 supplemental block (U+00A0 ~ U+00FF). (they're special-cased for speed-up and needs to have a test for the range.). TEST=intl/general/case-mapping BUG=v8:5681 Review-Url: https://codereview.chromium.org/2533033003 Cr-Commit-Position: refs/heads/master@{#41331} PR-URL: https://github.com/nodejs/node/pull/9828 Fixes: https://github.com/nodejs/node/issues/9785 Reviewed-By: James M Snell Reviewed-By: Ali Ijaz Sheikh Reviewed-By: Myles Borins --- deps/v8/include/v8-version.h | 2 +- deps/v8/src/runtime/runtime-i18n.cc | 2 +- deps/v8/test/intl/general/case-mapping.js | 26 +++++++++++++++++++++++ 3 files changed, 28 insertions(+), 2 deletions(-) diff --git a/deps/v8/include/v8-version.h b/deps/v8/include/v8-version.h index b383f39b6a766e..bb16d9543b8564 100644 --- a/deps/v8/include/v8-version.h +++ b/deps/v8/include/v8-version.h @@ -11,7 +11,7 @@ #define V8_MAJOR_VERSION 5 #define V8_MINOR_VERSION 4 #define V8_BUILD_NUMBER 500 -#define V8_PATCH_LEVEL 47 +#define V8_PATCH_LEVEL 48 // Use 1 for candidates and 0 otherwise. // (Boolean macro values are not supported by all preprocessors.) diff --git a/deps/v8/src/runtime/runtime-i18n.cc b/deps/v8/src/runtime/runtime-i18n.cc index 8b9d92ec006eb5..c5577dadaf651f 100644 --- a/deps/v8/src/runtime/runtime-i18n.cc +++ b/deps/v8/src/runtime/runtime-i18n.cc @@ -931,7 +931,7 @@ inline uint16_t ToASCIIUpper(uint16_t ch) { inline uint16_t ToLatin1Upper(uint16_t ch) { DCHECK(ch != 0xDF && ch != 0xB5 && ch != 0xFF); return ch & - ~(((ch >= 'a' && ch <= 'z') || (((ch & 0xE0) == 0xE0) && ch != 0xE7)) + ~(((ch >= 'a' && ch <= 'z') || (((ch & 0xE0) == 0xE0) && ch != 0xF7)) << 5); } diff --git a/deps/v8/test/intl/general/case-mapping.js b/deps/v8/test/intl/general/case-mapping.js index a73622bf0deb9c..17eb5bae57bf02 100644 --- a/deps/v8/test/intl/general/case-mapping.js +++ b/deps/v8/test/intl/general/case-mapping.js @@ -136,3 +136,29 @@ assertEquals("\u{10CC0}", "\u{10C80}".toLocaleLowerCase()); assertEquals("\u{10C80}", "\u{10CC0}".toLocaleUpperCase(["tr"])); assertEquals("\u{10C80}", "\u{10CC0}".toLocaleUpperCase(["tr"])); assertEquals("\u{10CC0}", "\u{10C80}".toLocaleLowerCase()); + +// check fast path for Latin-1 supplement (U+00A0 ~ U+00FF) +var latin1Suppl = "\u00A0¡¢£¤¥¦§¨©ª«¬\u00AD®°±²³´µ¶·¸¹º»¼½¾¿" + + "ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ"; +var latin1SupplLowercased = "\u00A0¡¢£¤¥¦§¨©ª«¬\u00AD®°±²³´µ¶·¸¹º»¼½¾¿" + + "àáâãäåæçèéêëìíîïðñòóôõö×øùúûüýþßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ"; +var latin1SupplUppercased = "\u00A0¡¢£¤¥¦§¨©ª«¬\u00AD®°±²³´\u039C¶·¸¹º»¼½¾¿" + + "ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞSSÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ÷ØÙÚÛÜÝÞ\u0178"; + +assertEquals(latin1SupplLowercased, latin1Suppl.toLowerCase()); +assertEquals(latin1SupplUppercased, latin1Suppl.toUpperCase()); +assertEquals(latin1SupplLowercased, latin1Suppl.toLocaleLowerCase("de")); +assertEquals(latin1SupplUppercased, latin1Suppl.toLocaleUpperCase("de")); +assertEquals(latin1SupplLowercased, latin1Suppl.toLocaleLowerCase("el")); +assertEquals(latin1SupplUppercased, latin1Suppl.toLocaleUpperCase("el")); +assertEquals(latin1SupplUppercased, latin1Suppl.toLocaleUpperCase("tr")); +assertEquals(latin1SupplLowercased, latin1Suppl.toLocaleLowerCase("tr")); +assertEquals(latin1SupplUppercased, latin1Suppl.toLocaleUpperCase("az")); +assertEquals(latin1SupplLowercased, latin1Suppl.toLocaleLowerCase("az")); +assertEquals(latin1SupplUppercased, latin1Suppl.toLocaleUpperCase("lt")); +// Lithuanian need to have a dot-above for U+00CC(Ì) and U+00CD(Í) when +// lowercasing. +assertEquals("\u00A0¡¢£¤¥¦§¨©ª«¬\u00AD®°±²³´µ¶·¸¹º»¼½¾¿" + + "àáâãäåæçèéêëi\u0307\u0300i\u0307\u0301îïðñòóôõö×øùúûüýþß" + + "àáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ", + latin1Suppl.toLocaleLowerCase("lt")); From 6e0888ad9ecb3a1fdde3d0dfc404b4ada85240dd Mon Sep 17 00:00:00 2001 From: "Steven R. Loomis" Date: Mon, 28 Nov 2016 11:15:21 -0800 Subject: [PATCH 187/291] =?UTF-8?q?deps:=20add=20test=20for=20v8=20bug=20i?= =?UTF-8?q?n=20toUpper('=C3=A7')?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * add test for ç/Ç in various locales PR-URL: https://github.com/nodejs/node/pull/9828 Fixes: https://github.com/nodejs/node/issues/9785 Reviewed-By: James M Snell Reviewed-By: Ali Ijaz Sheikh Reviewed-By: Myles Borins --- test/parallel/test-intl.js | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/test/parallel/test-intl.js b/test/parallel/test-intl.js index 1058650830d084..43707e08c03710 100644 --- a/test/parallel/test-intl.js +++ b/test/parallel/test-intl.js @@ -16,6 +16,16 @@ function haveLocale(loc) { return locs.indexOf(loc) !== -1; } +// Always run these. They should always pass, even if the locale +// param is ignored. +assert.strictEqual('Ç'.toLocaleLowerCase('el'), 'ç'); +assert.strictEqual('Ç'.toLocaleLowerCase('tr'), 'ç'); +assert.strictEqual('Ç'.toLowerCase(), 'ç'); + +assert.strictEqual('ç'.toLocaleUpperCase('el'), 'Ç'); +assert.strictEqual('ç'.toLocaleUpperCase('tr'), 'Ç'); +assert.strictEqual('ç'.toUpperCase(), 'Ç'); + if (!common.hasIntl) { const erMsg = '"Intl" object is NOT present but v8_enable_i18n_support is ' + From 727c5e3c963c078e5977bfd02ed65cac9405da40 Mon Sep 17 00:00:00 2001 From: Adrian Estrada Date: Sat, 7 Jan 2017 09:58:28 -0500 Subject: [PATCH 188/291] test: improve test-fs-write-file-sync * use let and const instead of var * use assert.strictEqual instead of assert.equal * swap assertions arguments to match the standard PR-URL: https://github.com/nodejs/node/pull/10624 Reviewed-By: Colin Ihrig Reviewed-By: James M Snell Reviewed-By: Luigi Pinca Reviewed-By: Michael Dawson --- test/parallel/test-fs-write-file-sync.js | 28 ++++++++++++------------ 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/test/parallel/test-fs-write-file-sync.js b/test/parallel/test-fs-write-file-sync.js index ece5ba48df754d..ca6324ac1ff789 100644 --- a/test/parallel/test-fs-write-file-sync.js +++ b/test/parallel/test-fs-write-file-sync.js @@ -3,9 +3,9 @@ const common = require('../common'); const assert = require('assert'); const path = require('path'); const fs = require('fs'); -var openCount = 0; -var mode; -var content; +let openCount = 0; +let mode; +let content; // Need to hijack fs.open/close to make sure that things // get closed once they're opened. @@ -28,39 +28,39 @@ if (common.isWindows) { common.refreshTmpDir(); // Test writeFileSync -var file1 = path.join(common.tmpDir, 'testWriteFileSync.txt'); +const file1 = path.join(common.tmpDir, 'testWriteFileSync.txt'); fs.writeFileSync(file1, '123', {mode: mode}); content = fs.readFileSync(file1, {encoding: 'utf8'}); -assert.equal('123', content); +assert.strictEqual(content, '123'); -assert.equal(mode, fs.statSync(file1).mode & 0o777); +assert.strictEqual(fs.statSync(file1).mode & 0o777, mode); // Test appendFileSync -var file2 = path.join(common.tmpDir, 'testAppendFileSync.txt'); +const file2 = path.join(common.tmpDir, 'testAppendFileSync.txt'); fs.appendFileSync(file2, 'abc', {mode: mode}); content = fs.readFileSync(file2, {encoding: 'utf8'}); -assert.equal('abc', content); +assert.strictEqual(content, 'abc'); -assert.equal(mode, fs.statSync(file2).mode & mode); +assert.strictEqual(fs.statSync(file2).mode & mode, mode); // Test writeFileSync with file descriptor -var file3 = path.join(common.tmpDir, 'testWriteFileSyncFd.txt'); +const file3 = path.join(common.tmpDir, 'testWriteFileSyncFd.txt'); -var fd = fs.openSync(file3, 'w+', mode); +const fd = fs.openSync(file3, 'w+', mode); fs.writeFileSync(fd, '123'); fs.closeSync(fd); content = fs.readFileSync(file3, {encoding: 'utf8'}); -assert.equal('123', content); +assert.strictEqual(content, '123'); -assert.equal(mode, fs.statSync(file3).mode & 0o777); +assert.strictEqual(fs.statSync(file3).mode & 0o777, mode); // Verify that all opened files were closed. -assert.equal(0, openCount); +assert.strictEqual(openCount, 0); function openSync() { openCount++; From 3adda4b2ad65fff0b751f34f1cd39eacf376139e Mon Sep 17 00:00:00 2001 From: Teddy Katz Date: Fri, 6 Jan 2017 19:11:07 -0500 Subject: [PATCH 189/291] tools,test: enforce assert.ifError with lint rule This adds an ESLint rule to enforce the use of `assert.ifError(err)` instead of `if (err) throw err;` in tests. PR-URL: https://github.com/nodejs/node/pull/10671 Ref: https://github.com/nodejs/node/pull/10543 Reviewed-By: Colin Ihrig Reviewed-By: Rich Trott Reviewed-By: James M Snell Reviewed-By: Gibson Fahnestock Reviewed-By: Michal Zasso --- test/.eslintrc.yaml | 1 + test/parallel/test-crypto-pbkdf2.js | 2 +- test/parallel/test-fs-long-path.js | 5 ++- test/parallel/test-fs-readfile-pipe.js | 2 +- .../test-fs-symlink-dir-junction-relative.js | 2 +- test/parallel/test-fs-symlink-dir-junction.js | 8 ++-- test/parallel/test-preload.js | 12 +++--- test/pummel/test-regress-GH-814.js | 5 +-- test/pummel/test-regress-GH-814_2.js | 5 +-- tools/eslint-rules/prefer-assert-iferror.js | 42 +++++++++++++++++++ 10 files changed, 63 insertions(+), 21 deletions(-) create mode 100644 tools/eslint-rules/prefer-assert-iferror.js diff --git a/test/.eslintrc.yaml b/test/.eslintrc.yaml index 90bf5f6d88d4e5..5e73630174e75e 100644 --- a/test/.eslintrc.yaml +++ b/test/.eslintrc.yaml @@ -3,4 +3,5 @@ rules: ## common module is mandatory in tests required-modules: [2, common] + prefer-assert-iferror: 2 prefer-assert-methods: 2 diff --git a/test/parallel/test-crypto-pbkdf2.js b/test/parallel/test-crypto-pbkdf2.js index 20ea5c7298199a..9bac769a5cab83 100644 --- a/test/parallel/test-crypto-pbkdf2.js +++ b/test/parallel/test-crypto-pbkdf2.js @@ -52,7 +52,7 @@ assert.strictEqual(key.toString('hex'), expected); crypto.pbkdf2('password', 'salt', 32, 32, 'sha256', common.mustCall(ondone)); function ondone(err, key) { - if (err) throw err; + assert.ifError(err); assert.strictEqual(key.toString('hex'), expected); } diff --git a/test/parallel/test-fs-long-path.js b/test/parallel/test-fs-long-path.js index 63b00118217288..dd091ae1b1a94c 100644 --- a/test/parallel/test-fs-long-path.js +++ b/test/parallel/test-fs-long-path.js @@ -2,6 +2,7 @@ const common = require('../common'); const fs = require('fs'); const path = require('path'); +const assert = require('assert'); if (!common.isWindows) { common.skip('this test is Windows-specific.'); @@ -21,10 +22,10 @@ console.log({ }); fs.writeFile(fullPath, 'ok', common.mustCall(function(err) { - if (err) throw err; + assert.ifError(err); fs.stat(fullPath, common.mustCall(function(err, stats) { - if (err) throw err; + assert.ifError(err); })); })); diff --git a/test/parallel/test-fs-readfile-pipe.js b/test/parallel/test-fs-readfile-pipe.js index 91465a261c8f96..566dbbe4c84929 100644 --- a/test/parallel/test-fs-readfile-pipe.js +++ b/test/parallel/test-fs-readfile-pipe.js @@ -15,7 +15,7 @@ const dataExpected = fs.readFileSync(__filename, 'utf8'); if (process.argv[2] === 'child') { fs.readFile('/dev/stdin', function(er, data) { - if (er) throw er; + assert.ifError(er); process.stdout.write(data); }); return; diff --git a/test/parallel/test-fs-symlink-dir-junction-relative.js b/test/parallel/test-fs-symlink-dir-junction-relative.js index 814b0c678eb3ef..166894c97ed846 100644 --- a/test/parallel/test-fs-symlink-dir-junction-relative.js +++ b/test/parallel/test-fs-symlink-dir-junction-relative.js @@ -15,7 +15,7 @@ common.refreshTmpDir(); // Test fs.symlink() fs.symlink(linkData, linkPath1, 'junction', common.mustCall(function(err) { - if (err) throw err; + assert.ifError(err); verifyLink(linkPath1); })); diff --git a/test/parallel/test-fs-symlink-dir-junction.js b/test/parallel/test-fs-symlink-dir-junction.js index 58ddb7ca38ae1c..ed0430b947ba0c 100644 --- a/test/parallel/test-fs-symlink-dir-junction.js +++ b/test/parallel/test-fs-symlink-dir-junction.js @@ -14,18 +14,18 @@ console.log('linkData: ' + linkData); console.log('linkPath: ' + linkPath); fs.symlink(linkData, linkPath, 'junction', common.mustCall(function(err) { - if (err) throw err; + assert.ifError(err); fs.lstat(linkPath, common.mustCall(function(err, stats) { - if (err) throw err; + assert.ifError(err); assert.ok(stats.isSymbolicLink()); fs.readlink(linkPath, common.mustCall(function(err, destination) { - if (err) throw err; + assert.ifError(err); assert.strictEqual(destination, linkData); fs.unlink(linkPath, common.mustCall(function(err) { - if (err) throw err; + assert.ifError(err); assert(!common.fileExists(linkPath)); assert(common.fileExists(linkData)); })); diff --git a/test/parallel/test-preload.js b/test/parallel/test-preload.js index bf3c4a09cf5600..3413a2a6dc69c8 100644 --- a/test/parallel/test-preload.js +++ b/test/parallel/test-preload.js @@ -34,7 +34,7 @@ const fixtureThrows = fixture('throws_error4.js'); // test preloading a single module works childProcess.exec(nodeBinary + ' ' + preloadOption([fixtureA]) + ' ' + fixtureB, function(err, stdout, stderr) { - if (err) throw err; + assert.ifError(err); assert.strictEqual(stdout, 'A\nB\n'); }); @@ -42,7 +42,7 @@ childProcess.exec(nodeBinary + ' ' + preloadOption([fixtureA]) + ' ' + fixtureB, childProcess.exec( nodeBinary + ' ' + preloadOption([fixtureA, fixtureB]) + ' ' + fixtureC, function(err, stdout, stderr) { - if (err) throw err; + assert.ifError(err); assert.strictEqual(stdout, 'A\nB\nC\n'); } ); @@ -63,7 +63,7 @@ childProcess.exec( childProcess.exec( nodeBinary + ' ' + preloadOption([fixtureA]) + '-e "console.log(\'hello\');"', function(err, stdout, stderr) { - if (err) throw err; + assert.ifError(err); assert.strictEqual(stdout, 'A\nhello\n'); } ); @@ -110,7 +110,7 @@ childProcess.exec( nodeBinary + ' ' + preloadOption([fixtureA]) + '-e "console.log(\'hello\');" ' + preloadOption([fixtureA, fixtureB]), function(err, stdout, stderr) { - if (err) throw err; + assert.ifError(err); assert.strictEqual(stdout, 'A\nB\nhello\n'); } ); @@ -131,7 +131,7 @@ childProcess.exec( nodeBinary + ' ' + '--require ' + fixture('cluster-preload.js') + ' ' + fixture('cluster-preload-test.js'), function(err, stdout, stderr) { - if (err) throw err; + assert.ifError(err); assert.ok(/worker terminated with code 43/.test(stdout)); } ); @@ -142,7 +142,7 @@ childProcess.exec( nodeBinary + ' ' + '--expose_debug_as=v8debug ' + '--require ' + fixture('cluster-preload.js') + ' ' + 'cluster-preload-test.js', function(err, stdout, stderr) { - if (err) throw err; + assert.ifError(err); assert.ok(/worker terminated with code 43/.test(stdout)); } ); diff --git a/test/pummel/test-regress-GH-814.js b/test/pummel/test-regress-GH-814.js index 4633844ee1b65a..4c890e1705acc3 100644 --- a/test/pummel/test-regress-GH-814.js +++ b/test/pummel/test-regress-GH-814.js @@ -2,6 +2,7 @@ // Flags: --expose_gc const common = require('../common'); +const assert = require('assert'); function newBuffer(size, value) { var buffer = Buffer.allocUnsafe(size); @@ -59,7 +60,5 @@ var timeToQuit = Date.now() + 8e3; //Test during no more than this seconds. function cb(err, written) { - if (err) { - throw err; - } + assert.ifError(err); } diff --git a/test/pummel/test-regress-GH-814_2.js b/test/pummel/test-regress-GH-814_2.js index 31c18529856da9..afba742e60bb7d 100644 --- a/test/pummel/test-regress-GH-814_2.js +++ b/test/pummel/test-regress-GH-814_2.js @@ -2,6 +2,7 @@ // Flags: --expose_gc const common = require('../common'); +const assert = require('assert'); const fs = require('fs'); const testFileName = require('path').join(common.tmpDir, 'GH-814_test.txt'); @@ -64,9 +65,7 @@ function writer() { function writerCB(err, written) { //console.error('cb.'); - if (err) { - throw err; - } + assert.ifError(err); } diff --git a/tools/eslint-rules/prefer-assert-iferror.js b/tools/eslint-rules/prefer-assert-iferror.js new file mode 100644 index 00000000000000..0da272d5f670e3 --- /dev/null +++ b/tools/eslint-rules/prefer-assert-iferror.js @@ -0,0 +1,42 @@ +/** + * @fileoverview Prohibit the `if (err) throw err;` pattern + * @author Teddy Katz + */ + +'use strict'; + +module.exports = { + create(context) { + const sourceCode = context.getSourceCode(); + + function hasSameTokens(nodeA, nodeB) { + const aTokens = sourceCode.getTokens(nodeA); + const bTokens = sourceCode.getTokens(nodeB); + + return aTokens.length === bTokens.length && + aTokens.every((token, index) => { + return token.type === bTokens[index].type && + token.value === bTokens[index].value; + }); + } + + return { + IfStatement(node) { + const firstStatement = node.consequent.type === 'BlockStatement' ? + node.consequent.body[0] : + node.consequent; + if ( + firstStatement && + firstStatement.type === 'ThrowStatement' && + hasSameTokens(node.test, firstStatement.argument) + ) { + context.report({ + node: firstStatement, + message: 'Use assert.ifError({{argument}}) instead.', + data: {argument: sourceCode.getText(node.test)} + }); + } + } + }; + } +}; From 2f9fdc454fc8356a83a4fa23ec1b61c448a20e89 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Thu, 5 Jan 2017 10:25:46 -0800 Subject: [PATCH 190/291] url: allow use of URL with http.request and https.request PR-URL: https://github.com/nodejs/node/pull/10638 Reviewed-By: Colin Ihrig Reviewed-By: Evan Lucas Reviewed-By: Michal Zasso Reviewed-By: Joyee Cheung --- lib/_http_client.js | 4 +++- lib/https.js | 3 +++ lib/internal/url.js | 24 +++++++++++++++++++++ test/parallel/test-http-client-get-url.js | 9 ++++++-- test/parallel/test-https-client-get-url.js | 9 ++++++-- test/parallel/test-whatwg-url-properties.js | 17 +++++++++++++++ 6 files changed, 61 insertions(+), 5 deletions(-) diff --git a/lib/_http_client.js b/lib/_http_client.js index 97fdf16cc875b1..c2b3d60afbee61 100644 --- a/lib/_http_client.js +++ b/lib/_http_client.js @@ -13,7 +13,7 @@ const debug = common.debug; const OutgoingMessage = require('_http_outgoing').OutgoingMessage; const Agent = require('_http_agent'); const Buffer = require('buffer').Buffer; - +const urlToOptions = require('internal/url').urlToOptions; // The actual list of disallowed characters in regexp form is more like: // /[^A-Za-z0-9\-._~!$&'()*+,;=/:@]/ @@ -52,6 +52,8 @@ function ClientRequest(options, cb) { if (!options.hostname) { throw new Error('Unable to determine the domain name'); } + } else if (options instanceof url.URL) { + options = urlToOptions(options); } else { options = util._extend({}, options); } diff --git a/lib/https.js b/lib/https.js index e05be20b4d6d5a..e59e7dfcb6beeb 100644 --- a/lib/https.js +++ b/lib/https.js @@ -8,6 +8,7 @@ const http = require('http'); const util = require('util'); const inherits = util.inherits; const debug = util.debuglog('https'); +const urlToOptions = require('internal/url').urlToOptions; function Server(opts, requestListener) { if (!(this instanceof Server)) return new Server(opts, requestListener); @@ -196,6 +197,8 @@ exports.request = function request(options, cb) { if (!options.hostname) { throw new Error('Unable to determine the domain name'); } + } else if (options instanceof url.URL) { + options = urlToOptions(options); } else { options = util._extend({}, options); } diff --git a/lib/internal/url.js b/lib/internal/url.js index 995e533013249c..9be683f28a4e06 100644 --- a/lib/internal/url.js +++ b/lib/internal/url.js @@ -1019,9 +1019,33 @@ function domainToUnicode(domain) { return binding.domainToUnicode(String(domain)); } +// Utility function that converts a URL object into an ordinary +// options object as expected by the http.request and https.request +// APIs. +function urlToOptions(url) { + var options = { + protocol: url.protocol, + host: url.host, + hostname: url.hostname, + hash: url.hash, + search: url.search, + pathname: url.pathname, + path: `${url.pathname}${url.search}`, + href: url.href + }; + if (url.port !== '') { + options.port = Number(url.port); + } + if (url.username || url.password) { + options.auth = `${url.username}:${url.password}`; + } + return options; +} + exports.URL = URL; exports.URLSearchParams = URLSearchParams; exports.originFor = originFor; exports.domainToASCII = domainToASCII; exports.domainToUnicode = domainToUnicode; exports.encodeAuth = encodeAuth; +exports.urlToOptions = urlToOptions; diff --git a/test/parallel/test-http-client-get-url.js b/test/parallel/test-http-client-get-url.js index 0fc8cf47da5b3d..d9a5e9325699d2 100644 --- a/test/parallel/test-http-client-get-url.js +++ b/test/parallel/test-http-client-get-url.js @@ -2,6 +2,8 @@ const common = require('../common'); const assert = require('assert'); const http = require('http'); +const url = require('url'); +const URL = url.URL; var server = http.createServer(common.mustCall(function(req, res) { assert.equal('GET', req.method); @@ -10,8 +12,11 @@ var server = http.createServer(common.mustCall(function(req, res) { res.write('hello\n'); res.end(); server.close(); -})); +}, 3)); server.listen(0, function() { - http.get(`http://127.0.0.1:${this.address().port}/foo?bar`); + const u = `http://127.0.0.1:${this.address().port}/foo?bar`; + http.get(u); + http.get(url.parse(u)); + http.get(new URL(u)); }); diff --git a/test/parallel/test-https-client-get-url.js b/test/parallel/test-https-client-get-url.js index 4e92b6ae881451..6852967848a16b 100644 --- a/test/parallel/test-https-client-get-url.js +++ b/test/parallel/test-https-client-get-url.js @@ -12,6 +12,8 @@ if (!common.hasCrypto) { const https = require('https'); const fs = require('fs'); +const url = require('url'); +const URL = url.URL; var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), @@ -25,8 +27,11 @@ var server = https.createServer(options, common.mustCall(function(req, res) { res.write('hello\n'); res.end(); server.close(); -})); +}, 3)); server.listen(0, function() { - https.get(`https://127.0.0.1:${this.address().port}/foo?bar`); + const u = `https://127.0.0.1:${this.address().port}/foo?bar`; + https.get(u); + https.get(url.parse(u)); + https.get(new URL(u)); }); diff --git a/test/parallel/test-whatwg-url-properties.js b/test/parallel/test-whatwg-url-properties.js index 340a51525e33bf..0b5e633677170a 100644 --- a/test/parallel/test-whatwg-url-properties.js +++ b/test/parallel/test-whatwg-url-properties.js @@ -1,9 +1,11 @@ +// Flags: --expose-internals 'use strict'; require('../common'); const URL = require('url').URL; const assert = require('assert'); +const urlToOptions = require('internal/url').urlToOptions; const url = new URL('http://user:pass@foo.bar.com:21/aaa/zzz?l=24#test'); const oldParams = url.searchParams; // for test of [SameObject] @@ -125,3 +127,18 @@ assert.strictEqual(url.toString(), 'https://user2:pass2@foo.bar.org:23/aaa/bbb?k=99#abcd'); assert.strictEqual((delete url.searchParams), true); assert.strictEqual(url.searchParams, oldParams); + +// Test urlToOptions +{ + const opts = + urlToOptions(new URL('http://user:pass@foo.bar.com:21/aaa/zzz?l=24#test')); + assert.strictEqual(opts instanceof URL, false); + assert.strictEqual(opts.protocol, 'http:'); + assert.strictEqual(opts.auth, 'user:pass'); + assert.strictEqual(opts.hostname, 'foo.bar.com'); + assert.strictEqual(opts.port, 21); + assert.strictEqual(opts.path, '/aaa/zzz?l=24'); + assert.strictEqual(opts.pathname, '/aaa/zzz'); + assert.strictEqual(opts.search, '?l=24'); + assert.strictEqual(opts.hash, '#test'); +} From fc0551072b81cee2c8b58e568a62d22399d18982 Mon Sep 17 00:00:00 2001 From: Adrian Estrada Date: Mon, 9 Jan 2017 11:32:57 -0500 Subject: [PATCH 191/291] test: improve test-crypto-rsa-dsa * use const and let instead of var * use assert.strictEqual or assert.strictDeepEqual instead of assert.equal * use arrow functions * swap assertions arguments to match the standard * validate the error for assert.throws PR-URL: https://github.com/nodejs/node/pull/10681 Reviewed-By: James M Snell Reviewed-By: Colin Ihrig Reviewed-By: Luigi Pinca --- test/parallel/test-crypto-rsa-dsa.js | 107 ++++++++++++++------------- 1 file changed, 54 insertions(+), 53 deletions(-) diff --git a/test/parallel/test-crypto-rsa-dsa.js b/test/parallel/test-crypto-rsa-dsa.js index ffa862d6a97569..d894e0dcafd9eb 100644 --- a/test/parallel/test-crypto-rsa-dsa.js +++ b/test/parallel/test-crypto-rsa-dsa.js @@ -11,21 +11,24 @@ const constants = require('crypto').constants; const crypto = require('crypto'); // Test certificates -var certPem = fs.readFileSync(common.fixturesDir + '/test_cert.pem', 'ascii'); -var keyPem = fs.readFileSync(common.fixturesDir + '/test_key.pem', 'ascii'); -var rsaPubPem = fs.readFileSync(common.fixturesDir + '/test_rsa_pubkey.pem', - 'ascii'); -var rsaKeyPem = fs.readFileSync(common.fixturesDir + '/test_rsa_privkey.pem', - 'ascii'); -var rsaKeyPemEncrypted = fs.readFileSync( +const certPem = fs.readFileSync(common.fixturesDir + '/test_cert.pem', 'ascii'); +const keyPem = fs.readFileSync(common.fixturesDir + '/test_key.pem', 'ascii'); +const rsaPubPem = fs.readFileSync(common.fixturesDir + '/test_rsa_pubkey.pem', + 'ascii'); +const rsaKeyPem = fs.readFileSync(common.fixturesDir + '/test_rsa_privkey.pem', + 'ascii'); +const rsaKeyPemEncrypted = fs.readFileSync( common.fixturesDir + '/test_rsa_privkey_encrypted.pem', 'ascii'); -var dsaPubPem = fs.readFileSync(common.fixturesDir + '/test_dsa_pubkey.pem', - 'ascii'); -var dsaKeyPem = fs.readFileSync(common.fixturesDir + '/test_dsa_privkey.pem', - 'ascii'); -var dsaKeyPemEncrypted = fs.readFileSync( +const dsaPubPem = fs.readFileSync(common.fixturesDir + '/test_dsa_pubkey.pem', + 'ascii'); +const dsaKeyPem = fs.readFileSync(common.fixturesDir + '/test_dsa_privkey.pem', + 'ascii'); +const dsaKeyPemEncrypted = fs.readFileSync( common.fixturesDir + '/test_dsa_privkey_encrypted.pem', 'ascii'); +const decryptError = new RegExp('^Error: error:06065064:digital envelope ' + + 'routines:EVP_DecryptFinal_ex:bad decrypt$'); + // Test RSA encryption/decryption { const input = 'I AM THE WALRUS'; @@ -34,13 +37,13 @@ var dsaKeyPemEncrypted = fs.readFileSync( let encryptedBuffer = crypto.publicEncrypt(rsaPubPem, bufferToEncrypt); let decryptedBuffer = crypto.privateDecrypt(rsaKeyPem, encryptedBuffer); - assert.strictEqual(input, decryptedBuffer.toString()); + assert.strictEqual(decryptedBuffer.toString(), input); let decryptedBufferWithPassword = crypto.privateDecrypt({ key: rsaKeyPemEncrypted, passphrase: 'password' }, encryptedBuffer); - assert.strictEqual(input, decryptedBufferWithPassword.toString()); + assert.strictEqual(decryptedBufferWithPassword.toString(), input); encryptedBuffer = crypto.publicEncrypt({ key: rsaKeyPemEncrypted, @@ -51,7 +54,7 @@ var dsaKeyPemEncrypted = fs.readFileSync( key: rsaKeyPemEncrypted, passphrase: 'password' }, encryptedBuffer); - assert.strictEqual(input, decryptedBufferWithPassword.toString()); + assert.strictEqual(decryptedBufferWithPassword.toString(), input); encryptedBuffer = crypto.privateEncrypt({ key: rsaKeyPemEncrypted, @@ -62,68 +65,69 @@ var dsaKeyPemEncrypted = fs.readFileSync( key: rsaKeyPemEncrypted, passphrase: Buffer.from('password') }, encryptedBuffer); - assert.strictEqual(input, decryptedBufferWithPassword.toString()); + assert.strictEqual(decryptedBufferWithPassword.toString(), input); encryptedBuffer = crypto.publicEncrypt(certPem, bufferToEncrypt); decryptedBuffer = crypto.privateDecrypt(keyPem, encryptedBuffer); - assert.strictEqual(input, decryptedBuffer.toString()); + assert.strictEqual(decryptedBuffer.toString(), input); encryptedBuffer = crypto.publicEncrypt(keyPem, bufferToEncrypt); decryptedBuffer = crypto.privateDecrypt(keyPem, encryptedBuffer); - assert.strictEqual(input, decryptedBuffer.toString()); + assert.strictEqual(decryptedBuffer.toString(), input); encryptedBuffer = crypto.privateEncrypt(keyPem, bufferToEncrypt); decryptedBuffer = crypto.publicDecrypt(keyPem, encryptedBuffer); - assert.strictEqual(input, decryptedBuffer.toString()); + assert.strictEqual(decryptedBuffer.toString(), input); - assert.throws(function() { + assert.throws(() => { crypto.privateDecrypt({ key: rsaKeyPemEncrypted, passphrase: 'wrong' }, bufferToEncrypt); - }); + }, decryptError); - assert.throws(function() { + assert.throws(() => { crypto.publicEncrypt({ key: rsaKeyPemEncrypted, passphrase: 'wrong' }, encryptedBuffer); - }); + }, decryptError); encryptedBuffer = crypto.privateEncrypt({ key: rsaKeyPemEncrypted, passphrase: Buffer.from('password') }, bufferToEncrypt); - assert.throws(function() { + assert.throws(() => { crypto.publicDecrypt({ key: rsaKeyPemEncrypted, passphrase: [].concat.apply([], Buffer.from('password')) }, encryptedBuffer); - }); + }, decryptError); } function test_rsa(padding) { - var input = Buffer.allocUnsafe(padding === 'RSA_NO_PADDING' ? 1024 / 8 : 32); - for (var i = 0; i < input.length; i++) + const size = (padding === 'RSA_NO_PADDING') ? 1024 / 8 : 32; + const input = Buffer.allocUnsafe(size); + for (let i = 0; i < input.length; i++) input[i] = (i * 7 + 11) & 0xff; - var bufferToEncrypt = Buffer.from(input); + const bufferToEncrypt = Buffer.from(input); padding = constants[padding]; - var encryptedBuffer = crypto.publicEncrypt({ + const encryptedBuffer = crypto.publicEncrypt({ key: rsaPubPem, padding: padding }, bufferToEncrypt); - var decryptedBuffer = crypto.privateDecrypt({ + const decryptedBuffer = crypto.privateDecrypt({ key: rsaKeyPem, padding: padding }, encryptedBuffer); - assert.equal(input, decryptedBuffer.toString()); + assert.deepStrictEqual(decryptedBuffer, input); } test_rsa('RSA_NO_PADDING'); @@ -131,19 +135,21 @@ test_rsa('RSA_PKCS1_PADDING'); test_rsa('RSA_PKCS1_OAEP_PADDING'); // Test RSA key signing/verification -var rsaSign = crypto.createSign('RSA-SHA1'); -var rsaVerify = crypto.createVerify('RSA-SHA1'); +let rsaSign = crypto.createSign('RSA-SHA1'); +let rsaVerify = crypto.createVerify('RSA-SHA1'); assert.ok(rsaSign); assert.ok(rsaVerify); +const expectedSignature = + '5c50e3145c4e2497aadb0eabc83b342d0b0021ece0d4c4a064b7c' + + '8f020d7e2688b122bfb54c724ac9ee169f83f66d2fe90abeb95e8' + + 'e1290e7e177152a4de3d944cf7d4883114a20ed0f78e70e25ef0f' + + '60f06b858e6af42a2f276ede95bbc6bc9a9bbdda15bd663186a6f' + + '40819a7af19e577bb2efa5e579a1f5ce8a0d4ca8b8f6'; + rsaSign.update(rsaPubPem); -var rsaSignature = rsaSign.sign(rsaKeyPem, 'hex'); -assert.equal(rsaSignature, - '5c50e3145c4e2497aadb0eabc83b342d0b0021ece0d4c4a064b7c' + - '8f020d7e2688b122bfb54c724ac9ee169f83f66d2fe90abeb95e8' + - 'e1290e7e177152a4de3d944cf7d4883114a20ed0f78e70e25ef0f' + - '60f06b858e6af42a2f276ede95bbc6bc9a9bbdda15bd663186a6f' + - '40819a7af19e577bb2efa5e579a1f5ce8a0d4ca8b8f6'); +let rsaSignature = rsaSign.sign(rsaKeyPem, 'hex'); +assert.strictEqual(rsaSignature, expectedSignature); rsaVerify.update(rsaPubPem); assert.strictEqual(rsaVerify.verify(rsaPubPem, rsaSignature, 'hex'), true); @@ -151,16 +157,11 @@ assert.strictEqual(rsaVerify.verify(rsaPubPem, rsaSignature, 'hex'), true); // Test RSA key signing/verification with encrypted key rsaSign = crypto.createSign('RSA-SHA1'); rsaSign.update(rsaPubPem); -assert.doesNotThrow(function() { +assert.doesNotThrow(() => { var signOptions = { key: rsaKeyPemEncrypted, passphrase: 'password' }; rsaSignature = rsaSign.sign(signOptions, 'hex'); }); -assert.equal(rsaSignature, - '5c50e3145c4e2497aadb0eabc83b342d0b0021ece0d4c4a064b7c' + - '8f020d7e2688b122bfb54c724ac9ee169f83f66d2fe90abeb95e8' + - 'e1290e7e177152a4de3d944cf7d4883114a20ed0f78e70e25ef0f' + - '60f06b858e6af42a2f276ede95bbc6bc9a9bbdda15bd663186a6f' + - '40819a7af19e577bb2efa5e579a1f5ce8a0d4ca8b8f6'); +assert.strictEqual(rsaSignature, expectedSignature); rsaVerify = crypto.createVerify('RSA-SHA1'); rsaVerify.update(rsaPubPem); @@ -168,10 +169,10 @@ assert.strictEqual(rsaVerify.verify(rsaPubPem, rsaSignature, 'hex'), true); rsaSign = crypto.createSign('RSA-SHA1'); rsaSign.update(rsaPubPem); -assert.throws(function() { +assert.throws(() => { var signOptions = { key: rsaKeyPemEncrypted, passphrase: 'wrong' }; rsaSign.sign(signOptions, 'hex'); -}); +}, decryptError); // // Test RSA signing and verification @@ -196,7 +197,7 @@ assert.throws(function() { sign.update(input); const output = sign.sign(privateKey, 'hex'); - assert.strictEqual(output, signature); + assert.strictEqual(signature, output); const verify = crypto.createVerify('RSA-SHA256'); verify.update(input); @@ -232,9 +233,9 @@ const input = 'I AM THE WALRUS'; { const sign = crypto.createSign('DSS1'); sign.update(input); - assert.throws(function() { + assert.throws(() => { sign.sign({ key: dsaKeyPemEncrypted, passphrase: 'wrong' }, 'hex'); - }); + }, decryptError); } { @@ -244,7 +245,7 @@ const input = 'I AM THE WALRUS'; sign.update(input); let signature; - assert.doesNotThrow(function() { + assert.doesNotThrow(() => { const signOptions = { key: dsaKeyPemEncrypted, passphrase: 'password' }; signature = sign.sign(signOptions, 'hex'); }); From 8262d49a44fd53c0a9af118c6ab71400b77dab1c Mon Sep 17 00:00:00 2001 From: abouthiroppy Date: Mon, 9 Jan 2017 15:58:37 +0900 Subject: [PATCH 192/291] test: refactor cluster-preload.js PR-URL: https://github.com/nodejs/node/pull/10701 Reviewed-By: Colin Ihrig Reviewed-By: James M Snell Reviewed-By: Italo A. Casas --- test/fixtures/cluster-preload.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/fixtures/cluster-preload.js b/test/fixtures/cluster-preload.js index 26d81d8b7a53f6..bb38793b65d7de 100644 --- a/test/fixtures/cluster-preload.js +++ b/test/fixtures/cluster-preload.js @@ -5,7 +5,7 @@ const assert = require('assert'); // module search paths initialized from the current working directory assert.ok(module.parent); const expectedPaths = require('module')._nodeModulePaths(process.cwd()); -assert.deepEqual(module.parent.paths, expectedPaths); +assert.deepStrictEqual(module.parent.paths, expectedPaths); const cluster = require('cluster'); cluster.isMaster || process.exit(42 + cluster.worker.id); // +42 to distinguish From e6b6ce429cf2652c3320df48239a1d6cbb5d19f3 Mon Sep 17 00:00:00 2001 From: cjihrig Date: Tue, 10 Jan 2017 12:38:18 -0500 Subject: [PATCH 193/291] test: refactor test-http-mutable-headers.js MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR-URL: https://github.com/nodejs/node/pull/10664 Reviewed-By: James M Snell Reviewed-By: Michaël Zasso Reviewed-By: Luigi Pinca --- test/parallel/test-http-mutable-headers.js | 97 ++++++++++------------ 1 file changed, 45 insertions(+), 52 deletions(-) diff --git a/test/parallel/test-http-mutable-headers.js b/test/parallel/test-http-mutable-headers.js index ecb777c09b683d..072dd97076fe1a 100644 --- a/test/parallel/test-http-mutable-headers.js +++ b/test/parallel/test-http-mutable-headers.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); const assert = require('assert'); const http = require('http'); @@ -11,43 +11,48 @@ const http = require('http'); // .method // .path -var testsComplete = 0; -var test = 'headers'; -var content = 'hello world\n'; -var cookies = [ +let test = 'headers'; +const content = 'hello world\n'; +const cookies = [ 'session_token=; path=/; expires=Sun, 15-Sep-2030 13:48:52 GMT', 'prefers_open_id=; path=/; expires=Thu, 01-Jan-1970 00:00:00 GMT' ]; -var s = http.createServer(function(req, res) { +const s = http.createServer(common.mustCall((req, res) => { switch (test) { case 'headers': - assert.throws(function() { res.setHeader(); }); - assert.throws(function() { res.setHeader('someHeader'); }); - assert.throws(function() { res.getHeader(); }); - assert.throws(function() { res.removeHeader(); }); + assert.throws(() => { + res.setHeader(); + }, /^TypeError: Header name must be a valid HTTP Token \["undefined"\]$/); + assert.throws(() => { + res.setHeader('someHeader'); + }, /^Error: "value" required in setHeader\("someHeader", value\)$/); + assert.throws(() => { + res.getHeader(); + }, /^Error: "name" argument is required for getHeader\(name\)$/); + assert.throws(() => { + res.removeHeader(); + }, /^Error: "name" argument is required for removeHeader\(name\)$/); res.setHeader('x-test-header', 'testing'); res.setHeader('X-TEST-HEADER2', 'testing'); res.setHeader('set-cookie', cookies); res.setHeader('x-test-array-header', [1, 2, 3]); - var val1 = res.getHeader('x-test-header'); - var val2 = res.getHeader('x-test-header2'); - assert.equal(val1, 'testing'); - assert.equal(val2, 'testing'); + assert.strictEqual(res.getHeader('x-test-header'), 'testing'); + assert.strictEqual(res.getHeader('x-test-header2'), 'testing'); res.removeHeader('x-test-header2'); break; case 'contentLength': res.setHeader('content-length', content.length); - assert.equal(content.length, res.getHeader('Content-Length')); + assert.strictEqual(res.getHeader('Content-Length'), content.length); break; case 'transferEncoding': res.setHeader('transfer-encoding', 'chunked'); - assert.equal(res.getHeader('Transfer-Encoding'), 'chunked'); + assert.strictEqual(res.getHeader('Transfer-Encoding'), 'chunked'); break; case 'writeHead': @@ -55,11 +60,14 @@ var s = http.createServer(function(req, res) { res.setHeader('x-foo', 'keyboard cat'); res.writeHead(200, { 'x-foo': 'bar', 'x-bar': 'baz' }); break; + + default: + common.fail('Unknown test'); } res.statusCode = 201; res.end(content); -}); +}, 4)); s.listen(0, nextTest); @@ -69,64 +77,49 @@ function nextTest() { return s.close(); } - var bufferedResponse = ''; - - http.get({ port: s.address().port }, function(response) { - console.log('TEST: ' + test); - console.log('STATUS: ' + response.statusCode); - console.log('HEADERS: '); - console.dir(response.headers); + let bufferedResponse = ''; + http.get({ port: s.address().port }, common.mustCall((response) => { switch (test) { case 'headers': - assert.equal(response.statusCode, 201); - assert.equal(response.headers['x-test-header'], - 'testing'); - assert.equal(response.headers['x-test-array-header'], - [1, 2, 3].join(', ')); - assert.deepStrictEqual(cookies, - response.headers['set-cookie']); - assert.equal(response.headers['x-test-header2'] !== undefined, false); - // Make the next request + assert.strictEqual(response.statusCode, 201); + assert.strictEqual(response.headers['x-test-header'], 'testing'); + assert.strictEqual(response.headers['x-test-array-header'], + [1, 2, 3].join(', ')); + assert.deepStrictEqual(cookies, response.headers['set-cookie']); + assert.strictEqual(response.headers['x-test-header2'], undefined); test = 'contentLength'; - console.log('foobar'); break; case 'contentLength': - assert.equal(response.headers['content-length'], content.length); + assert.strictEqual(+response.headers['content-length'], content.length); test = 'transferEncoding'; break; case 'transferEncoding': - assert.equal(response.headers['transfer-encoding'], 'chunked'); + assert.strictEqual(response.headers['transfer-encoding'], 'chunked'); test = 'writeHead'; break; case 'writeHead': - assert.equal(response.headers['x-foo'], 'bar'); - assert.equal(response.headers['x-bar'], 'baz'); - assert.equal(200, response.statusCode); + assert.strictEqual(response.headers['x-foo'], 'bar'); + assert.strictEqual(response.headers['x-bar'], 'baz'); + assert.strictEqual(response.statusCode, 200); test = 'end'; break; default: - throw new Error('?'); + common.fail('Unknown test'); } response.setEncoding('utf8'); - response.on('data', function(s) { + response.on('data', (s) => { bufferedResponse += s; }); - response.on('end', function() { - assert.equal(content, bufferedResponse); - testsComplete++; - nextTest(); - }); - }); + response.on('end', common.mustCall(() => { + assert.strictEqual(bufferedResponse, content); + common.mustCall(nextTest)(); + })); + })); } - - -process.on('exit', function() { - assert.equal(4, testsComplete); -}); From a6bd28772402e66f38d0a012ca9bdae96449f47e Mon Sep 17 00:00:00 2001 From: Gibson Fahnestock Date: Sun, 8 Jan 2017 13:19:00 +0000 Subject: [PATCH 194/291] test: use eslint to fix var->const/let Manually fix issues that eslint --fix couldn't do automatically. PR-URL: https://github.com/nodejs/node/pull/10685 Reviewed-By: Colin Ihrig Reviewed-By: James M Snell Reviewed-By: Roman Reiss --- test/addons/buffer-free-callback/test.js | 4 +- test/addons/load-long-path/test.js | 6 +- test/addons/make-callback-recurse/test.js | 2 +- test/addons/repl-domain-abort/test.js | 14 +- .../test-stringbytes-external-at-max.js | 3 +- ...ingbytes-external-exceed-max-by-1-ascii.js | 3 +- ...ngbytes-external-exceed-max-by-1-base64.js | 3 +- ...ngbytes-external-exceed-max-by-1-binary.js | 5 +- ...tringbytes-external-exceed-max-by-1-hex.js | 3 +- ...ringbytes-external-exceed-max-by-1-utf8.js | 3 +- ...st-stringbytes-external-exceed-max-by-2.js | 3 +- .../test-stringbytes-external-exceed-max.js | 3 +- test/common.js | 2 +- test/debugger/helper-debugger-repl.js | 28 +-- test/debugger/test-debugger-repl-restart.js | 4 +- test/debugger/test-debugger-repl-term.js | 2 +- test/debugger/test-debugger-repl-utf8.js | 2 +- test/debugger/test-debugger-repl.js | 2 +- test/gc/test-http-client-connaborted.js | 8 +- test/gc/test-http-client-onerror.js | 8 +- test/gc/test-http-client-timeout.js | 8 +- test/gc/test-http-client.js | 6 +- test/gc/test-net-timeout.js | 7 +- test/inspector/inspector-helper.js | 4 +- .../test-dgram-multicast-multi-process.js | 19 +- .../test-dgram-send-cb-quelches-error.js | 6 +- test/internet/test-dns-cares-domains.js | 4 +- test/internet/test-dns.js | 96 +++++----- test/internet/test-net-connect-timeout.js | 8 +- test/internet/test-net-connect-unref.js | 5 +- .../internet/test-tls-connnect-melissadata.js | 2 +- .../test-url-parse-conformance.js | 8 +- test/message/eval_messages.js | 8 +- test/message/max_tick_depth.js | 2 +- test/message/stdin_messages.js | 8 +- .../test-assert-typedarray-deepequal.js | 2 +- test/parallel/test-assert.js | 31 ++-- .../test-async-wrap-check-providers.js | 2 +- .../test-async-wrap-throw-from-callback.js | 6 +- test/parallel/test-async-wrap-uid.js | 2 +- test/parallel/test-buffer-ascii.js | 2 +- test/parallel/test-buffer-bytelength.js | 26 +-- test/parallel/test-buffer-concat.js | 2 +- test/parallel/test-buffer-copy.js | 2 +- test/parallel/test-buffer-fill.js | 6 +- test/parallel/test-buffer-includes.js | 10 +- test/parallel/test-buffer-indexof.js | 39 ++-- test/parallel/test-buffer-inspect.js | 6 +- test/parallel/test-buffer-iterator.js | 4 +- test/parallel/test-buffer-swap.js | 48 ++--- .../test-child-process-constructor.js | 4 +- .../test-child-process-default-options.js | 4 +- .../test-child-process-double-pipe.js | 4 +- test/parallel/test-child-process-env.js | 6 +- test/parallel/test-child-process-exec-cwd.js | 2 +- ...-process-exec-stdout-stderr-data-string.js | 4 +- test/parallel/test-child-process-exit-code.js | 10 +- .../parallel/test-child-process-fork-close.js | 2 +- .../parallel/test-child-process-fork-dgram.js | 4 +- .../test-child-process-fork-exec-argv.js | 12 +- .../test-child-process-fork-exec-path.js | 8 +- test/parallel/test-child-process-fork-net.js | 32 ++-- test/parallel/test-child-process-fork-net2.js | 22 +-- test/parallel/test-child-process-fork-ref.js | 5 +- test/parallel/test-child-process-fork-ref2.js | 2 +- .../test-child-process-fork-regr-gh-2847.js | 6 +- test/parallel/test-child-process-fork.js | 4 +- test/parallel/test-child-process-internal.js | 8 +- ...test-child-process-send-returns-boolean.js | 2 +- .../test-child-process-set-blocking.js | 4 +- test/parallel/test-child-process-silent.js | 12 +- .../test-child-process-spawn-typeerror.js | 2 +- .../test-child-process-spawnsync-env.js | 4 +- .../test-child-process-spawnsync-input.js | 4 +- .../test-child-process-spawnsync-timeout.js | 10 +- test/parallel/test-child-process-stdin-ipc.js | 2 +- .../test-child-process-stdio-big-write-end.js | 3 +- .../test-child-process-stdio-inherit.js | 6 +- test/parallel/test-cli-eval.js | 4 +- test/parallel/test-cli-syntax.js | 20 +- test/parallel/test-cluster-basic.js | 5 +- .../test-cluster-bind-privileged-port.js | 2 +- test/parallel/test-cluster-dgram-1.js | 12 +- test/parallel/test-cluster-dgram-2.js | 6 +- test/parallel/test-cluster-dgram-reuse.js | 6 +- test/parallel/test-cluster-disconnect-race.js | 6 +- .../test-cluster-disconnect-suicide-race.js | 2 +- ...test-cluster-disconnect-with-no-workers.js | 2 +- test/parallel/test-cluster-disconnect.js | 16 +- test/parallel/test-cluster-eaccess.js | 2 +- test/parallel/test-cluster-eaddrinuse.js | 4 +- test/parallel/test-cluster-fork-env.js | 4 +- test/parallel/test-cluster-master-error.js | 10 +- test/parallel/test-cluster-master-kill.js | 4 +- test/parallel/test-cluster-message.js | 14 +- .../parallel/test-cluster-rr-domain-listen.js | 5 +- test/parallel/test-cluster-send-deadlock.js | 10 +- .../test-cluster-setup-master-argv.js | 4 +- .../test-cluster-setup-master-multiple.js | 4 +- test/parallel/test-cluster-setup-master.js | 12 +- test/parallel/test-cluster-shared-leak.js | 4 +- test/parallel/test-cluster-worker-death.js | 2 +- test/parallel/test-cluster-worker-destroy.js | 2 +- test/parallel/test-cluster-worker-events.js | 10 +- .../test-cluster-worker-forced-exit.js | 2 +- .../test-cluster-worker-isconnected.js | 2 +- test/parallel/test-cluster-worker-isdead.js | 2 +- test/parallel/test-cluster-worker-no-exit.js | 10 +- .../test-cluster-worker-wait-server-close.js | 8 +- test/parallel/test-console-instance.js | 4 +- .../test-console-not-call-toString.js | 4 +- test/parallel/test-crypto-binary-default.js | 118 ++++++------ test/parallel/test-crypto-certificate.js | 8 +- test/parallel/test-crypto-dh-odd-key.js | 4 +- test/parallel/test-crypto-dh.js | 63 +++---- test/parallel/test-crypto-domain.js | 6 +- test/parallel/test-crypto-domains.js | 4 +- test/parallel/test-crypto-fips.js | 4 +- test/parallel/test-crypto-from-binary.js | 6 +- test/parallel/test-crypto-hash.js | 32 ++-- test/parallel/test-crypto-hmac.js | 10 +- test/parallel/test-crypto-rsa-dsa.js | 4 +- test/parallel/test-crypto-sign-verify.js | 4 +- test/parallel/test-crypto-stream.js | 2 +- test/parallel/test-crypto-verify-failure.js | 6 +- test/parallel/test-cwd-enoent-repl.js | 4 +- test/parallel/test-cwd-enoent.js | 4 +- test/parallel/test-debug-brk.js | 14 +- test/parallel/test-debug-port-from-cmdline.js | 16 +- test/parallel/test-debug-signal-cluster.js | 8 +- .../test-debug-uncaught-exception-async.js | 2 +- test/parallel/test-debug-usage.js | 2 +- test/parallel/test-debugger-pid.js | 10 +- test/parallel/test-debugger-repeat-last.js | 8 +- test/parallel/test-dgram-address.js | 14 +- test/parallel/test-dgram-bind.js | 4 +- test/parallel/test-dgram-bytes-length.js | 4 +- .../test-dgram-close-is-not-callback.js | 4 +- test/parallel/test-dgram-close.js | 6 +- .../test-dgram-exclusive-implicit-bind.js | 7 +- test/parallel/test-dgram-implicit-bind.js | 6 +- test/parallel/test-dgram-listen-after-bind.js | 6 +- test/parallel/test-dgram-oob-buffer.js | 4 +- test/parallel/test-dgram-regress-4496.js | 2 +- .../parallel/test-dgram-send-bad-arguments.js | 6 +- test/parallel/test-dgram-send-empty-array.js | 2 +- test/parallel/test-dgram-send-empty-buffer.js | 2 +- test/parallel/test-dgram-setTTL.js | 2 +- test/parallel/test-dgram-unref.js | 2 +- test/parallel/test-dh-padding.js | 10 +- test/parallel/test-dns-lookup-cb-error.js | 2 +- .../parallel/test-domain-abort-on-uncaught.js | 6 +- test/parallel/test-domain-enter-exit.js | 6 +- .../test-domain-exit-dispose-again.js | 6 +- test/parallel/test-domain-exit-dispose.js | 4 +- test/parallel/test-domain-http-server.js | 22 +-- test/parallel/test-domain-implicit-fs.js | 2 +- test/parallel/test-domain-multi.js | 16 +- test/parallel/test-domain-nested-throw.js | 20 +- test/parallel/test-domain-safe-exit.js | 4 +- test/parallel/test-domain-stack.js | 6 +- ...n-throw-from-uncaught-exception-handler.js | 2 +- test/parallel/test-domain-timers.js | 8 +- ...st-domain-top-level-error-handler-throw.js | 10 +- ...domain-with-abort-on-uncaught-exception.js | 10 +- test/parallel/test-domain.js | 28 +-- test/parallel/test-dsa-fips-invalid-key.js | 6 +- test/parallel/test-error-reporting.js | 4 +- ...test-event-emitter-check-listener-leaks.js | 2 +- test/parallel/test-event-emitter-errors.js | 2 +- .../test-event-emitter-get-max-listeners.js | 4 +- ...st-event-emitter-listeners-side-effects.js | 4 +- .../test-event-emitter-method-names.js | 2 +- ...mitter-no-error-provided-to-error-event.js | 4 +- test/parallel/test-event-emitter-num-args.js | 2 +- test/parallel/test-event-emitter-once.js | 2 +- test/parallel/test-event-emitter-prepend.js | 2 +- ...test-event-emitter-remove-all-listeners.js | 2 +- ...-emitter-set-max-listeners-side-effects.js | 2 +- test/parallel/test-event-emitter-subclass.js | 6 +- test/parallel/test-exception-handler.js | 2 +- test/parallel/test-file-write-stream2.js | 9 +- test/parallel/test-force-repl-with-eval.js | 4 +- test/parallel/test-force-repl.js | 2 +- test/parallel/test-freelist.js | 2 +- test/parallel/test-fs-access.js | 2 +- test/parallel/test-fs-chmod.js | 2 +- test/parallel/test-fs-exists.js | 2 +- test/parallel/test-fs-long-path.js | 6 +- test/parallel/test-fs-open-flags.js | 14 +- .../test-fs-read-buffer-tostring-fail.js | 4 +- test/parallel/test-fs-read-stream-fd-leak.js | 6 +- test/parallel/test-fs-read-stream-resume.js | 2 +- test/parallel/test-fs-read-stream.js | 32 ++-- test/parallel/test-fs-read.js | 2 +- test/parallel/test-fs-readfile-fd.js | 2 +- .../test-fs-realpath-buffer-encoding.js | 5 +- .../test-fs-realpath-on-substed-drive.js | 3 +- test/parallel/test-fs-realpath.js | 15 +- test/parallel/test-fs-sir-writes-alot.js | 20 +- test/parallel/test-fs-stat.js | 2 +- .../test-fs-symlink-dir-junction-relative.js | 14 +- test/parallel/test-fs-symlink.js | 4 +- test/parallel/test-fs-sync-fd-leak.js | 4 +- test/parallel/test-fs-truncate-GH-6233.js | 2 +- test/parallel/test-fs-watch-recursive.js | 5 +- test/parallel/test-fs-watchfile.js | 2 +- test/parallel/test-fs-write-buffer.js | 2 +- test/parallel/test-fs-write-file-buffer.js | 4 +- .../test-fs-write-stream-change-open.js | 2 +- test/parallel/test-fs-write-stream-err.js | 10 +- test/parallel/test-fs-write-stream.js | 2 +- test/parallel/test-fs-write-string-coerce.js | 6 +- test/parallel/test-global-console-exists.js | 2 +- test/parallel/test-http-1.0-keep-alive.js | 12 +- test/parallel/test-http-1.0.js | 10 +- test/parallel/test-http-abort-before-end.js | 4 +- test/parallel/test-http-abort-client.js | 2 +- test/parallel/test-http-abort-queued.js | 12 +- test/parallel/test-http-after-connect.js | 4 +- .../test-http-agent-destroyed-socket.js | 16 +- .../parallel/test-http-agent-error-on-idle.js | 14 +- test/parallel/test-http-agent-false.js | 6 +- ...test-http-agent-maxsockets-regress-4050.js | 4 +- test/parallel/test-http-agent-maxsockets.js | 8 +- test/parallel/test-http-agent-no-protocol.js | 4 +- test/parallel/test-http-agent-null.js | 4 +- test/parallel/test-http-agent.js | 12 +- test/parallel/test-http-automatic-headers.js | 4 +- test/parallel/test-http-blank-header.js | 4 +- test/parallel/test-http-buffer-sanity.js | 16 +- test/parallel/test-http-byteswritten.js | 10 +- test/parallel/test-http-chunked.js | 24 +-- test/parallel/test-http-client-abort-event.js | 4 +- test/parallel/test-http-client-abort.js | 10 +- test/parallel/test-http-client-abort2.js | 4 +- test/parallel/test-http-client-agent.js | 14 +- .../test-http-client-default-headers-exist.js | 10 +- test/parallel/test-http-client-get-url.js | 2 +- test/parallel/test-http-client-parse-error.js | 6 +- test/parallel/test-http-client-pipe-end.js | 4 +- test/parallel/test-http-client-race-2.js | 24 +-- test/parallel/test-http-client-race.js | 16 +- .../test-http-client-read-in-error.js | 6 +- test/parallel/test-http-client-readable.js | 4 +- .../test-http-client-response-domain.js | 6 +- .../test-http-client-timeout-agent.js | 10 +- .../test-http-client-timeout-option.js | 8 +- .../test-http-client-timeout-with-data.js | 2 +- test/parallel/test-http-client-timeout.js | 8 +- test/parallel/test-http-client-upload-buf.js | 8 +- test/parallel/test-http-client-upload.js | 6 +- test/parallel/test-http-conn-reset.js | 6 +- test/parallel/test-http-connect-req-res.js | 4 +- test/parallel/test-http-content-length.js | 14 +- test/parallel/test-http-contentLength0.js | 4 +- test/parallel/test-http-date-header.js | 8 +- test/parallel/test-http-default-encoding.js | 6 +- .../test-http-destroyed-socket-write2.js | 4 +- test/parallel/test-http-eof-on-connect.js | 2 +- test/parallel/test-http-exceptions.js | 6 +- test/parallel/test-http-expect-continue.js | 16 +- test/parallel/test-http-extra-response.js | 10 +- .../test-http-flush-response-headers.js | 2 +- test/parallel/test-http-flush.js | 2 +- test/parallel/test-http-full-response.js | 16 +- .../test-http-get-pipeline-problem.js | 26 +-- test/parallel/test-http-head-request.js | 6 +- ...test-http-head-response-has-no-body-end.js | 4 +- .../test-http-head-response-has-no-body.js | 4 +- test/parallel/test-http-header-read.js | 6 +- test/parallel/test-http-hex-write.js | 4 +- .../test-http-host-header-ipv6-fail.js | 2 +- test/parallel/test-http-host-headers.js | 2 +- test/parallel/test-http-invalidheaderfield.js | 6 +- .../test-http-keep-alive-close-on-header.js | 14 +- test/parallel/test-http-keepalive-client.js | 16 +- .../test-http-keepalive-maxsockets.js | 12 +- test/parallel/test-http-keepalive-request.js | 16 +- .../test-http-localaddress-bind-error.js | 4 +- test/parallel/test-http-localaddress.js | 14 +- test/parallel/test-http-malformed-request.js | 8 +- .../test-http-many-ended-pipelines.js | 13 +- test/parallel/test-http-max-headers-count.js | 26 +-- test/parallel/test-http-multi-line-headers.js | 6 +- test/parallel/test-http-no-content-length.js | 4 +- test/parallel/test-http-outgoing-finish.js | 10 +- test/parallel/test-http-parser-bad-ref.js | 20 +- test/parallel/test-http-parser-free.js | 12 +- test/parallel/test-http-parser.js | 32 ++-- test/parallel/test-http-pause.js | 12 +- test/parallel/test-http-pipe-fs.js | 10 +- test/parallel/test-http-pipeline-flood.js | 4 +- test/parallel/test-http-pipeline-regr-2639.js | 6 +- test/parallel/test-http-pipeline-regr-3332.js | 6 +- test/parallel/test-http-pipeline-regr-3508.js | 16 +- test/parallel/test-http-proxy.js | 16 +- test/parallel/test-http-raw-headers.js | 18 +- .../test-http-remove-header-stays-removed.js | 4 +- ...test-http-request-dont-override-options.js | 6 +- test/parallel/test-http-request-end-twice.js | 4 +- test/parallel/test-http-request-end.js | 6 +- test/parallel/test-http-request-methods.js | 6 +- .../parallel/test-http-res-write-after-end.js | 4 +- ...test-http-res-write-end-dont-take-array.js | 4 +- test/parallel/test-http-response-close.js | 2 +- ...test-http-response-multi-content-length.js | 2 +- .../test-http-response-multiheaders.js | 4 +- .../parallel/test-http-response-no-headers.js | 14 +- test/parallel/test-http-response-readable.js | 2 +- test/parallel/test-http-response-splitting.js | 2 +- .../test-http-response-status-message.js | 16 +- .../parallel/test-http-response-statuscode.js | 2 +- .../parallel/test-http-server-client-error.js | 2 +- .../parallel/test-http-server-multiheaders.js | 2 +- .../test-http-server-multiheaders2.js | 8 +- test/parallel/test-http-server-stale-close.js | 4 +- test/parallel/test-http-server-unconsume.js | 6 +- test/parallel/test-http-server.js | 16 +- test/parallel/test-http-set-cookies.js | 4 +- test/parallel/test-http-set-timeout-server.js | 62 +++---- test/parallel/test-http-set-timeout.js | 6 +- test/parallel/test-http-set-trailers.js | 14 +- test/parallel/test-http-should-keep-alive.js | 12 +- test/parallel/test-http-status-code.js | 12 +- test/parallel/test-http-status-message.js | 8 +- test/parallel/test-http-timeout-overflow.js | 8 +- test/parallel/test-http-timeout.js | 8 +- test/parallel/test-http-unix-socket.js | 4 +- test/parallel/test-http-upgrade-agent.js | 16 +- test/parallel/test-http-upgrade-client.js | 10 +- test/parallel/test-http-upgrade-client2.js | 10 +- test/parallel/test-http-upgrade-server.js | 20 +- test/parallel/test-http-upgrade-server2.js | 4 +- ...p-url.parse-auth-with-header-in-request.js | 5 +- test/parallel/test-http-url.parse-auth.js | 4 +- test/parallel/test-http-url.parse-basic.js | 6 +- .../test-http-url.parse-https.request.js | 8 +- test/parallel/test-http-url.parse-path.js | 4 +- test/parallel/test-http-url.parse-post.js | 4 +- test/parallel/test-http-url.parse-search.js | 4 +- test/parallel/test-http-wget.js | 6 +- test/parallel/test-http-write-callbacks.js | 16 +- test/parallel/test-http-write-empty-string.js | 4 +- test/parallel/test-http-write-head.js | 4 +- test/parallel/test-http-zero-length-write.js | 20 +- test/parallel/test-http.js | 8 +- .../test-https-agent-disable-session-reuse.js | 4 +- test/parallel/test-https-agent-servername.js | 4 +- test/parallel/test-https-agent-sni.js | 6 +- test/parallel/test-https-agent.js | 6 +- test/parallel/test-https-byteswritten.js | 6 +- .../test-https-client-checkServerIdentity.js | 10 +- test/parallel/test-https-client-get-url.js | 4 +- test/parallel/test-https-client-reject.js | 14 +- test/parallel/test-https-client-resume.js | 12 +- test/parallel/test-https-close.js | 14 +- .../parallel/test-https-connecting-to-http.js | 4 +- test/parallel/test-https-drain.js | 16 +- test/parallel/test-https-eof-for-eom.js | 6 +- test/parallel/test-https-foafssl.js | 26 +-- test/parallel/test-https-host-headers.js | 2 +- .../test-https-localaddress-bind-error.js | 6 +- test/parallel/test-https-localaddress.js | 8 +- test/parallel/test-https-pfx.js | 8 +- test/parallel/test-https-req-split.js | 6 +- .../parallel/test-https-resume-after-renew.js | 15 +- .../parallel/test-https-set-timeout-server.js | 40 ++-- test/parallel/test-https-socket-options.js | 12 +- test/parallel/test-https-timeout-server-2.js | 6 +- test/parallel/test-icu-transcode.js | 2 +- test/parallel/test-listen-fd-cluster.js | 10 +- .../test-listen-fd-detached-inherit.js | 12 +- test/parallel/test-listen-fd-detached.js | 12 +- test/parallel/test-listen-fd-server.js | 8 +- test/parallel/test-memory-usage-emfile.js | 4 +- test/parallel/test-memory-usage.js | 2 +- ...test-microtask-queue-integration-domain.js | 8 +- .../test-microtask-queue-integration.js | 8 +- .../test-microtask-queue-run-domain.js | 4 +- ...st-microtask-queue-run-immediate-domain.js | 4 +- .../test-microtask-queue-run-immediate.js | 4 +- test/parallel/test-microtask-queue-run.js | 4 +- .../test-module-globalpaths-nodepath.js | 4 +- test/parallel/test-module-loading-error.js | 4 +- test/parallel/test-net-after-close.js | 4 +- .../test-net-better-error-messages-path.js | 4 +- test/parallel/test-net-binary.js | 10 +- test/parallel/test-net-bind-twice.js | 4 +- test/parallel/test-net-buffersize.js | 8 +- test/parallel/test-net-bytes-stats.js | 10 +- test/parallel/test-net-can-reset-timeout.js | 4 +- test/parallel/test-net-connect-buffer.js | 16 +- test/parallel/test-net-connect-local-error.js | 2 +- .../parallel/test-net-connect-options-ipv6.js | 6 +- test/parallel/test-net-connect-options.js | 4 +- test/parallel/test-net-create-connection.js | 4 +- test/parallel/test-net-dns-custom-lookup.js | 4 +- test/parallel/test-net-dns-error.js | 4 +- test/parallel/test-net-dns-lookup-skip.js | 4 +- test/parallel/test-net-dns-lookup.js | 2 +- test/parallel/test-net-during-close.js | 4 +- test/parallel/test-net-eaddrinuse.js | 4 +- test/parallel/test-net-end-without-connect.js | 2 +- test/parallel/test-net-error-twice.js | 8 +- test/parallel/test-net-internal.js | 2 +- test/parallel/test-net-keepalive.js | 6 +- test/parallel/test-net-large-string.js | 12 +- ...n-close-server-callback-is-not-function.js | 2 +- test/parallel/test-net-listen-close-server.js | 2 +- test/parallel/test-net-listen-error.js | 2 +- .../test-net-listen-exclusive-random-ports.js | 6 +- test/parallel/test-net-listen-shared-ports.js | 8 +- test/parallel/test-net-local-address-port.js | 5 +- test/parallel/test-net-localport.js | 4 +- .../test-net-pause-resume-connecting.js | 2 +- .../parallel/test-net-persistent-keepalive.js | 8 +- test/parallel/test-net-persistent-nodelay.js | 14 +- .../parallel/test-net-persistent-ref-unref.js | 12 +- test/parallel/test-net-pingpong.js | 6 +- test/parallel/test-net-pipe-connect-errors.js | 8 +- test/parallel/test-net-reconnect.js | 12 +- test/parallel/test-net-remote-address-port.js | 12 +- test/parallel/test-net-server-bind.js | 24 +-- test/parallel/test-net-server-close.js | 6 +- test/parallel/test-net-server-connections.js | 2 +- .../test-net-server-listen-remove-callback.js | 4 +- ...-connections-close-makes-more-available.js | 16 +- .../test-net-server-max-connections.js | 6 +- .../test-net-server-pause-on-connect.js | 4 +- .../test-net-server-unref-persistent.js | 2 +- test/parallel/test-net-server-unref.js | 2 +- .../parallel/test-net-socket-destroy-twice.js | 2 +- .../parallel/test-net-socket-local-address.js | 6 +- .../parallel/test-net-socket-timeout-unref.js | 2 +- test/parallel/test-net-stream.js | 14 +- test/parallel/test-net-write-after-close.js | 4 +- test/parallel/test-net-write-connect-write.js | 6 +- test/parallel/test-net-write-slow.js | 16 +- test/parallel/test-next-tick-domain.js | 2 +- .../test-next-tick-intentional-starvation.js | 10 +- test/parallel/test-next-tick-ordering.js | 6 +- test/parallel/test-next-tick-ordering2.js | 2 +- test/parallel/test-next-tick.js | 2 +- test/parallel/test-no-enter-tickcallback.js | 4 +- test/parallel/test-path-makelong.js | 4 +- test/parallel/test-path-parse-format.js | 2 +- test/parallel/test-path.js | 4 +- test/parallel/test-pipe-address.js | 2 +- test/parallel/test-pipe-return-val.js | 6 +- test/parallel/test-pipe-stream.js | 10 +- test/parallel/test-pipe-unref.js | 2 +- test/parallel/test-preload.js | 6 +- test/parallel/test-process-argv-0.js | 4 +- test/parallel/test-process-config.js | 4 +- test/parallel/test-process-exec-argv.js | 8 +- test/parallel/test-process-exit-code.js | 6 +- test/parallel/test-process-exit-recursive.js | 2 +- test/parallel/test-process-exit.js | 2 +- .../parallel/test-process-getactivehandles.js | 2 +- test/parallel/test-process-getgroups.js | 6 +- test/parallel/test-process-kill-null.js | 4 +- test/parallel/test-process-kill-pid.js | 6 +- test/parallel/test-process-next-tick.js | 4 +- test/parallel/test-process-raw-debug.js | 6 +- ...est-process-remove-all-signal-listeners.js | 2 +- test/parallel/test-process-versions.js | 4 +- test/parallel/test-process-wrap.js | 16 +- .../test-promises-unhandled-rejections.js | 161 ++++++++-------- ...promises-warning-on-unhandled-rejection.js | 2 +- .../test-querystring-maxKeys-non-finite.js | 6 +- test/parallel/test-querystring.js | 20 +- test/parallel/test-readdouble.js | 2 +- test/parallel/test-readfloat.js | 2 +- test/parallel/test-readint.js | 6 +- test/parallel/test-readline-interface.js | 28 +-- test/parallel/test-readline-keys.js | 6 +- test/parallel/test-readline-set-raw-mode.js | 12 +- .../test-readline-undefined-columns.js | 2 +- test/parallel/test-readuint.js | 6 +- test/parallel/test-regress-GH-1531.js | 4 +- test/parallel/test-regress-GH-1899.js | 4 +- test/parallel/test-regress-GH-2245.js | 2 +- test/parallel/test-regress-GH-3542.js | 2 +- test/parallel/test-regress-GH-3739.js | 4 +- test/parallel/test-regress-GH-4948.js | 10 +- test/parallel/test-regress-GH-5927.js | 8 +- test/parallel/test-regress-GH-746.js | 2 +- test/parallel/test-regress-GH-7511.js | 4 +- test/parallel/test-regress-GH-819.js | 2 +- test/parallel/test-regress-GH-node-9326.js | 2 +- test/parallel/test-repl-.save.load.js | 10 +- test/parallel/test-repl-autolibs.js | 6 +- test/parallel/test-repl-console.js | 2 +- test/parallel/test-repl-definecommand.js | 2 +- test/parallel/test-repl-end-emits-exit.js | 4 +- test/parallel/test-repl-harmony.js | 10 +- test/parallel/test-repl-history-perm.js | 2 +- test/parallel/test-repl-null.js | 2 +- test/parallel/test-repl-options.js | 6 +- test/parallel/test-repl-persistent-history.js | 2 +- test/parallel/test-repl-require.js | 2 +- test/parallel/test-repl-setprompt.js | 10 +- .../test-repl-syntax-error-handling.js | 7 +- test/parallel/test-repl-tab-complete.js | 6 +- test/parallel/test-repl-tab.js | 5 +- .../test-repl-unexpected-token-recoverable.js | 10 +- test/parallel/test-sigint-infinite-loop.js | 4 +- test/parallel/test-signal-handler.js | 2 +- test/parallel/test-signal-safety.js | 6 +- .../test-socket-write-after-fin-error.js | 14 +- test/parallel/test-socket-write-after-fin.js | 8 +- test/parallel/test-stdin-pipe-resume.js | 6 +- test/parallel/test-stdin-script-child.js | 2 +- ...out-cannot-be-closed-child-process-pipe.js | 6 +- test/parallel/test-stdout-stderr-reading.js | 12 +- test/parallel/test-stdout-to-file.js | 16 +- test/parallel/test-stream-base-no-abort.js | 2 +- test/parallel/test-stream-big-push.js | 6 +- test/parallel/test-stream-pipe-event.js | 6 +- test/parallel/test-stream-push-order.js | 8 +- test/parallel/test-stream-push-strings.js | 8 +- ...stream-readable-constructor-set-methods.js | 4 +- .../test-stream-readable-flow-recursion.js | 10 +- ...tream-transform-constructor-set-methods.js | 6 +- .../test-stream-transform-flush-data.js | 2 +- .../test-stream-transform-split-objectmode.js | 8 +- .../test-stream-unshift-empty-chunk.js | 16 +- test/parallel/test-stream-wrap.js | 6 +- ...stream-writable-change-default-encoding.js | 8 +- ...stream-writable-constructor-set-methods.js | 10 +- test/parallel/test-stream-writable-null.js | 12 +- test/parallel/test-stream-writev.js | 22 +-- ...est-stream2-base64-single-char-read-end.js | 11 +- test/parallel/test-stream2-compatibility.js | 6 +- test/parallel/test-stream2-decode-partial.js | 2 +- test/parallel/test-stream2-finish-pipe.js | 4 +- .../test-stream2-httpclient-response-end.js | 6 +- .../parallel/test-stream2-large-read-stall.js | 17 +- test/parallel/test-stream2-objects.js | 82 ++++----- .../test-stream2-pipe-error-once-listener.js | 8 +- test/parallel/test-stream2-push.js | 20 +- test/parallel/test-stream2-read-sync-stack.js | 8 +- ...st-stream2-readable-empty-buffer-no-eof.js | 8 +- .../test-stream2-readable-from-list.js | 20 +- .../test-stream2-readable-legacy-drain.js | 12 +- .../test-stream2-readable-non-empty-end.js | 20 +- .../test-stream2-readable-wrap-empty.js | 4 +- test/parallel/test-stream2-set-encoding.js | 78 ++++---- test/parallel/test-stream2-transform.js | 68 +++---- test/parallel/test-stream2-unpipe-leak.js | 8 +- test/parallel/test-stream2-writable.js | 89 ++++----- test/parallel/test-stream3-cork-end.js | 18 +- test/parallel/test-stream3-cork-uncork.js | 18 +- test/parallel/test-stream3-pause-then-read.js | 36 ++-- test/parallel/test-string-decoder-end.js | 18 +- test/parallel/test-string-decoder.js | 22 +-- test/parallel/test-stringbytes-external.js | 28 +-- test/parallel/test-sync-io-option.js | 6 +- test/parallel/test-tcp-wrap-connect.js | 22 +-- test/parallel/test-tcp-wrap.js | 10 +- test/parallel/test-timers-active.js | 4 +- test/parallel/test-timers-clearImmediate.js | 4 +- test/parallel/test-timers-immediate-queue.js | 2 +- test/parallel/test-timers-immediate.js | 3 +- test/parallel/test-timers-nested.js | 2 +- ...imeout-removes-other-socket-unref-timer.js | 2 +- test/parallel/test-timers-unref-active.js | 4 +- test/parallel/test-timers-unref-call.js | 6 +- test/parallel/test-timers-unref-leak.js | 8 +- ...emove-other-unref-timers-only-one-fires.js | 2 +- test/parallel/test-timers-unref.js | 4 +- ...test-timers-unrefd-interval-still-fires.js | 2 +- .../test-timers-unrefed-in-beforeexit.js | 2 +- test/parallel/test-timers.js | 8 +- test/parallel/test-tls-alert.js | 12 +- test/parallel/test-tls-alpn-server-client.js | 76 ++++---- .../test-tls-async-cb-after-socket-end.js | 14 +- test/parallel/test-tls-cert-regression.js | 6 +- test/parallel/test-tls-cipher-list.js | 2 +- test/parallel/test-tls-client-abort.js | 6 +- test/parallel/test-tls-client-abort2.js | 2 +- .../test-tls-client-default-ciphers.js | 2 +- test/parallel/test-tls-client-destroy-soon.js | 12 +- .../test-tls-client-getephemeralkeyinfo.js | 18 +- test/parallel/test-tls-client-mindhsize.js | 16 +- test/parallel/test-tls-client-resume.js | 12 +- test/parallel/test-tls-client-verify.js | 2 +- test/parallel/test-tls-close-error.js | 4 +- test/parallel/test-tls-close-notify.js | 4 +- test/parallel/test-tls-connect-no-host.js | 6 +- test/parallel/test-tls-connect-pipe.js | 8 +- .../test-tls-connect-stream-writes.js | 33 ++-- .../parallel/test-tls-delayed-attach-error.js | 10 +- test/parallel/test-tls-delayed-attach.js | 12 +- test/parallel/test-tls-dhe.js | 26 +-- test/parallel/test-tls-ecdh-disable.js | 6 +- test/parallel/test-tls-econnreset.js | 16 +- test/parallel/test-tls-env-bad-extra-ca.js | 4 +- test/parallel/test-tls-fast-writing.js | 20 +- .../test-tls-friendly-error-message.js | 2 +- test/parallel/test-tls-handshake-error.js | 4 +- test/parallel/test-tls-honorcipherorder.js | 16 +- test/parallel/test-tls-inception.js | 2 +- test/parallel/test-tls-invoke-queued.js | 6 +- test/parallel/test-tls-js-stream.js | 14 +- test/parallel/test-tls-legacy-onselect.js | 4 +- test/parallel/test-tls-max-send-fragment.js | 10 +- test/parallel/test-tls-multi-key.js | 10 +- test/parallel/test-tls-no-rsa-key.js | 6 +- test/parallel/test-tls-npn-server-client.js | 8 +- test/parallel/test-tls-over-http-tunnel.js | 16 +- test/parallel/test-tls-pause.js | 16 +- .../test-tls-peer-certificate-encoding.js | 8 +- .../test-tls-peer-certificate-multi-keys.js | 8 +- test/parallel/test-tls-pfx-gh-5100-regr.js | 2 +- test/parallel/test-tls-request-timeout.js | 6 +- test/parallel/test-tls-securepair-fiftharg.js | 2 +- test/parallel/test-tls-securepair-server.js | 22 +-- test/parallel/test-tls-session-cache.js | 8 +- test/parallel/test-tls-set-ciphers.js | 2 +- test/parallel/test-tls-sni-option.js | 14 +- test/parallel/test-tls-sni-server-client.js | 14 +- test/parallel/test-tls-wrap-timeout.js | 4 +- test/parallel/test-umask.js | 4 +- test/parallel/test-url.js | 22 +-- test/parallel/test-util-inspect.js | 80 ++++---- test/parallel/test-util-log.js | 6 +- test/parallel/test-v8-stats.js | 4 +- test/parallel/test-vm-basic.js | 12 +- test/parallel/test-vm-context-async-script.js | 4 +- .../test-vm-context-property-forwarding.js | 4 +- test/parallel/test-vm-context.js | 12 +- .../test-vm-create-and-run-in-context.js | 6 +- .../test-vm-create-context-accessors.js | 6 +- test/parallel/test-vm-create-context-arg.js | 2 +- ...st-vm-create-context-circular-reference.js | 2 +- test/parallel/test-vm-cross-context.js | 2 +- test/parallel/test-vm-function-declaration.js | 6 +- .../test-vm-global-define-property.js | 8 +- test/parallel/test-vm-global-identity.js | 6 +- test/parallel/test-vm-harmony-symbols.js | 2 +- test/parallel/test-vm-is-context.js | 2 +- .../test-vm-new-script-new-context.js | 6 +- .../test-vm-new-script-this-context.js | 2 +- test/parallel/test-vm-proxies.js | 2 +- test/parallel/test-vm-run-in-new-context.js | 6 +- test/parallel/test-vm-static-this.js | 11 +- test/parallel/test-vm-syntax-error-message.js | 4 +- test/parallel/test-vm-timeout.js | 2 +- test/parallel/test-whatwg-url-searchparams.js | 2 +- test/parallel/test-whatwg-url-setters.js | 2 +- test/parallel/test-writedouble.js | 2 +- test/parallel/test-writefloat.js | 2 +- test/parallel/test-writeint.js | 6 +- test/parallel/test-writeuint.js | 14 +- test/parallel/test-zerolengthbufferbug.js | 4 +- .../parallel/test-zlib-convenience-methods.js | 4 +- test/parallel/test-zlib-flush-drain.js | 6 +- test/parallel/test-zlib-flush.js | 3 +- test/parallel/test-zlib-from-gzip.js | 2 +- test/parallel/test-zlib-from-string.js | 2 +- test/parallel/test-zlib-invalid-input.js | 2 +- test/parallel/test-zlib-params.js | 2 +- test/parallel/test-zlib-random-byte-pipes.js | 12 +- test/parallel/test-zlib-write-after-flush.js | 2 +- test/parallel/test-zlib-zero-byte.js | 2 +- test/parallel/test-zlib.js | 67 +++---- test/pseudo-tty/no_dropped_stdio.js | 2 +- test/pseudo-tty/no_interleaved_stdio.js | 2 +- test/pummel/test-abort-fatal-error.js | 2 +- test/pummel/test-crypto-dh.js | 18 +- test/pummel/test-dh-regr.js | 4 +- test/pummel/test-dtrace-jsstack.js | 26 +-- test/pummel/test-exec.js | 16 +- test/pummel/test-fs-watch-file-slow.js | 6 +- test/pummel/test-fs-watch-file.js | 24 +-- test/pummel/test-fs-watch-non-recursive.js | 8 +- test/pummel/test-http-client-reconnect-bug.js | 6 +- .../test-http-many-keep-alive-connections.js | 12 +- test/pummel/test-http-upload-timeout.js | 6 +- test/pummel/test-https-ci-reneg-attack.js | 20 +- test/pummel/test-https-large-response.js | 8 +- test/pummel/test-https-no-reader.js | 10 +- test/pummel/test-net-connect-econnrefused.js | 13 +- test/pummel/test-net-connect-memleak.js | 6 +- test/pummel/test-net-many-clients.js | 18 +- test/pummel/test-net-pause.js | 8 +- test/pummel/test-net-pingpong-delay.js | 12 +- test/pummel/test-net-pingpong.js | 14 +- test/pummel/test-net-throttle.js | 12 +- test/pummel/test-net-timeout.js | 14 +- test/pummel/test-net-timeout2.js | 10 +- test/pummel/test-net-write-callbacks.js | 14 +- test/pummel/test-next-tick-infinite-calls.js | 2 +- test/pummel/test-process-hrtime.js | 6 +- test/pummel/test-process-uptime.js | 4 +- test/pummel/test-regress-GH-814.js | 16 +- test/pummel/test-regress-GH-814_2.js | 16 +- test/pummel/test-regress-GH-892.js | 20 +- test/pummel/test-stream-pipe-multi.js | 24 +-- test/pummel/test-stream2-basic.js | 172 +++++++++--------- test/pummel/test-timer-wrap.js | 6 +- test/pummel/test-timer-wrap2.js | 2 +- test/pummel/test-timers.js | 30 +-- test/pummel/test-tls-ci-reneg-attack.js | 18 +- test/pummel/test-tls-connect-memleak.js | 6 +- test/pummel/test-tls-securepair-client.js | 28 +-- test/pummel/test-tls-server-large-request.js | 10 +- test/pummel/test-tls-session-timeout.js | 38 ++-- test/pummel/test-tls-throttle.js | 12 +- test/pummel/test-vm-memleak.js | 12 +- .../sequential/test-child-process-execsync.js | 23 +-- test/sequential/test-debugger-debug-brk.js | 4 +- test/sequential/test-deprecation-flags.js | 2 +- .../test-fs-readfile-tostring-fail.js | 2 +- test/sequential/test-http-regr-gh-2928.js | 8 +- test/sequential/test-module-loading.js | 8 +- test/sequential/test-net-GH-5504.js | 10 +- test/sequential/test-regress-GH-1697.js | 10 +- test/sequential/test-regress-GH-1726.js | 6 +- test/sequential/test-regress-GH-4015.js | 4 +- test/sequential/test-regress-GH-4027.js | 2 +- test/sequential/test-regress-GH-784.js | 16 +- test/sequential/test-regress-GH-877.js | 20 +- test/sequential/test-repl-timeout-throw.js | 6 +- .../test-require-cache-without-stat.js | 10 +- test/sequential/test-stream2-fs.js | 12 +- test/sequential/test-stream2-stderr-sync.js | 10 +- .../test-timers-blocking-callback.js | 6 +- test/sequential/test-vm-timeout-rethrow.js | 12 +- test/timers/test-timers-reliability.js | 10 +- 732 files changed, 3393 insertions(+), 3374 deletions(-) diff --git a/test/addons/buffer-free-callback/test.js b/test/addons/buffer-free-callback/test.js index 8dbc2d57725c56..d25130a905ac90 100644 --- a/test/addons/buffer-free-callback/test.js +++ b/test/addons/buffer-free-callback/test.js @@ -5,8 +5,8 @@ const common = require('../../common'); const binding = require(`./build/${common.buildType}/binding`); function check(size, alignment, offset) { - var buf = binding.alloc(size, alignment, offset); - var slice = buf.slice(size >>> 1); + let buf = binding.alloc(size, alignment, offset); + let slice = buf.slice(size >>> 1); buf = null; binding.check(slice); diff --git a/test/addons/load-long-path/test.js b/test/addons/load-long-path/test.js index ea0783331b058f..73d85a75a097a2 100644 --- a/test/addons/load-long-path/test.js +++ b/test/addons/load-long-path/test.js @@ -14,9 +14,9 @@ common.refreshTmpDir(); // make a path that is more than 260 chars long. // Any given folder cannot have a name longer than 260 characters, // so create 10 nested folders each with 30 character long names. -var addonDestinationDir = path.resolve(common.tmpDir); +let addonDestinationDir = path.resolve(common.tmpDir); -for (var i = 0; i < 10; i++) { +for (let i = 0; i < 10; i++) { addonDestinationDir = path.join(addonDestinationDir, 'x'.repeat(30)); fs.mkdirSync(addonDestinationDir); } @@ -28,7 +28,7 @@ const addonPath = path.join(__dirname, const addonDestinationPath = path.join(addonDestinationDir, 'binding.node'); // Copy binary to long path destination -var contents = fs.readFileSync(addonPath); +const contents = fs.readFileSync(addonPath); fs.writeFileSync(addonDestinationPath, contents); // Attempt to load at long path destination diff --git a/test/addons/make-callback-recurse/test.js b/test/addons/make-callback-recurse/test.js index 0145a142e40f09..46b1327d7dedac 100644 --- a/test/addons/make-callback-recurse/test.js +++ b/test/addons/make-callback-recurse/test.js @@ -65,7 +65,7 @@ assert.throws(function() { results.push(2); setImmediate(common.mustCall(function() { - for (var i = 0; i < results.length; i++) { + for (let i = 0; i < results.length; i++) { assert.strictEqual(results[i], i, `verifyExecutionOrder(${arg}) results: ${results}`); } diff --git a/test/addons/repl-domain-abort/test.js b/test/addons/repl-domain-abort/test.js index 1f30f0f9beae54..95536f99711324 100644 --- a/test/addons/repl-domain-abort/test.js +++ b/test/addons/repl-domain-abort/test.js @@ -4,27 +4,27 @@ const assert = require('assert'); const repl = require('repl'); const stream = require('stream'); const path = require('path'); -var buildType = process.config.target_defaults.default_configuration; -var buildPath = path.join(__dirname, 'build', buildType, 'binding'); +const buildType = process.config.target_defaults.default_configuration; +let buildPath = path.join(__dirname, 'build', buildType, 'binding'); // On Windows, escape backslashes in the path before passing it to REPL. if (common.isWindows) buildPath = buildPath.replace(/\\/g, '/'); -var cb_ran = false; +let cb_ran = false; process.on('exit', function() { assert(cb_ran); console.log('ok'); }); -var lines = [ +const lines = [ // This line shouldn't cause an assertion error. 'require(\'' + buildPath + '\')' + // Log output to double check callback ran. '.method(function() { console.log(\'cb_ran\'); });', ]; -var dInput = new stream.Readable(); -var dOutput = new stream.Writable(); +const dInput = new stream.Readable(); +const dOutput = new stream.Writable(); dInput._read = function _read(size) { while (lines.length > 0 && this.push(lines.shift())); @@ -38,7 +38,7 @@ dOutput._write = function _write(chunk, encoding, cb) { cb(); }; -var options = { +const options = { input: dInput, output: dOutput, terminal: false, diff --git a/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-at-max.js b/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-at-max.js index 2ce695852e25ae..5dd727f8ffddd3 100644 --- a/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-at-max.js +++ b/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-at-max.js @@ -14,8 +14,9 @@ if (!common.enoughTestMem) { return; } +let buf; try { - var buf = Buffer.allocUnsafe(kStringMaxLength); + buf = Buffer.allocUnsafe(kStringMaxLength); } catch (e) { // If the exception is not due to memory confinement then rethrow it. if (e.message !== 'Array buffer allocation failed') throw (e); diff --git a/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-1-ascii.js b/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-1-ascii.js index 4be525d79fa39e..2466c8ec42ed57 100644 --- a/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-1-ascii.js +++ b/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-1-ascii.js @@ -14,8 +14,9 @@ if (!common.enoughTestMem) { // v8::String::kMaxLength defined in v8.h const kStringMaxLength = process.binding('buffer').kStringMaxLength; +let buf; try { - var buf = Buffer.allocUnsafe(kStringMaxLength + 1); + buf = Buffer.allocUnsafe(kStringMaxLength + 1); } catch (e) { // If the exception is not due to memory confinement then rethrow it. if (e.message !== 'Array buffer allocation failed') throw (e); diff --git a/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-1-base64.js b/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-1-base64.js index 47426bf6352bbb..16f0f5392e5206 100644 --- a/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-1-base64.js +++ b/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-1-base64.js @@ -14,8 +14,9 @@ if (!common.enoughTestMem) { // v8::String::kMaxLength defined in v8.h const kStringMaxLength = process.binding('buffer').kStringMaxLength; +let buf; try { - var buf = Buffer.allocUnsafe(kStringMaxLength + 1); + buf = Buffer.allocUnsafe(kStringMaxLength + 1); } catch (e) { // If the exception is not due to memory confinement then rethrow it. if (e.message !== 'Array buffer allocation failed') throw (e); diff --git a/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-1-binary.js b/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-1-binary.js index 51324a3f337731..1028706b1d1aa9 100644 --- a/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-1-binary.js +++ b/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-1-binary.js @@ -14,8 +14,9 @@ if (!common.enoughTestMem) { // v8::String::kMaxLength defined in v8.h const kStringMaxLength = process.binding('buffer').kStringMaxLength; +let buf; try { - var buf = Buffer.allocUnsafe(kStringMaxLength + 1); + buf = Buffer.allocUnsafe(kStringMaxLength + 1); } catch (e) { // If the exception is not due to memory confinement then rethrow it. if (e.message !== 'Array buffer allocation failed') throw (e); @@ -33,7 +34,7 @@ assert.throws(function() { buf.toString('latin1'); }, /"toString\(\)" failed/); -var maxString = buf.toString('latin1', 1); +let maxString = buf.toString('latin1', 1); assert.strictEqual(maxString.length, kStringMaxLength); // Free the memory early instead of at the end of the next assignment maxString = undefined; diff --git a/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-1-hex.js b/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-1-hex.js index ae6966d0545194..caf6112011e2a8 100644 --- a/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-1-hex.js +++ b/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-1-hex.js @@ -14,8 +14,9 @@ if (!common.enoughTestMem) { // v8::String::kMaxLength defined in v8.h const kStringMaxLength = process.binding('buffer').kStringMaxLength; +let buf; try { - var buf = Buffer.allocUnsafe(kStringMaxLength + 1); + buf = Buffer.allocUnsafe(kStringMaxLength + 1); } catch (e) { // If the exception is not due to memory confinement then rethrow it. if (e.message !== 'Array buffer allocation failed') throw (e); diff --git a/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-1-utf8.js b/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-1-utf8.js index cea175aa93ab5c..4d3199a033e6d5 100644 --- a/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-1-utf8.js +++ b/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-1-utf8.js @@ -14,8 +14,9 @@ if (!common.enoughTestMem) { // v8::String::kMaxLength defined in v8.h const kStringMaxLength = process.binding('buffer').kStringMaxLength; +let buf; try { - var buf = Buffer.allocUnsafe(kStringMaxLength + 1); + buf = Buffer.allocUnsafe(kStringMaxLength + 1); } catch (e) { // If the exception is not due to memory confinement then rethrow it. if (e.message !== 'Array buffer allocation failed') throw (e); diff --git a/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-2.js b/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-2.js index 0fab606e4663ec..786d0b679895e1 100644 --- a/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-2.js +++ b/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-2.js @@ -14,8 +14,9 @@ if (!common.enoughTestMem) { // v8::String::kMaxLength defined in v8.h const kStringMaxLength = process.binding('buffer').kStringMaxLength; +let buf; try { - var buf = Buffer.allocUnsafe(kStringMaxLength + 2); + buf = Buffer.allocUnsafe(kStringMaxLength + 2); } catch (e) { // If the exception is not due to memory confinement then rethrow it. if (e.message !== 'Array buffer allocation failed') throw (e); diff --git a/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max.js b/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max.js index f984179525abeb..36b0d4174a030b 100644 --- a/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max.js +++ b/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max.js @@ -14,8 +14,9 @@ if (!common.enoughTestMem) { // v8::String::kMaxLength defined in v8.h const kStringMaxLength = process.binding('buffer').kStringMaxLength; +let buf; try { - var buf = Buffer.allocUnsafe(kStringMaxLength * 2 + 2); + buf = Buffer.allocUnsafe(kStringMaxLength * 2 + 2); } catch (e) { // If the exception is not due to memory confinement then rethrow it. if (e.message !== 'Array buffer allocation failed') throw (e); diff --git a/test/common.js b/test/common.js index 5ee9a5ce314793..05ef4c9d682c0d 100644 --- a/test/common.js +++ b/test/common.js @@ -209,7 +209,7 @@ exports.hasIPv6 = Object.keys(ifaces).some(function(name) { * the process aborts. */ exports.childShouldThrowAndAbort = function() { - var testCmd = ''; + let testCmd = ''; if (!exports.isWindows) { // Do not create core files, as it can take a lot of disk space on // continuous testing and developers' machines diff --git a/test/debugger/helper-debugger-repl.js b/test/debugger/helper-debugger-repl.js index d6c3e5ca9e609a..38c65a03fa590d 100644 --- a/test/debugger/helper-debugger-repl.js +++ b/test/debugger/helper-debugger-repl.js @@ -4,12 +4,12 @@ const assert = require('assert'); const spawn = require('child_process').spawn; process.env.NODE_DEBUGGER_TIMEOUT = 2000; -var port = common.PORT; +const port = common.PORT; -var child; -var buffer = ''; -var expected = []; -var quit; +let child; +let buffer = ''; +const expected = []; +let quit; function startDebugger(scriptToDebug) { scriptToDebug = process.env.NODE_DEBUGGER_TEST_SCRIPT || @@ -34,23 +34,23 @@ function startDebugger(scriptToDebug) { console.log(line); assert.ok(expected.length > 0, 'Got unexpected line: ' + line); - var expectedLine = expected[0].lines.shift(); + const expectedLine = expected[0].lines.shift(); assert.ok(line.match(expectedLine) !== null, line + ' != ' + expectedLine); if (expected[0].lines.length === 0) { - var callback = expected[0].callback; + const callback = expected[0].callback; expected.shift(); callback && callback(); } }); - var childClosed = false; + let childClosed = false; child.on('close', function(code) { assert(!code); childClosed = true; }); - var quitCalled = false; + let quitCalled = false; quit = function() { if (quitCalled || childClosed) return; quitCalled = true; @@ -60,7 +60,7 @@ function startDebugger(scriptToDebug) { setTimeout(function() { console.error('dying badly buffer=%j', buffer); - var err = 'Timeout'; + let err = 'Timeout'; if (expected.length > 0 && expected[0].lines) { err = err + '. Expected: ' + expected[0].lines.shift(); } @@ -95,7 +95,7 @@ function addTest(input, output) { child.stdin.write(expected[0].input + '\n'); if (!expected[0].lines) { - var callback = expected[0].callback; + const callback = expected[0].callback; expected.shift(); callback && callback(); @@ -107,17 +107,17 @@ function addTest(input, output) { expected.push({input: input, lines: output, callback: next}); } -var handshakeLines = [ +const handshakeLines = [ /listening on /, /connecting.* ok/ ]; -var initialBreakLines = [ +const initialBreakLines = [ /break in .*:1/, /1/, /2/, /3/ ]; -var initialLines = handshakeLines.concat(initialBreakLines); +const initialLines = handshakeLines.concat(initialBreakLines); // Process initial lines addTest(null, initialLines); diff --git a/test/debugger/test-debugger-repl-restart.js b/test/debugger/test-debugger-repl-restart.js index 7dbef4288a6f44..f5de9f5ee95778 100644 --- a/test/debugger/test-debugger-repl-restart.js +++ b/test/debugger/test-debugger-repl-restart.js @@ -3,13 +3,13 @@ require('../common'); const repl = require('./helper-debugger-repl.js'); repl.startDebugger('breakpoints.js'); -var linesWithBreakpoint = [ +const linesWithBreakpoint = [ /1/, /2/, /3/, /4/, /5/, /\* 6/ ]; // We slice here, because addTest will change the given array. repl.addTest('sb(6)', linesWithBreakpoint.slice()); -var initialLines = repl.initialLines.slice(); +const initialLines = repl.initialLines.slice(); initialLines.splice(2, 0, /Restoring/, /Warning/); // Restart the debugged script diff --git a/test/debugger/test-debugger-repl-term.js b/test/debugger/test-debugger-repl-term.js index 8c44372f681672..4932df12e713bb 100644 --- a/test/debugger/test-debugger-repl-term.js +++ b/test/debugger/test-debugger-repl-term.js @@ -6,7 +6,7 @@ const repl = require('./helper-debugger-repl.js'); repl.startDebugger('breakpoints.js'); -var addTest = repl.addTest; +const addTest = repl.addTest; // next addTest('n', [ diff --git a/test/debugger/test-debugger-repl-utf8.js b/test/debugger/test-debugger-repl-utf8.js index 1af75840f5a6cf..90214158884371 100644 --- a/test/debugger/test-debugger-repl-utf8.js +++ b/test/debugger/test-debugger-repl-utf8.js @@ -1,6 +1,6 @@ 'use strict'; const common = require('../common'); -var script = common.fixturesDir + '/breakpoints_utf8.js'; +const script = common.fixturesDir + '/breakpoints_utf8.js'; process.env.NODE_DEBUGGER_TEST_SCRIPT = script; require('./test-debugger-repl.js'); diff --git a/test/debugger/test-debugger-repl.js b/test/debugger/test-debugger-repl.js index 0725348e56e477..32dbfa22c0d3a9 100644 --- a/test/debugger/test-debugger-repl.js +++ b/test/debugger/test-debugger-repl.js @@ -4,7 +4,7 @@ const repl = require('./helper-debugger-repl.js'); repl.startDebugger('breakpoints.js'); -var addTest = repl.addTest; +const addTest = repl.addTest; // Next addTest('n', [ diff --git a/test/gc/test-http-client-connaborted.js b/test/gc/test-http-client-connaborted.js index 071baf738ee9d3..6ff2a282d89c98 100644 --- a/test/gc/test-http-client-connaborted.js +++ b/test/gc/test-http-client-connaborted.js @@ -18,7 +18,7 @@ let countGC = 0; console.log('We should do ' + todo + ' requests'); -var server = http.createServer(serverHandler); +const server = http.createServer(serverHandler); server.listen(0, getall); function getall() { @@ -31,7 +31,7 @@ function getall() { statusLater(); } - var req = http.get({ + const req = http.get({ hostname: 'localhost', pathname: '/', port: server.address().port @@ -44,14 +44,14 @@ function getall() { setImmediate(getall); } -for (var i = 0; i < 10; i++) +for (let i = 0; i < 10; i++) getall(); function afterGC() { countGC++; } -var timer; +let timer; function statusLater() { global.gc(); if (timer) clearTimeout(timer); diff --git a/test/gc/test-http-client-onerror.js b/test/gc/test-http-client-onerror.js index a2ef0fa4bee9b7..b17ab428a2ccd7 100644 --- a/test/gc/test-http-client-onerror.js +++ b/test/gc/test-http-client-onerror.js @@ -20,7 +20,7 @@ let countGC = 0; console.log('We should do ' + todo + ' requests'); -var server = http.createServer(serverHandler); +const server = http.createServer(serverHandler); server.listen(0, runTest); function getall() { @@ -37,7 +37,7 @@ function getall() { throw er; } - var req = http.get({ + const req = http.get({ hostname: 'localhost', pathname: '/', port: server.address().port @@ -51,7 +51,7 @@ function getall() { } function runTest() { - for (var i = 0; i < 10; i++) + for (let i = 0; i < 10; i++) getall(); } @@ -59,7 +59,7 @@ function afterGC() { countGC++; } -var timer; +let timer; function statusLater() { global.gc(); if (timer) clearTimeout(timer); diff --git a/test/gc/test-http-client-timeout.js b/test/gc/test-http-client-timeout.js index 27baf837ca8282..fb4e8ba0f7058d 100644 --- a/test/gc/test-http-client-timeout.js +++ b/test/gc/test-http-client-timeout.js @@ -22,7 +22,7 @@ let countGC = 0; console.log('We should do ' + todo + ' requests'); -var server = http.createServer(serverHandler); +const server = http.createServer(serverHandler); server.listen(0, getall); function getall() { @@ -36,7 +36,7 @@ function getall() { statusLater(); } - var req = http.get({ + const req = http.get({ hostname: 'localhost', pathname: '/', port: server.address().port @@ -53,14 +53,14 @@ function getall() { setImmediate(getall); } -for (var i = 0; i < 10; i++) +for (let i = 0; i < 10; i++) getall(); function afterGC() { countGC++; } -var timer; +let timer; function statusLater() { global.gc(); if (timer) clearTimeout(timer); diff --git a/test/gc/test-http-client.js b/test/gc/test-http-client.js index 06bd08b2651d1b..f81cab0b09d2c2 100644 --- a/test/gc/test-http-client.js +++ b/test/gc/test-http-client.js @@ -18,7 +18,7 @@ let countGC = 0; console.log('We should do ' + todo + ' requests'); -var server = http.createServer(serverHandler); +const server = http.createServer(serverHandler); server.listen(0, getall); @@ -34,7 +34,7 @@ function getall() { res.on('end', global.gc); } - var req = http.get({ + const req = http.get({ hostname: 'localhost', pathname: '/', port: server.address().port @@ -47,7 +47,7 @@ function getall() { setImmediate(getall); } -for (var i = 0; i < 10; i++) +for (let i = 0; i < 10; i++) getall(); function afterGC() { diff --git a/test/gc/test-net-timeout.js b/test/gc/test-net-timeout.js index 9bc19a04256108..b8ea8e2089c439 100644 --- a/test/gc/test-net-timeout.js +++ b/test/gc/test-net-timeout.js @@ -7,14 +7,13 @@ require('../common'); function serverHandler(sock) { sock.setTimeout(120000); sock.resume(); - var timer; sock.on('close', function() { clearTimeout(timer); }); sock.on('error', function(err) { assert.strictEqual(err.code, 'ECONNRESET'); }); - timer = setTimeout(function() { + const timer = setTimeout(function() { sock.end('hello\n'); }, 100); } @@ -29,7 +28,7 @@ let countGC = 0; console.log('We should do ' + todo + ' requests'); -var server = net.createServer(serverHandler); +const server = net.createServer(serverHandler); server.listen(0, getall); function getall() { @@ -50,7 +49,7 @@ function getall() { setImmediate(getall); } -for (var i = 0; i < 10; i++) +for (let i = 0; i < 10; i++) getall(); function afterGC() { diff --git a/test/inspector/inspector-helper.js b/test/inspector/inspector-helper.js index 3e517123fe27f9..e22ca87dff7858 100644 --- a/test/inspector/inspector-helper.js +++ b/test/inspector/inspector-helper.js @@ -110,7 +110,7 @@ function makeBufferingDataCallback(dataCallback) { buffer = Buffer.alloc(0); else buffer = Buffer.from(lines.pop(), 'utf8'); - for (var line of lines) + for (const line of lines) dataCallback(line); }; } @@ -222,7 +222,7 @@ TestSession.prototype.sendInspectorCommands = function(commands) { }; TestSession.prototype.createCallbackWithTimeout_ = function(message) { - var promise = new Promise((resolve) => { + const promise = new Promise((resolve) => { this.enqueue((callback) => { const timeoutId = timeout(message); resolve(() => { diff --git a/test/internet/test-dgram-multicast-multi-process.js b/test/internet/test-dgram-multicast-multi-process.js index de6bf874ed874c..46f47a5982977e 100644 --- a/test/internet/test-dgram-multicast-multi-process.js +++ b/test/internet/test-dgram-multicast-multi-process.js @@ -13,6 +13,7 @@ const messages = [ ]; const workers = {}; const listeners = 3; +let listening, sendSocket, done, timer, dead; // Skip test in FreeBSD jails. @@ -76,10 +77,10 @@ function launchChildProcess(index) { Object.keys(workers).forEach(function(pid) { const worker = workers[pid]; - var count = 0; + let count = 0; worker.messagesReceived.forEach(function(buf) { - for (var i = 0; i < messages.length; ++i) { + for (let i = 0; i < messages.length; ++i) { if (buf.toString() === messages[i].toString()) { count++; break; @@ -110,13 +111,13 @@ function killChildren(children) { } if (process.argv[2] !== 'child') { - var listening = 0; - var dead = 0; - var i = 0; - var done = 0; + listening = 0; + dead = 0; + let i = 0; + done = 0; // Exit the test if it doesn't succeed within TIMEOUT. - var timer = setTimeout(function() { + timer = setTimeout(function() { console.error('[PARENT] Responses were not received within %d ms.', TIMEOUT); console.error('[PARENT] Fail'); @@ -127,11 +128,11 @@ if (process.argv[2] !== 'child') { }, TIMEOUT); // Launch child processes. - for (var x = 0; x < listeners; x++) { + for (let x = 0; x < listeners; x++) { launchChildProcess(x); } - var sendSocket = dgram.createSocket('udp4'); + sendSocket = dgram.createSocket('udp4'); // The socket is actually created async now. sendSocket.on('listening', function() { diff --git a/test/internet/test-dgram-send-cb-quelches-error.js b/test/internet/test-dgram-send-cb-quelches-error.js index e20c8e107081cd..abcc36859b96d9 100644 --- a/test/internet/test-dgram-send-cb-quelches-error.js +++ b/test/internet/test-dgram-send-cb-quelches-error.js @@ -1,12 +1,12 @@ 'use strict'; const common = require('../common'); -var mustCall = common.mustCall; +const mustCall = common.mustCall; const assert = require('assert'); const dgram = require('dgram'); const dns = require('dns'); -var socket = dgram.createSocket('udp4'); -var buffer = Buffer.from('gary busey'); +const socket = dgram.createSocket('udp4'); +const buffer = Buffer.from('gary busey'); dns.setServers([]); diff --git a/test/internet/test-dns-cares-domains.js b/test/internet/test-dns-cares-domains.js index 61ac679274d8b3..5328d7e3d97925 100644 --- a/test/internet/test-dns-cares-domains.js +++ b/test/internet/test-dns-cares-domains.js @@ -4,7 +4,7 @@ const assert = require('assert'); const dns = require('dns'); const domain = require('domain'); -var methods = [ +const methods = [ 'resolve4', 'resolve6', 'resolveCname', @@ -18,7 +18,7 @@ var methods = [ ]; methods.forEach(function(method) { - var d = domain.create(); + const d = domain.create(); d.run(function() { dns[method]('google.com', function() { assert.strictEqual(process.domain, d, method + ' retains domain'); diff --git a/test/internet/test-dns.js b/test/internet/test-dns.js index be3f9b0469ed2e..8a857c030af39e 100644 --- a/test/internet/test-dns.js +++ b/test/internet/test-dns.js @@ -15,7 +15,7 @@ const queue = []; function TEST(f) { function next() { - var f = queue.shift(); + const f = queue.shift(); if (f) { running = true; console.log(f.name); @@ -44,7 +44,7 @@ function checkWrap(req) { TEST(function test_reverse_bogus(done) { - var error; + let error; try { dns.reverse('bogus ip', function() { @@ -61,12 +61,12 @@ TEST(function test_reverse_bogus(done) { }); TEST(function test_resolve4_ttl(done) { - var req = dns.resolve4('google.com', { ttl: true }, function(err, result) { + const req = dns.resolve4('google.com', { ttl: true }, function(err, result) { assert.ifError(err); assert.ok(result.length > 0); - for (var i = 0; i < result.length; i++) { - var item = result[i]; + for (let i = 0; i < result.length; i++) { + const item = result[i]; assert.ok(item); assert.strictEqual(typeof item, 'object'); assert.strictEqual(typeof item.ttl, 'number'); @@ -82,12 +82,12 @@ TEST(function test_resolve4_ttl(done) { }); TEST(function test_resolve6_ttl(done) { - var req = dns.resolve6('google.com', { ttl: true }, function(err, result) { + const req = dns.resolve6('google.com', { ttl: true }, function(err, result) { assert.ifError(err); assert.ok(result.length > 0); - for (var i = 0; i < result.length; i++) { - var item = result[i]; + for (let i = 0; i < result.length; i++) { + const item = result[i]; assert.ok(item); assert.strictEqual(typeof item, 'object'); assert.strictEqual(typeof item.ttl, 'number'); @@ -103,12 +103,12 @@ TEST(function test_resolve6_ttl(done) { }); TEST(function test_resolveMx(done) { - var req = dns.resolveMx('gmail.com', function(err, result) { + const req = dns.resolveMx('gmail.com', function(err, result) { assert.ifError(err); assert.ok(result.length > 0); - for (var i = 0; i < result.length; i++) { - var item = result[i]; + for (let i = 0; i < result.length; i++) { + const item = result[i]; assert.ok(item); assert.strictEqual(typeof item, 'object'); @@ -125,7 +125,7 @@ TEST(function test_resolveMx(done) { }); TEST(function test_resolveMx_failure(done) { - var req = dns.resolveMx('something.invalid', function(err, result) { + const req = dns.resolveMx('something.invalid', function(err, result) { assert.ok(err instanceof Error); assert.strictEqual(err.errno, 'ENOTFOUND'); @@ -138,12 +138,12 @@ TEST(function test_resolveMx_failure(done) { }); TEST(function test_resolveNs(done) { - var req = dns.resolveNs('rackspace.com', function(err, names) { + const req = dns.resolveNs('rackspace.com', function(err, names) { assert.ifError(err); assert.ok(names.length > 0); - for (var i = 0; i < names.length; i++) { - var name = names[i]; + for (let i = 0; i < names.length; i++) { + const name = names[i]; assert.ok(name); assert.strictEqual(typeof name, 'string'); } @@ -155,7 +155,7 @@ TEST(function test_resolveNs(done) { }); TEST(function test_resolveNs_failure(done) { - var req = dns.resolveNs('something.invalid', function(err, result) { + const req = dns.resolveNs('something.invalid', function(err, result) { assert.ok(err instanceof Error); assert.strictEqual(err.errno, 'ENOTFOUND'); @@ -168,12 +168,12 @@ TEST(function test_resolveNs_failure(done) { }); TEST(function test_resolveSrv(done) { - var req = dns.resolveSrv('_jabber._tcp.google.com', function(err, result) { + const req = dns.resolveSrv('_jabber._tcp.google.com', function(err, result) { assert.ifError(err); assert.ok(result.length > 0); - for (var i = 0; i < result.length; i++) { - var item = result[i]; + for (let i = 0; i < result.length; i++) { + const item = result[i]; assert.ok(item); assert.strictEqual(typeof item, 'object'); @@ -192,7 +192,7 @@ TEST(function test_resolveSrv(done) { }); TEST(function test_resolveSrv_failure(done) { - var req = dns.resolveSrv('something.invalid', function(err, result) { + const req = dns.resolveSrv('something.invalid', function(err, result) { assert.ok(err instanceof Error); assert.strictEqual(err.errno, 'ENOTFOUND'); @@ -205,12 +205,12 @@ TEST(function test_resolveSrv_failure(done) { }); TEST(function test_resolvePtr(done) { - var req = dns.resolvePtr('8.8.8.8.in-addr.arpa', function(err, result) { + const req = dns.resolvePtr('8.8.8.8.in-addr.arpa', function(err, result) { assert.ifError(err); assert.ok(result.length > 0); - for (var i = 0; i < result.length; i++) { - var item = result[i]; + for (let i = 0; i < result.length; i++) { + const item = result[i]; assert.ok(item); assert.strictEqual(typeof item, 'string'); } @@ -222,7 +222,7 @@ TEST(function test_resolvePtr(done) { }); TEST(function test_resolvePtr_failure(done) { - var req = dns.resolvePtr('something.invalid', function(err, result) { + const req = dns.resolvePtr('something.invalid', function(err, result) { assert.ok(err instanceof Error); assert.strictEqual(err.errno, 'ENOTFOUND'); @@ -235,12 +235,12 @@ TEST(function test_resolvePtr_failure(done) { }); TEST(function test_resolveNaptr(done) { - var req = dns.resolveNaptr('sip2sip.info', function(err, result) { + const req = dns.resolveNaptr('sip2sip.info', function(err, result) { assert.ifError(err); assert.ok(result.length > 0); - for (var i = 0; i < result.length; i++) { - var item = result[i]; + for (let i = 0; i < result.length; i++) { + const item = result[i]; assert.ok(item); assert.strictEqual(typeof item, 'object'); @@ -259,7 +259,7 @@ TEST(function test_resolveNaptr(done) { }); TEST(function test_resolveNaptr_failure(done) { - var req = dns.resolveNaptr('something.invalid', function(err, result) { + const req = dns.resolveNaptr('something.invalid', function(err, result) { assert.ok(err instanceof Error); assert.strictEqual(err.errno, 'ENOTFOUND'); @@ -272,7 +272,7 @@ TEST(function test_resolveNaptr_failure(done) { }); TEST(function test_resolveSoa(done) { - var req = dns.resolveSoa('nodejs.org', function(err, result) { + const req = dns.resolveSoa('nodejs.org', function(err, result) { assert.ifError(err); assert.ok(result); assert.strictEqual(typeof result, 'object'); @@ -305,7 +305,7 @@ TEST(function test_resolveSoa(done) { }); TEST(function test_resolveSoa_failure(done) { - var req = dns.resolveSoa('something.invalid', function(err, result) { + const req = dns.resolveSoa('something.invalid', function(err, result) { assert.ok(err instanceof Error); assert.strictEqual(err.errno, 'ENOTFOUND'); @@ -318,12 +318,12 @@ TEST(function test_resolveSoa_failure(done) { }); TEST(function test_resolveCname(done) { - var req = dns.resolveCname('www.microsoft.com', function(err, names) { + const req = dns.resolveCname('www.microsoft.com', function(err, names) { assert.ifError(err); assert.ok(names.length > 0); - for (var i = 0; i < names.length; i++) { - var name = names[i]; + for (let i = 0; i < names.length; i++) { + const name = names[i]; assert.ok(name); assert.strictEqual(typeof name, 'string'); } @@ -335,7 +335,7 @@ TEST(function test_resolveCname(done) { }); TEST(function test_resolveCname_failure(done) { - var req = dns.resolveCname('something.invalid', function(err, result) { + const req = dns.resolveCname('something.invalid', function(err, result) { assert.ok(err instanceof Error); assert.strictEqual(err.errno, 'ENOTFOUND'); @@ -349,7 +349,7 @@ TEST(function test_resolveCname_failure(done) { TEST(function test_resolveTxt(done) { - var req = dns.resolveTxt('google.com', function(err, records) { + const req = dns.resolveTxt('google.com', function(err, records) { assert.ifError(err); assert.strictEqual(records.length, 1); assert.ok(util.isArray(records[0])); @@ -361,7 +361,7 @@ TEST(function test_resolveTxt(done) { }); TEST(function test_resolveTxt_failure(done) { - var req = dns.resolveTxt('something.invalid', function(err, result) { + const req = dns.resolveTxt('something.invalid', function(err, result) { assert.ok(err instanceof Error); assert.strictEqual(err.errno, 'ENOTFOUND'); @@ -375,7 +375,7 @@ TEST(function test_resolveTxt_failure(done) { TEST(function test_lookup_failure(done) { - var req = dns.lookup('does.not.exist', 4, function(err, ip, family) { + const req = dns.lookup('does.not.exist', 4, function(err, ip, family) { assert.ok(err instanceof Error); assert.strictEqual(err.errno, dns.NOTFOUND); assert.strictEqual(err.errno, 'ENOTFOUND'); @@ -390,7 +390,7 @@ TEST(function test_lookup_failure(done) { TEST(function test_lookup_null(done) { - var req = dns.lookup(null, function(err, ip, family) { + const req = dns.lookup(null, function(err, ip, family) { assert.ifError(err); assert.strictEqual(ip, null); assert.strictEqual(family, 4); @@ -403,7 +403,7 @@ TEST(function test_lookup_null(done) { TEST(function test_lookup_ip_all(done) { - var req = dns.lookup('127.0.0.1', {all: true}, function(err, ips, family) { + const req = dns.lookup('127.0.0.1', {all: true}, function(err, ips, family) { assert.ifError(err); assert.ok(Array.isArray(ips)); assert.ok(ips.length > 0); @@ -418,7 +418,7 @@ TEST(function test_lookup_ip_all(done) { TEST(function test_lookup_null_all(done) { - var req = dns.lookup(null, {all: true}, function(err, ips, family) { + const req = dns.lookup(null, {all: true}, function(err, ips, family) { assert.ifError(err); assert.ok(Array.isArray(ips)); assert.strictEqual(ips.length, 0); @@ -431,7 +431,7 @@ TEST(function test_lookup_null_all(done) { TEST(function test_lookup_all_mixed(done) { - var req = dns.lookup('www.google.com', {all: true}, function(err, ips) { + const req = dns.lookup('www.google.com', {all: true}, function(err, ips) { assert.ifError(err); assert.ok(Array.isArray(ips)); assert.ok(ips.length > 0); @@ -453,7 +453,7 @@ TEST(function test_lookup_all_mixed(done) { TEST(function test_lookupservice_invalid(done) { - var req = dns.lookupService('1.2.3.4', 80, function(err, host, service) { + const req = dns.lookupService('1.2.3.4', 80, function(err, host, service) { assert(err instanceof Error); assert.strictEqual(err.code, 'ENOTFOUND'); assert.ok(/1\.2\.3\.4/.test(err.message)); @@ -466,7 +466,7 @@ TEST(function test_lookupservice_invalid(done) { TEST(function test_reverse_failure(done) { - var req = dns.reverse('0.0.0.0', function(err) { + const req = dns.reverse('0.0.0.0', function(err) { assert(err instanceof Error); assert.strictEqual(err.code, 'ENOTFOUND'); // Silly error code... assert.strictEqual(err.hostname, '0.0.0.0'); @@ -480,7 +480,7 @@ TEST(function test_reverse_failure(done) { TEST(function test_lookup_failure(done) { - var req = dns.lookup('nosuchhostimsure', function(err) { + const req = dns.lookup('nosuchhostimsure', function(err) { assert(err instanceof Error); assert.strictEqual(err.code, 'ENOTFOUND'); // Silly error code... assert.strictEqual(err.hostname, 'nosuchhostimsure'); @@ -494,7 +494,7 @@ TEST(function test_lookup_failure(done) { TEST(function test_resolve_failure(done) { - var req = dns.resolve4('nosuchhostimsure', function(err) { + const req = dns.resolve4('nosuchhostimsure', function(err) { assert(err instanceof Error); switch (err.code) { @@ -516,12 +516,12 @@ TEST(function test_resolve_failure(done) { }); -var getaddrinfoCallbackCalled = false; +let getaddrinfoCallbackCalled = false; console.log('looking up nodejs.org...'); -var cares = process.binding('cares_wrap'); -var req = new cares.GetAddrInfoReqWrap(); +const cares = process.binding('cares_wrap'); +const req = new cares.GetAddrInfoReqWrap(); cares.getaddrinfo(req, 'nodejs.org', 4); req.oncomplete = function(err, domains) { diff --git a/test/internet/test-net-connect-timeout.js b/test/internet/test-net-connect-timeout.js index e379f4146720b9..95e25614ffa2b7 100644 --- a/test/internet/test-net-connect-timeout.js +++ b/test/internet/test-net-connect-timeout.js @@ -7,21 +7,21 @@ const common = require('../common'); const net = require('net'); const assert = require('assert'); -var start = new Date(); +const start = new Date(); -var T = 100; +const T = 100; // 192.0.2.1 is part of subnet assigned as "TEST-NET" in RFC 5737. // For use solely in documentation and example source code. // In short, it should be unreachable. // In practice, it's a network black hole. -var socket = net.createConnection(9999, '192.0.2.1'); +const socket = net.createConnection(9999, '192.0.2.1'); socket.setTimeout(T); socket.on('timeout', common.mustCall(function() { console.error('timeout'); - var now = new Date(); + const now = new Date(); assert.ok(now - start < T + 500); socket.destroy(); })); diff --git a/test/internet/test-net-connect-unref.js b/test/internet/test-net-connect-unref.js index fa45cc711e1016..f3be8409844702 100644 --- a/test/internet/test-net-connect-unref.js +++ b/test/internet/test-net-connect-unref.js @@ -2,10 +2,9 @@ const common = require('../common'); const net = require('net'); -var client; -var TIMEOUT = 10 * 1000; +const TIMEOUT = 10 * 1000; -client = net.createConnection(53, '8.8.8.8', function() { +const client = net.createConnection(53, '8.8.8.8', function() { client.unref(); }); diff --git a/test/internet/test-tls-connnect-melissadata.js b/test/internet/test-tls-connnect-melissadata.js index 3c6c205d6e4013..f57b897099fc2d 100644 --- a/test/internet/test-tls-connnect-melissadata.js +++ b/test/internet/test-tls-connnect-melissadata.js @@ -9,7 +9,7 @@ if (!common.hasCrypto) { } const tls = require('tls'); -var socket = tls.connect(443, 'address.melissadata.net', function() { +const socket = tls.connect(443, 'address.melissadata.net', function() { socket.resume(); socket.destroy(); }); diff --git a/test/known_issues/test-url-parse-conformance.js b/test/known_issues/test-url-parse-conformance.js index d70a322d6b7455..f7fcec821c8e50 100644 --- a/test/known_issues/test-url-parse-conformance.js +++ b/test/known_issues/test-url-parse-conformance.js @@ -9,14 +9,14 @@ const path = require('path'); const tests = require(path.join(common.fixturesDir, 'url-tests.json')); -var failed = 0; -var attempted = 0; +let failed = 0; +let attempted = 0; tests.forEach((test) => { attempted++; // Skip comments if (typeof test === 'string') return; - var parsed; + let parsed; try { // Attempt to parse @@ -28,7 +28,7 @@ tests.forEach((test) => { } else { // Test was not supposed to fail, so we're good so far. Now // check the results of the parse. - var username, password; + let username, password; try { assert.strictEqual(test.href, parsed.href); assert.strictEqual(test.protocol, parsed.protocol); diff --git a/test/message/eval_messages.js b/test/message/eval_messages.js index 188311851c5163..d50df9081b2d25 100644 --- a/test/message/eval_messages.js +++ b/test/message/eval_messages.js @@ -5,16 +5,16 @@ require('../common'); const spawn = require('child_process').spawn; function run(cmd, strict, cb) { - var args = []; + const args = []; if (strict) args.push('--use_strict'); args.push('-pe', cmd); - var child = spawn(process.execPath, args); + const child = spawn(process.execPath, args); child.stdout.pipe(process.stdout); child.stderr.pipe(process.stdout); child.on('close', cb); } -var queue = +const queue = [ 'with(this){__filename}', '42', 'throw new Error("hello")', @@ -22,7 +22,7 @@ var queue = 'var ______________________________________________; throw 10' ]; function go() { - var c = queue.shift(); + const c = queue.shift(); if (!c) return console.log('done'); run(c, false, function() { run(c, true, go); diff --git a/test/message/max_tick_depth.js b/test/message/max_tick_depth.js index 1d2ec175c5d957..c433c0bab3f100 100644 --- a/test/message/max_tick_depth.js +++ b/test/message/max_tick_depth.js @@ -2,7 +2,7 @@ require('../common'); process.maxTickDepth = 10; -var i = 20; +let i = 20; process.nextTick(function f() { console.error('tick %d', i); if (i-- > 0) diff --git a/test/message/stdin_messages.js b/test/message/stdin_messages.js index 4759e2b0d51159..b32004c329dead 100644 --- a/test/message/stdin_messages.js +++ b/test/message/stdin_messages.js @@ -5,17 +5,17 @@ require('../common'); const spawn = require('child_process').spawn; function run(cmd, strict, cb) { - var args = []; + const args = []; if (strict) args.push('--use_strict'); args.push('-p'); - var child = spawn(process.execPath, args); + const child = spawn(process.execPath, args); child.stdout.pipe(process.stdout); child.stderr.pipe(process.stdout); child.stdin.end(cmd); child.on('close', cb); } -var queue = +const queue = [ 'with(this){__filename}', '42', 'throw new Error("hello")', @@ -23,7 +23,7 @@ var queue = 'var ______________________________________________; throw 10' ]; function go() { - var c = queue.shift(); + const c = queue.shift(); if (!c) return console.log('done'); run(c, false, function() { run(c, true, go); diff --git a/test/parallel/test-assert-typedarray-deepequal.js b/test/parallel/test-assert-typedarray-deepequal.js index 2e6c88848a809f..f5ecb274a86a32 100644 --- a/test/parallel/test-assert-typedarray-deepequal.js +++ b/test/parallel/test-assert-typedarray-deepequal.js @@ -5,7 +5,7 @@ const assert = require('assert'); const a = require('assert'); function makeBlock(f) { - var args = Array.prototype.slice.call(arguments, 1); + const args = Array.prototype.slice.call(arguments, 1); return function() { return f.apply(this, args); }; diff --git a/test/parallel/test-assert.js b/test/parallel/test-assert.js index 06d328eea4c67b..346776ef5ed483 100644 --- a/test/parallel/test-assert.js +++ b/test/parallel/test-assert.js @@ -4,7 +4,7 @@ const assert = require('assert'); const a = require('assert'); function makeBlock(f) { - var args = Array.prototype.slice.call(arguments, 1); + const args = Array.prototype.slice.call(arguments, 1); return function() { return f.apply(this, args); }; @@ -125,8 +125,8 @@ assert.throws(makeBlock(a.deepEqual, {a: 4}, {a: 4, b: true}), assert.doesNotThrow(makeBlock(a.deepEqual, ['a'], {0: 'a'})); //(although not necessarily the same order), assert.doesNotThrow(makeBlock(a.deepEqual, {a: 4, b: '1'}, {b: '1', a: 4})); -var a1 = [1, 2, 3]; -var a2 = [1, 2, 3]; +const a1 = [1, 2, 3]; +const a2 = [1, 2, 3]; a1.a = 'test'; a1.b = true; a2.b = true; @@ -136,7 +136,7 @@ assert.throws(makeBlock(a.deepEqual, Object.keys(a1), Object.keys(a2)), assert.doesNotThrow(makeBlock(a.deepEqual, a1, a2)); // having an identical prototype property -var nbRoot = { +const nbRoot = { toString: function() { return this.first + ' ' + this.last; } }; @@ -154,8 +154,8 @@ function nameBuilder2(first, last) { } nameBuilder2.prototype = nbRoot; -var nb1 = new nameBuilder('Ryan', 'Dahl'); -var nb2 = new nameBuilder2('Ryan', 'Dahl'); +const nb1 = new nameBuilder('Ryan', 'Dahl'); +let nb2 = new nameBuilder2('Ryan', 'Dahl'); assert.doesNotThrow(makeBlock(a.deepEqual, nb1, nb2)); @@ -287,8 +287,8 @@ function Constructor2(first, last) { this.last = last; } -var obj1 = new Constructor1('Ryan', 'Dahl'); -var obj2 = new Constructor2('Ryan', 'Dahl'); +const obj1 = new Constructor1('Ryan', 'Dahl'); +let obj2 = new Constructor2('Ryan', 'Dahl'); assert.throws(makeBlock(a.deepStrictEqual, obj1, obj2), a.AssertionError); @@ -305,7 +305,7 @@ assert.throws(makeBlock(assert.deepStrictEqual, true, 1), assert.throws(makeBlock(assert.deepStrictEqual, Symbol(), Symbol()), a.AssertionError); -var s = Symbol(); +const s = Symbol(); assert.doesNotThrow(makeBlock(assert.deepStrictEqual, s, s)); @@ -346,7 +346,7 @@ assert.throws(makeBlock(thrower, a.AssertionError)); assert.throws(makeBlock(thrower, TypeError)); // when passing a type, only catch errors of the appropriate type -var threw = false; +let threw = false; try { a.throws(makeBlock(thrower, TypeError), a.AssertionError); } catch (e) { @@ -414,10 +414,11 @@ a.throws(makeBlock(thrower, TypeError), function(err) { // https://github.com/nodejs/node/issues/3188 threw = false; +let AnotherErrorType; try { - var ES6Error = class extends Error {}; + const ES6Error = class extends Error {}; - var AnotherErrorType = class extends Error {}; + AnotherErrorType = class extends Error {}; const functionThatThrows = function() { throw new AnotherErrorType('foo'); @@ -456,7 +457,7 @@ assert.ok(threw); a.throws(makeBlock(a.deepStrictEqual, d, e), /AssertionError/); } // GH-7178. Ensure reflexivity of deepEqual with `arguments` objects. -var args = (function() { return arguments; })(); +const args = (function() { return arguments; })(); a.throws(makeBlock(a.deepEqual, [], args)); a.throws(makeBlock(a.deepEqual, args, [])); @@ -475,7 +476,7 @@ a.throws(makeBlock(a.deepEqual, args, [])); a.doesNotThrow(makeBlock(a.deepEqual, someArgs, sameArgs)); } -var circular = {y: 1}; +const circular = {y: 1}; circular.x = circular; function testAssertionMessage(actual, expected) { @@ -540,7 +541,7 @@ try { // Verify that throws() and doesNotThrow() throw on non-function block function testBlockTypeError(method, block) { - var threw = true; + let threw = true; try { method(block); diff --git a/test/parallel/test-async-wrap-check-providers.js b/test/parallel/test-async-wrap-check-providers.js index c574403eaecffa..354534a6b30a5a 100644 --- a/test/parallel/test-async-wrap-check-providers.js +++ b/test/parallel/test-async-wrap-check-providers.js @@ -28,7 +28,7 @@ keyList.splice(0, 1); // want to improve under https://github.com/nodejs/node/issues/5085. // strip out fs watch related parts for now if (common.isAix) { - for (var i = 0; i < keyList.length; i++) { + for (let i = 0; i < keyList.length; i++) { if ((keyList[i] === 'FSEVENTWRAP') || (keyList[i] === 'STATWATCHER')) { keyList.splice(i, 1); } diff --git a/test/parallel/test-async-wrap-throw-from-callback.js b/test/parallel/test-async-wrap-throw-from-callback.js index adc92c69d978d5..b1a51773e2348c 100644 --- a/test/parallel/test-async-wrap-throw-from-callback.js +++ b/test/parallel/test-async-wrap-throw-from-callback.js @@ -13,8 +13,8 @@ const domain = require('domain'); const spawn = require('child_process').spawn; const callbacks = [ 'init', 'pre', 'post', 'destroy' ]; const toCall = process.argv[2]; -var msgCalled = 0; -var msgReceived = 0; +let msgCalled = 0; +let msgReceived = 0; function init() { if (toCall === 'init') @@ -57,7 +57,7 @@ if (typeof process.argv[2] === 'string') { msgCalled++; const child = spawn(process.execPath, [__filename, item]); - var errstring = ''; + let errstring = ''; child.stderr.on('data', (data) => { errstring += data.toString(); diff --git a/test/parallel/test-async-wrap-uid.js b/test/parallel/test-async-wrap-uid.js index 19cb01cfa83c7a..f16388cfe766f0 100644 --- a/test/parallel/test-async-wrap-uid.js +++ b/test/parallel/test-async-wrap-uid.js @@ -6,7 +6,7 @@ const assert = require('assert'); const async_wrap = process.binding('async_wrap'); // Give the event loop time to clear out the final uv_close(). -var si_cntr = 3; +let si_cntr = 3; process.on('beforeExit', () => { if (--si_cntr > 0) setImmediate(() => {}); }); diff --git a/test/parallel/test-buffer-ascii.js b/test/parallel/test-buffer-ascii.js index ea125283f23f93..cf5b529183cabf 100644 --- a/test/parallel/test-buffer-ascii.js +++ b/test/parallel/test-buffer-ascii.js @@ -16,7 +16,7 @@ const expected = 'Cb\u0000\u0019est, graphiquement, la rC)union ' + const buf = Buffer.from(input); -for (var i = 0; i < expected.length; ++i) { +for (let i = 0; i < expected.length; ++i) { assert.strictEqual(buf.slice(i).toString('ascii'), expected.slice(i)); // Skip remainder of multi-byte sequence. diff --git a/test/parallel/test-buffer-bytelength.js b/test/parallel/test-buffer-bytelength.js index e31e514ffa1182..c30e06cc73690d 100644 --- a/test/parallel/test-buffer-bytelength.js +++ b/test/parallel/test-buffer-bytelength.js @@ -24,37 +24,37 @@ assert(ArrayBuffer.isView(Buffer.allocUnsafeSlow(10))); assert(ArrayBuffer.isView(Buffer.from(''))); // buffer -var incomplete = Buffer.from([0xe4, 0xb8, 0xad, 0xe6, 0x96]); +const incomplete = Buffer.from([0xe4, 0xb8, 0xad, 0xe6, 0x96]); assert.strictEqual(Buffer.byteLength(incomplete), 5); -var ascii = Buffer.from('abc'); +const ascii = Buffer.from('abc'); assert.strictEqual(Buffer.byteLength(ascii), 3); // ArrayBuffer -var buffer = new ArrayBuffer(8); +const buffer = new ArrayBuffer(8); assert.strictEqual(Buffer.byteLength(buffer), 8); // TypedArray -var int8 = new Int8Array(8); +const int8 = new Int8Array(8); assert.strictEqual(Buffer.byteLength(int8), 8); -var uint8 = new Uint8Array(8); +const uint8 = new Uint8Array(8); assert.strictEqual(Buffer.byteLength(uint8), 8); -var uintc8 = new Uint8ClampedArray(2); +const uintc8 = new Uint8ClampedArray(2); assert.strictEqual(Buffer.byteLength(uintc8), 2); -var int16 = new Int16Array(8); +const int16 = new Int16Array(8); assert.strictEqual(Buffer.byteLength(int16), 16); -var uint16 = new Uint16Array(8); +const uint16 = new Uint16Array(8); assert.strictEqual(Buffer.byteLength(uint16), 16); -var int32 = new Int32Array(8); +const int32 = new Int32Array(8); assert.strictEqual(Buffer.byteLength(int32), 32); -var uint32 = new Uint32Array(8); +const uint32 = new Uint32Array(8); assert.strictEqual(Buffer.byteLength(uint32), 32); -var float32 = new Float32Array(8); +const float32 = new Float32Array(8); assert.strictEqual(Buffer.byteLength(float32), 32); -var float64 = new Float64Array(8); +const float64 = new Float64Array(8); assert.strictEqual(Buffer.byteLength(float64), 64); // DataView -var dv = new DataView(new ArrayBuffer(2)); +const dv = new DataView(new ArrayBuffer(2)); assert.strictEqual(Buffer.byteLength(dv), 2); // special case: zero length string diff --git a/test/parallel/test-buffer-concat.js b/test/parallel/test-buffer-concat.js index b29e00682c114b..5d558835b7db83 100644 --- a/test/parallel/test-buffer-concat.js +++ b/test/parallel/test-buffer-concat.js @@ -5,7 +5,7 @@ const assert = require('assert'); const zero = []; const one = [ Buffer.from('asdf') ]; const long = []; -for (var i = 0; i < 10; i++) long.push(Buffer.from('asdf')); +for (let i = 0; i < 10; i++) long.push(Buffer.from('asdf')); const flatZero = Buffer.concat(zero); const flatOne = Buffer.concat(one); diff --git a/test/parallel/test-buffer-copy.js b/test/parallel/test-buffer-copy.js index fef4acf7df286b..5737ed748058ef 100644 --- a/test/parallel/test-buffer-copy.js +++ b/test/parallel/test-buffer-copy.js @@ -5,7 +5,7 @@ const assert = require('assert'); const b = Buffer.allocUnsafe(1024); const c = Buffer.allocUnsafe(512); -var cntr = 0; +let cntr = 0; { // copy 512 bytes, from 0 to 512. diff --git a/test/parallel/test-buffer-fill.js b/test/parallel/test-buffer-fill.js index 8cfeeabe91eebe..06a9044bec3103 100644 --- a/test/parallel/test-buffer-fill.js +++ b/test/parallel/test-buffer-fill.js @@ -243,7 +243,7 @@ function writeToFill(string, offset, end, encoding) { // Convert "end" to "length" (which write understands). const length = end - offset < 0 ? 0 : end - offset; - var wasZero = false; + let wasZero = false; do { const written = buf2.write(string, offset, length, encoding); offset += written; @@ -324,7 +324,7 @@ Buffer.alloc(8, ''); { let elseWasLast = false; assert.throws(() => { - var ctr = 0; + let ctr = 0; const start = { [Symbol.toPrimitive]() { // We use this condition to get around the check in lib/buffer.js @@ -357,7 +357,7 @@ assert.throws(() => { { let elseWasLast = false; assert.throws(() => { - var ctr = 0; + let ctr = 0; const end = { [Symbol.toPrimitive]() { // We use this condition to get around the check in lib/buffer.js diff --git a/test/parallel/test-buffer-includes.js b/test/parallel/test-buffer-includes.js index 15e1eedeb54d15..9b0aef0ad7652d 100644 --- a/test/parallel/test-buffer-includes.js +++ b/test/parallel/test-buffer-includes.js @@ -140,7 +140,7 @@ assert.strictEqual( // test usc2 encoding -var twoByteString = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2'); +let twoByteString = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2'); assert(twoByteString.includes('\u0395', 4, 'ucs2')); assert(twoByteString.includes('\u03a3', -4, 'ucs2')); @@ -190,7 +190,7 @@ assert(!mixedByteStringUtf8.includes('\u0396')); // Test complex string includes algorithms. Only trigger for long strings. // Long string that isn't a simple repeat of a shorter string. -var longString = 'A'; +let longString = 'A'; for (let i = 66; i < 76; i++) { // from 'B' to 'K' longString = longString + String.fromCharCode(i) + longString; } @@ -198,7 +198,7 @@ for (let i = 66; i < 76; i++) { // from 'B' to 'K' const longBufferString = Buffer.from(longString); // pattern of 15 chars, repeated every 16 chars in long -var pattern = 'ABACABADABACABA'; +let pattern = 'ABACABADABACABA'; for (let i = 0; i < longBufferString.length - pattern.length; i += 7) { const includes = longBufferString.includes(pattern, i); assert(includes, 'Long ABACABA...-string at index ' + i); @@ -229,8 +229,8 @@ assert(!allCharsBufferUtf8.includes('notfound')); assert(!allCharsBufferUcs2.includes('notfound')); // Find substrings in Utf8. -var lengths = [1, 3, 15]; // Single char, simple and complex. -var indices = [0x5, 0x60, 0x400, 0x680, 0x7ee, 0xFF02, 0x16610, 0x2f77b]; +let lengths = [1, 3, 15]; // Single char, simple and complex. +let indices = [0x5, 0x60, 0x400, 0x680, 0x7ee, 0xFF02, 0x16610, 0x2f77b]; for (let lengthIndex = 0; lengthIndex < lengths.length; lengthIndex++) { for (let i = 0; i < indices.length; i++) { const index = indices[i]; diff --git a/test/parallel/test-buffer-indexof.js b/test/parallel/test-buffer-indexof.js index 27b71b1b17008a..503add948826ab 100644 --- a/test/parallel/test-buffer-indexof.js +++ b/test/parallel/test-buffer-indexof.js @@ -191,7 +191,7 @@ assert.equal(Buffer.from('aaaa00a').indexOf('3030', 'hex'), 4); assert.equal(-1, twoByteString.indexOf('\u03a3', -2, 'ucs2')); } -var mixedByteStringUcs2 = +const mixedByteStringUcs2 = Buffer.from('\u039a\u0391abc\u03a3\u03a3\u0395', 'ucs2'); assert.equal(6, mixedByteStringUcs2.indexOf('bc', 0, 'ucs2')); assert.equal(10, mixedByteStringUcs2.indexOf('\u03a3', 0, 'ucs2')); @@ -226,7 +226,7 @@ assert.equal( 6, twoByteString.indexOf('\u03a3\u0395', 0, 'ucs2'), 'Sigma Epsilon'); } -var mixedByteStringUtf8 = Buffer.from('\u039a\u0391abc\u03a3\u03a3\u0395'); +const mixedByteStringUtf8 = Buffer.from('\u039a\u0391abc\u03a3\u03a3\u0395'); assert.equal(5, mixedByteStringUtf8.indexOf('bc')); assert.equal(5, mixedByteStringUtf8.indexOf('bc', 5)); assert.equal(5, mixedByteStringUtf8.indexOf('bc', -8)); @@ -236,15 +236,15 @@ assert.equal(-1, mixedByteStringUtf8.indexOf('\u0396')); // Test complex string indexOf algorithms. Only trigger for long strings. // Long string that isn't a simple repeat of a shorter string. -var longString = 'A'; +let longString = 'A'; for (let i = 66; i < 76; i++) { // from 'B' to 'K' longString = longString + String.fromCharCode(i) + longString; } -var longBufferString = Buffer.from(longString); +const longBufferString = Buffer.from(longString); // pattern of 15 chars, repeated every 16 chars in long -var pattern = 'ABACABADABACABA'; +let pattern = 'ABACABADABACABA'; for (let i = 0; i < longBufferString.length - pattern.length; i += 7) { const index = longBufferString.indexOf(pattern, i); assert.equal((i + 15) & ~0xf, index, 'Long ABACABA...-string at index ' + i); @@ -260,17 +260,17 @@ assert.equal( 1535, longBufferString.indexOf(pattern, 512), 'Long JABACABA..., Second J'); // Search for a non-ASCII string in a pure ASCII string. -var asciiString = Buffer.from( +const asciiString = Buffer.from( 'arglebargleglopglyfarglebargleglopglyfarglebargleglopglyf'); assert.equal(-1, asciiString.indexOf('\x2061')); assert.equal(3, asciiString.indexOf('leb', 0)); // Search in string containing many non-ASCII chars. -var allCodePoints = []; +const allCodePoints = []; for (let i = 0; i < 65536; i++) allCodePoints[i] = i; -var allCharsString = String.fromCharCode.apply(String, allCodePoints); -var allCharsBufferUtf8 = Buffer.from(allCharsString); -var allCharsBufferUcs2 = Buffer.from(allCharsString, 'ucs2'); +const allCharsString = String.fromCharCode.apply(String, allCodePoints); +const allCharsBufferUtf8 = Buffer.from(allCharsString); +const allCharsBufferUcs2 = Buffer.from(allCharsString, 'ucs2'); // Search for string long enough to trigger complex search with ASCII pattern // and UC16 subject. @@ -307,10 +307,10 @@ assert.strictEqual(Buffer.from('aaaaa').indexOf('b', 'ucs2'), -1); length = 4 * length; } - var patternBufferUtf8 = allCharsBufferUtf8.slice(index, index + length); + const patternBufferUtf8 = allCharsBufferUtf8.slice(index, index + length); assert.equal(index, allCharsBufferUtf8.indexOf(patternBufferUtf8)); - var patternStringUtf8 = patternBufferUtf8.toString(); + const patternStringUtf8 = patternBufferUtf8.toString(); assert.equal(index, allCharsBufferUtf8.indexOf(patternStringUtf8)); } } @@ -325,12 +325,12 @@ assert.strictEqual(Buffer.from('aaaaa').indexOf('b', 'ucs2'), -1); const index = indices[i] * 2; const length = lengths[lengthIndex]; - var patternBufferUcs2 = + const patternBufferUcs2 = allCharsBufferUcs2.slice(index, index + length); assert.equal( index, allCharsBufferUcs2.indexOf(patternBufferUcs2, 0, 'ucs2')); - var patternStringUcs2 = patternBufferUcs2.toString('ucs2'); + const patternStringUcs2 = patternBufferUcs2.toString('ucs2'); assert.equal( index, allCharsBufferUcs2.indexOf(patternStringUcs2, 0, 'ucs2')); } @@ -439,7 +439,7 @@ assert.strictEqual(buf_bc.lastIndexOf('你好', 5, 'binary'), -1); assert.strictEqual(buf_bc.lastIndexOf(Buffer.from('你好'), 7), -1); // Test lastIndexOf on a longer buffer: -var bufferString = new Buffer('a man a plan a canal panama'); +const bufferString = new Buffer('a man a plan a canal panama'); assert.equal(15, bufferString.lastIndexOf('canal')); assert.equal(21, bufferString.lastIndexOf('panama')); assert.equal(0, bufferString.lastIndexOf('a man a plan a canal panama')); @@ -490,16 +490,17 @@ assert.equal(511, longBufferString.lastIndexOf(pattern, 1534)); // countBits returns the number of bits in the binary reprsentation of n. function countBits(n) { - for (var count = 0; n > 0; count++) { + let count; + for (count = 0; n > 0; count++) { n = n & (n - 1); // remove top bit } return count; } -var parts = []; -for (var i = 0; i < 1000000; i++) { +const parts = []; +for (let i = 0; i < 1000000; i++) { parts.push((countBits(i) % 2 === 0) ? 'yolo' : 'swag'); } -var reallyLong = new Buffer(parts.join(' ')); +const reallyLong = new Buffer(parts.join(' ')); assert.equal('yolo swag swag yolo', reallyLong.slice(0, 19).toString()); // Expensive reverse searches. Stress test lastIndexOf: diff --git a/test/parallel/test-buffer-inspect.js b/test/parallel/test-buffer-inspect.js index 4fed249207611b..41e8197da6a38a 100644 --- a/test/parallel/test-buffer-inspect.js +++ b/test/parallel/test-buffer-inspect.js @@ -6,13 +6,13 @@ const buffer = require('buffer'); buffer.INSPECT_MAX_BYTES = 2; -var b = Buffer.allocUnsafe(4); +let b = Buffer.allocUnsafe(4); b.fill('1234'); -var s = buffer.SlowBuffer(4); +let s = buffer.SlowBuffer(4); s.fill('1234'); -var expected = ''; +let expected = ''; assert.strictEqual(util.inspect(b), expected); assert.strictEqual(util.inspect(s), expected); diff --git a/test/parallel/test-buffer-iterator.js b/test/parallel/test-buffer-iterator.js index 7a25682ebc27d9..3120ff1d2ab457 100644 --- a/test/parallel/test-buffer-iterator.js +++ b/test/parallel/test-buffer-iterator.js @@ -3,8 +3,8 @@ require('../common'); const assert = require('assert'); const buffer = Buffer.from([1, 2, 3, 4, 5]); -var arr; -var b; +let arr; +let b; // buffers should be iterable diff --git a/test/parallel/test-buffer-swap.js b/test/parallel/test-buffer-swap.js index f72b638f75a30b..bcb636edb1733f 100644 --- a/test/parallel/test-buffer-swap.js +++ b/test/parallel/test-buffer-swap.js @@ -45,80 +45,80 @@ assert.deepStrictEqual(buf3_64, Buffer.from([0x01, 0x02, 0x0a, 0x09, 0x08, 0x07, 0x0f, 0x10])); // Force use of native code (Buffer size above threshold limit for js impl) -var buf4A = new Uint32Array(256).fill(0x04030201); -var buf4 = Buffer.from(buf4A.buffer, buf4A.byteOffset); -var buf5A = new Uint32Array(256).fill(0x03040102); -var buf5 = Buffer.from(buf5A.buffer, buf5A.byteOffset); +const buf4A = new Uint32Array(256).fill(0x04030201); +const buf4 = Buffer.from(buf4A.buffer, buf4A.byteOffset); +const buf5A = new Uint32Array(256).fill(0x03040102); +const buf5 = Buffer.from(buf5A.buffer, buf5A.byteOffset); buf4.swap16(); assert.deepStrictEqual(buf4, buf5); -var buf6A = new Uint32Array(256).fill(0x04030201); -var buf6 = Buffer.from(buf6A.buffer); -var bu7A = new Uint32Array(256).fill(0x01020304); -var buf7 = Buffer.from(bu7A.buffer, bu7A.byteOffset); +const buf6A = new Uint32Array(256).fill(0x04030201); +const buf6 = Buffer.from(buf6A.buffer); +const bu7A = new Uint32Array(256).fill(0x01020304); +const buf7 = Buffer.from(bu7A.buffer, bu7A.byteOffset); buf6.swap32(); assert.deepStrictEqual(buf6, buf7); -var buf8A = new Uint8Array(256 * 8); -var buf9A = new Uint8Array(256 * 8); +const buf8A = new Uint8Array(256 * 8); +const buf9A = new Uint8Array(256 * 8); for (let i = 0; i < buf8A.length; i++) { buf8A[i] = i % 8; buf9A[buf9A.length - i - 1] = i % 8; } -var buf8 = Buffer.from(buf8A.buffer, buf8A.byteOffset); -var buf9 = Buffer.from(buf9A.buffer, buf9A.byteOffset); +const buf8 = Buffer.from(buf8A.buffer, buf8A.byteOffset); +const buf9 = Buffer.from(buf9A.buffer, buf9A.byteOffset); buf8.swap64(); assert.deepStrictEqual(buf8, buf9); // Test native code with buffers that are not memory-aligned -var buf10A = new Uint8Array(256 * 8); -var buf11A = new Uint8Array(256 * 8 - 2); +const buf10A = new Uint8Array(256 * 8); +const buf11A = new Uint8Array(256 * 8 - 2); for (let i = 0; i < buf10A.length; i++) { buf10A[i] = i % 2; } for (let i = 1; i < buf11A.length; i++) { buf11A[buf11A.length - i] = (i + 1) % 2; } -var buf10 = Buffer.from(buf10A.buffer, buf10A.byteOffset); +const buf10 = Buffer.from(buf10A.buffer, buf10A.byteOffset); // 0|1 0|1 0|1... -var buf11 = Buffer.from(buf11A.buffer, buf11A.byteOffset); +const buf11 = Buffer.from(buf11A.buffer, buf11A.byteOffset); // 0|0 1|0 1|0... buf10.slice(1, buf10.length - 1).swap16(); assert.deepStrictEqual(buf10.slice(0, buf11.length), buf11); -var buf12A = new Uint8Array(256 * 8); -var buf13A = new Uint8Array(256 * 8 - 4); +const buf12A = new Uint8Array(256 * 8); +const buf13A = new Uint8Array(256 * 8 - 4); for (let i = 0; i < buf12A.length; i++) { buf12A[i] = i % 4; } for (let i = 1; i < buf13A.length; i++) { buf13A[buf13A.length - i] = (i + 1) % 4; } -var buf12 = Buffer.from(buf12A.buffer, buf12A.byteOffset); +const buf12 = Buffer.from(buf12A.buffer, buf12A.byteOffset); // 0|1 2 3 0|1 2 3... -var buf13 = Buffer.from(buf13A.buffer, buf13A.byteOffset); +const buf13 = Buffer.from(buf13A.buffer, buf13A.byteOffset); // 0|0 3 2 1|0 3 2... buf12.slice(1, buf12.length - 3).swap32(); assert.deepStrictEqual(buf12.slice(0, buf13.length), buf13); -var buf14A = new Uint8Array(256 * 8); -var buf15A = new Uint8Array(256 * 8 - 8); +const buf14A = new Uint8Array(256 * 8); +const buf15A = new Uint8Array(256 * 8 - 8); for (let i = 0; i < buf14A.length; i++) { buf14A[i] = i % 8; } for (let i = 1; i < buf15A.length; i++) { buf15A[buf15A.length - i] = (i + 1) % 8; } -var buf14 = Buffer.from(buf14A.buffer, buf14A.byteOffset); +const buf14 = Buffer.from(buf14A.buffer, buf14A.byteOffset); // 0|1 2 3 4 5 6 7 0|1 2 3 4... -var buf15 = Buffer.from(buf15A.buffer, buf15A.byteOffset); +const buf15 = Buffer.from(buf15A.buffer, buf15A.byteOffset); // 0|0 7 6 5 4 3 2 1|0 7 6 5... buf14.slice(1, buf14.length - 7).swap64(); diff --git a/test/parallel/test-child-process-constructor.js b/test/parallel/test-child-process-constructor.js index 59277dcabe5ffa..d33c7ae3acf626 100644 --- a/test/parallel/test-child-process-constructor.js +++ b/test/parallel/test-child-process-constructor.js @@ -3,11 +3,11 @@ require('../common'); const assert = require('assert'); const child_process = require('child_process'); -var ChildProcess = child_process.ChildProcess; +const ChildProcess = child_process.ChildProcess; assert.strictEqual(typeof ChildProcess, 'function'); // test that we can call spawn -var child = new ChildProcess(); +const child = new ChildProcess(); child.spawn({ file: process.execPath, args: ['--interactive'], diff --git a/test/parallel/test-child-process-default-options.js b/test/parallel/test-child-process-default-options.js index 2c60e274de51fa..37e7ea7494670e 100644 --- a/test/parallel/test-child-process-default-options.js +++ b/test/parallel/test-child-process-default-options.js @@ -6,14 +6,14 @@ const spawn = require('child_process').spawn; process.env.HELLO = 'WORLD'; -var child; +let child; if (common.isWindows) { child = spawn('cmd.exe', ['/c', 'set'], {}); } else { child = spawn('/usr/bin/env', [], {}); } -var response = ''; +let response = ''; child.stdout.setEncoding('utf8'); diff --git a/test/parallel/test-child-process-double-pipe.js b/test/parallel/test-child-process-double-pipe.js index c5b7c093af8a4a..dac48a2db7212a 100644 --- a/test/parallel/test-child-process-double-pipe.js +++ b/test/parallel/test-child-process-double-pipe.js @@ -8,7 +8,7 @@ const spawn = require('child_process').spawn; // We're trying to reproduce: // $ echo "hello\nnode\nand\nworld" | grep o | sed s/o/a/ -var grep, sed, echo; +let grep, sed, echo; if (common.isWindows) { grep = spawn('grep', ['--binary', 'o']), @@ -82,7 +82,7 @@ grep.stdout.on('end', function(code) { }); -var result = ''; +let result = ''; // print sed's output sed.stdout.on('data', function(data) { diff --git a/test/parallel/test-child-process-env.js b/test/parallel/test-child-process-env.js index cac82b9952a4da..ad41f978e21768 100644 --- a/test/parallel/test-child-process-env.js +++ b/test/parallel/test-child-process-env.js @@ -4,14 +4,14 @@ const assert = require('assert'); const spawn = require('child_process').spawn; -var env = { +const env = { 'HELLO': 'WORLD' }; Object.setPrototypeOf(env, { 'FOO': 'BAR' }); -var child; +let child; if (common.isWindows) { child = spawn('cmd.exe', ['/c', 'set'], {env: env}); } else { @@ -19,7 +19,7 @@ if (common.isWindows) { } -var response = ''; +let response = ''; child.stdout.setEncoding('utf8'); diff --git a/test/parallel/test-child-process-exec-cwd.js b/test/parallel/test-child-process-exec-cwd.js index 3b6e428a4aca65..95feb42314fc8d 100644 --- a/test/parallel/test-child-process-exec-cwd.js +++ b/test/parallel/test-child-process-exec-cwd.js @@ -3,7 +3,7 @@ const common = require('../common'); const assert = require('assert'); const exec = require('child_process').exec; -var pwdcommand, dir; +let pwdcommand, dir; if (common.isWindows) { pwdcommand = 'echo %cd%'; diff --git a/test/parallel/test-child-process-exec-stdout-stderr-data-string.js b/test/parallel/test-child-process-exec-stdout-stderr-data-string.js index 8ab834c98f8d79..472d31f16ac920 100644 --- a/test/parallel/test-child-process-exec-stdout-stderr-data-string.js +++ b/test/parallel/test-child-process-exec-stdout-stderr-data-string.js @@ -4,8 +4,8 @@ const common = require('../common'); const assert = require('assert'); const exec = require('child_process').exec; -var stdoutCalls = 0; -var stderrCalls = 0; +let stdoutCalls = 0; +let stderrCalls = 0; const command = common.isWindows ? 'dir' : 'ls'; exec(command).stdout.on('data', (data) => { diff --git a/test/parallel/test-child-process-exit-code.js b/test/parallel/test-child-process-exit-code.js index 2bd1256fe273d8..9596a202223993 100644 --- a/test/parallel/test-child-process-exit-code.js +++ b/test/parallel/test-child-process-exit-code.js @@ -4,17 +4,17 @@ const assert = require('assert'); const spawn = require('child_process').spawn; const path = require('path'); -var exitScript = path.join(common.fixturesDir, 'exit.js'); -var exitChild = spawn(process.argv[0], [exitScript, 23]); +const exitScript = path.join(common.fixturesDir, 'exit.js'); +const exitChild = spawn(process.argv[0], [exitScript, 23]); exitChild.on('exit', common.mustCall(function(code, signal) { assert.strictEqual(code, 23); assert.strictEqual(signal, null); })); -var errorScript = path.join(common.fixturesDir, - 'child_process_should_emit_error.js'); -var errorChild = spawn(process.argv[0], [errorScript]); +const errorScript = path.join(common.fixturesDir, + 'child_process_should_emit_error.js'); +const errorChild = spawn(process.argv[0], [errorScript]); errorChild.on('exit', common.mustCall(function(code, signal) { assert.ok(code !== 0); assert.strictEqual(signal, null); diff --git a/test/parallel/test-child-process-fork-close.js b/test/parallel/test-child-process-fork-close.js index d6e9675ba82012..d8b1aa0bf3267c 100644 --- a/test/parallel/test-child-process-fork-close.js +++ b/test/parallel/test-child-process-fork-close.js @@ -3,7 +3,7 @@ const common = require('../common'); const assert = require('assert'); const fork = require('child_process').fork; -var cp = fork(common.fixturesDir + '/child-process-message-and-exit.js'); +const cp = fork(common.fixturesDir + '/child-process-message-and-exit.js'); let gotMessage = false; let gotExit = false; diff --git a/test/parallel/test-child-process-fork-dgram.js b/test/parallel/test-child-process-fork-dgram.js index b25cf07ef6ff81..4447c54cae8f0c 100644 --- a/test/parallel/test-child-process-fork-dgram.js +++ b/test/parallel/test-child-process-fork-dgram.js @@ -37,8 +37,8 @@ if (process.argv[2] === 'child') { const msg = Buffer.from('Some bytes'); - var childGotMessage = false; - var parentGotMessage = false; + let childGotMessage = false; + let parentGotMessage = false; parentServer.once('message', function(msg, rinfo) { parentGotMessage = true; diff --git a/test/parallel/test-child-process-fork-exec-argv.js b/test/parallel/test-child-process-fork-exec-argv.js index 2daef37b669fc8..97d1e21a2f6d7a 100644 --- a/test/parallel/test-child-process-fork-exec-argv.js +++ b/test/parallel/test-child-process-fork-exec-argv.js @@ -2,8 +2,8 @@ require('../common'); const assert = require('assert'); const child_process = require('child_process'); -var spawn = child_process.spawn; -var fork = child_process.fork; +const spawn = child_process.spawn; +const fork = child_process.fork; if (process.argv[2] === 'fork') { process.stdout.write(JSON.stringify(process.execArgv), function() { @@ -12,11 +12,11 @@ if (process.argv[2] === 'fork') { } else if (process.argv[2] === 'child') { fork(__filename, ['fork']); } else { - var execArgv = ['--stack-size=256']; - var args = [__filename, 'child', 'arg0']; + const execArgv = ['--stack-size=256']; + const args = [__filename, 'child', 'arg0']; - var child = spawn(process.execPath, execArgv.concat(args)); - var out = ''; + const child = spawn(process.execPath, execArgv.concat(args)); + let out = ''; child.stdout.on('data', function(chunk) { out += chunk; diff --git a/test/parallel/test-child-process-fork-exec-path.js b/test/parallel/test-child-process-fork-exec-path.js index e9938d8ba12767..5af0184a21f55d 100644 --- a/test/parallel/test-child-process-fork-exec-path.js +++ b/test/parallel/test-child-process-fork-exec-path.js @@ -3,9 +3,9 @@ const common = require('../common'); const assert = require('assert'); const fs = require('fs'); const path = require('path'); -var msg = {test: 'this'}; -var nodePath = process.execPath; -var copyPath = path.join(common.tmpDir, 'node-copy.exe'); +const msg = {test: 'this'}; +const nodePath = process.execPath; +const copyPath = path.join(common.tmpDir, 'node-copy.exe'); if (process.env.FORK) { assert(process.send); @@ -23,7 +23,7 @@ if (process.env.FORK) { fs.chmodSync(copyPath, '0755'); // slow but simple - var envCopy = JSON.parse(JSON.stringify(process.env)); + const envCopy = JSON.parse(JSON.stringify(process.env)); envCopy.FORK = 'true'; const child = require('child_process').fork(__filename, { execPath: copyPath, diff --git a/test/parallel/test-child-process-fork-net.js b/test/parallel/test-child-process-fork-net.js index cbafcb13fbb068..c66b808ec0addf 100644 --- a/test/parallel/test-child-process-fork-net.js +++ b/test/parallel/test-child-process-fork-net.js @@ -19,7 +19,7 @@ ProgressTracker.prototype.check = function() { if (process.argv[2] === 'child') { - var serverScope; + let serverScope; process.on('message', function onServer(msg, server) { if (msg.what !== 'server') return; @@ -58,17 +58,17 @@ if (process.argv[2] === 'child') { process.send({what: 'ready'}); } else { - var child = fork(process.argv[1], ['child']); + const child = fork(process.argv[1], ['child']); child.on('exit', function() { console.log('CHILD: died'); }); // send net.Server to child and test by connecting - var testServer = function(callback) { + const testServer = function(callback) { // destroy server execute callback when done - var progress = new ProgressTracker(2, function() { + const progress = new ProgressTracker(2, function() { server.on('close', function() { console.log('PARENT: server closed'); child.send({what: 'close'}); @@ -77,11 +77,11 @@ if (process.argv[2] === 'child') { }); // we expect 4 connections and close events - var connections = new ProgressTracker(4, progress.done.bind(progress)); - var closed = new ProgressTracker(4, progress.done.bind(progress)); + const connections = new ProgressTracker(4, progress.done.bind(progress)); + const closed = new ProgressTracker(4, progress.done.bind(progress)); // create server and send it to child - var server = net.createServer(); + const server = net.createServer(); server.on('connection', function(socket) { console.log('PARENT: got connection'); socket.destroy(); @@ -94,12 +94,12 @@ if (process.argv[2] === 'child') { server.listen(0); // handle client messages - var messageHandlers = function(msg) { + const messageHandlers = function(msg) { if (msg.what === 'listening') { // make connections - var socket; - for (var i = 0; i < 4; i++) { + let socket; + for (let i = 0; i < 4; i++) { socket = net.connect(server.address().port, function() { console.log('CLIENT: connected'); }); @@ -122,11 +122,11 @@ if (process.argv[2] === 'child') { }; // send net.Socket to child - var testSocket = function(callback) { + const testSocket = function(callback) { // create a new server and connect to it, // but the socket will be handled by the child - var server = net.createServer(); + const server = net.createServer(); server.on('connection', function(socket) { socket.on('close', function() { console.log('CLIENT: socket closed'); @@ -145,8 +145,8 @@ if (process.argv[2] === 'child') { // will have to do. server.listen(0, function() { console.error('testSocket, listening'); - var connect = net.connect(server.address().port); - var store = ''; + const connect = net.connect(server.address().port); + let store = ''; connect.on('data', function(chunk) { store += chunk; console.log('CLIENT: got data'); @@ -160,8 +160,8 @@ if (process.argv[2] === 'child') { }; // create server and send it to child - var serverSuccess = false; - var socketSuccess = false; + let serverSuccess = false; + let socketSuccess = false; child.on('message', function onReady(msg) { if (msg.what !== 'ready') return; child.removeListener('message', onReady); diff --git a/test/parallel/test-child-process-fork-net2.js b/test/parallel/test-child-process-fork-net2.js index cee5c0a4ca548b..6d20f419049c7b 100644 --- a/test/parallel/test-child-process-fork-net2.js +++ b/test/parallel/test-child-process-fork-net2.js @@ -3,11 +3,11 @@ const common = require('../common'); const assert = require('assert'); const fork = require('child_process').fork; const net = require('net'); -var count = 12; +const count = 12; if (process.argv[2] === 'child') { - var needEnd = []; - var id = process.argv[3]; + const needEnd = []; + const id = process.argv[3]; process.on('message', function(m, socket) { if (!socket) return; @@ -60,11 +60,11 @@ if (process.argv[2] === 'child') { } else { - var child1 = fork(process.argv[1], ['child', '1']); - var child2 = fork(process.argv[1], ['child', '2']); - var child3 = fork(process.argv[1], ['child', '3']); + const child1 = fork(process.argv[1], ['child', '1']); + const child2 = fork(process.argv[1], ['child', '2']); + const child3 = fork(process.argv[1], ['child', '3']); - var server = net.createServer(); + const server = net.createServer(); let connected = 0; let closed = 0; @@ -94,10 +94,10 @@ if (process.argv[2] === 'child') { } }); - var disconnected = 0; + let disconnected = 0; server.on('listening', function() { - var j = count, client; + let j = count, client; while (j--) { client = net.connect(this.address().port, '127.0.0.1'); client.on('error', function() { @@ -112,7 +112,7 @@ if (process.argv[2] === 'child') { } }); - var closeEmitted = false; + let closeEmitted = false; server.on('close', common.mustCall(function() { closeEmitted = true; @@ -123,7 +123,7 @@ if (process.argv[2] === 'child') { server.listen(0, '127.0.0.1'); - var closeServer = function() { + const closeServer = function() { server.close(); setTimeout(function() { diff --git a/test/parallel/test-child-process-fork-ref.js b/test/parallel/test-child-process-fork-ref.js index 46eaab584f5581..1f8816c0cfaf1c 100644 --- a/test/parallel/test-child-process-fork-ref.js +++ b/test/parallel/test-child-process-fork-ref.js @@ -16,9 +16,10 @@ if (process.argv[2] === 'child') { }); } else { - var child = fork(__filename, ['child'], {silent: true}); + const child = fork(__filename, ['child'], {silent: true}); - var ipc = [], stdout = ''; + const ipc = []; + let stdout = ''; child.on('message', function(msg) { ipc.push(msg); diff --git a/test/parallel/test-child-process-fork-ref2.js b/test/parallel/test-child-process-fork-ref2.js index 6d6c56b6b3a93f..9f59aa344aa2c9 100644 --- a/test/parallel/test-child-process-fork-ref2.js +++ b/test/parallel/test-child-process-fork-ref2.js @@ -12,7 +12,7 @@ if (process.argv[2] === 'child') { }, 400); } else { - var child = fork(__filename, ['child']); + const child = fork(__filename, ['child']); child.on('disconnect', function() { console.log('parent -> disconnect'); diff --git a/test/parallel/test-child-process-fork-regr-gh-2847.js b/test/parallel/test-child-process-fork-regr-gh-2847.js index d985b8b4acaf19..0bcf4bf9a1c88f 100644 --- a/test/parallel/test-child-process-fork-regr-gh-2847.js +++ b/test/parallel/test-child-process-fork-regr-gh-2847.js @@ -14,7 +14,7 @@ if (!cluster.isMaster) { return; } -var server = net.createServer(function(s) { +const server = net.createServer(function(s) { if (common.isWindows) { s.on('error', function(err) { // Prevent possible ECONNRESET errors from popping up @@ -26,10 +26,10 @@ var server = net.createServer(function(s) { s.destroy(); }, 100); }).listen(0, function() { - var worker = cluster.fork(); + const worker = cluster.fork(); function send(callback) { - var s = net.connect(server.address().port, function() { + const s = net.connect(server.address().port, function() { worker.send({}, s, callback); }); diff --git a/test/parallel/test-child-process-fork.js b/test/parallel/test-child-process-fork.js index a8548eff5809c5..bfc68e41dc95fb 100644 --- a/test/parallel/test-child-process-fork.js +++ b/test/parallel/test-child-process-fork.js @@ -2,9 +2,9 @@ const common = require('../common'); const assert = require('assert'); const fork = require('child_process').fork; -var args = ['foo', 'bar']; +const args = ['foo', 'bar']; -var n = fork(common.fixturesDir + '/child-process-spawn-node.js', args); +const n = fork(common.fixturesDir + '/child-process-spawn-node.js', args); assert.strictEqual(n.channel, n._channel); assert.deepStrictEqual(args, ['foo', 'bar']); diff --git a/test/parallel/test-child-process-internal.js b/test/parallel/test-child-process-internal.js index 5d488f7839bd54..d795b69d7ee0e5 100644 --- a/test/parallel/test-child-process-internal.js +++ b/test/parallel/test-child-process-internal.js @@ -3,9 +3,9 @@ const common = require('../common'); const assert = require('assert'); //messages -var PREFIX = 'NODE_'; -var normal = {cmd: 'foo' + PREFIX}; -var internal = {cmd: PREFIX + 'bar'}; +const PREFIX = 'NODE_'; +const normal = {cmd: 'foo' + PREFIX}; +const internal = {cmd: PREFIX + 'bar'}; if (process.argv[2] === 'child') { //send non-internal message containing PREFIX at a non prefix position @@ -19,7 +19,7 @@ if (process.argv[2] === 'child') { } else { const fork = require('child_process').fork; - var child = fork(process.argv[1], ['child']); + const child = fork(process.argv[1], ['child']); child.once('message', common.mustCall(function(data) { assert.deepStrictEqual(data, normal); diff --git a/test/parallel/test-child-process-send-returns-boolean.js b/test/parallel/test-child-process-send-returns-boolean.js index 941a2da645f958..460c2b0022fc6b 100644 --- a/test/parallel/test-child-process-send-returns-boolean.js +++ b/test/parallel/test-child-process-send-returns-boolean.js @@ -15,7 +15,7 @@ assert.strictEqual(rv, true); const spawnOptions = { stdio: ['pipe', 'pipe', 'pipe', 'ipc'] }; const s = spawn(process.execPath, [emptyFile], spawnOptions); -var handle = null; +let handle = null; s.on('exit', function() { handle.close(); }); diff --git a/test/parallel/test-child-process-set-blocking.js b/test/parallel/test-child-process-set-blocking.js index 5a542fa97e2b5a..54037aea69feb2 100644 --- a/test/parallel/test-child-process-set-blocking.js +++ b/test/parallel/test-child-process-set-blocking.js @@ -3,9 +3,9 @@ const common = require('../common'); const assert = require('assert'); const ch = require('child_process'); -var SIZE = 100000; +const SIZE = 100000; -var cp = ch.spawn('python', ['-c', 'print ' + SIZE + ' * "C"'], { +const cp = ch.spawn('python', ['-c', 'print ' + SIZE + ' * "C"'], { stdio: 'inherit' }); diff --git a/test/parallel/test-child-process-silent.js b/test/parallel/test-child-process-silent.js index e087ae1cdea14f..3bfa9f5f7d5235 100644 --- a/test/parallel/test-child-process-silent.js +++ b/test/parallel/test-child-process-silent.js @@ -32,15 +32,15 @@ if (process.argv[2] === 'pipe') { // testcase | start parent && child IPC test // testing: is stderr and stdout piped to parent - var args = [process.argv[1], 'parent']; - var parent = childProcess.spawn(process.execPath, args); + const args = [process.argv[1], 'parent']; + const parent = childProcess.spawn(process.execPath, args); //got any stderr or std data - var stdoutData = false; + let stdoutData = false; parent.stdout.on('data', function() { stdoutData = true; }); - var stderrData = false; + let stderrData = false; parent.stdout.on('data', function() { stderrData = true; }); @@ -52,8 +52,8 @@ if (process.argv[2] === 'pipe') { child.stderr.pipe(process.stderr, {end: false}); child.stdout.pipe(process.stdout, {end: false}); - var childSending = false; - var childReciveing = false; + let childSending = false; + let childReciveing = false; child.on('message', function(message) { if (childSending === false) { childSending = (message === 'message from child'); diff --git a/test/parallel/test-child-process-spawn-typeerror.js b/test/parallel/test-child-process-spawn-typeerror.js index 7b98cedf8ba117..756d61931a68f3 100644 --- a/test/parallel/test-child-process-spawn-typeerror.js +++ b/test/parallel/test-child-process-spawn-typeerror.js @@ -12,7 +12,7 @@ const invalidOptionsMsg = /"options" argument must be an object/; const empty = common.fixturesDir + '/empty.js'; assert.throws(function() { - var child = spawn(invalidcmd, 'this is not an array'); + const child = spawn(invalidcmd, 'this is not an array'); child.on('error', common.fail); }, TypeError); diff --git a/test/parallel/test-child-process-spawnsync-env.js b/test/parallel/test-child-process-spawnsync-env.js index 05ef18bf7279a7..6f5ea3dc83d107 100644 --- a/test/parallel/test-child-process-spawnsync-env.js +++ b/test/parallel/test-child-process-spawnsync-env.js @@ -6,8 +6,8 @@ const cp = require('child_process'); if (process.argv[2] === 'child') { console.log(process.env.foo); } else { - var expected = 'bar'; - var child = cp.spawnSync(process.execPath, [__filename, 'child'], { + const expected = 'bar'; + const child = cp.spawnSync(process.execPath, [__filename, 'child'], { env: Object.assign(process.env, { foo: expected }) }); diff --git a/test/parallel/test-child-process-spawnsync-input.js b/test/parallel/test-child-process-spawnsync-input.js index fdd29aa7d0cc50..1bda3d5dcf9da2 100644 --- a/test/parallel/test-child-process-spawnsync-input.js +++ b/test/parallel/test-child-process-spawnsync-input.js @@ -17,7 +17,7 @@ const args = [ `console.log("${msgOut}"); console.error("${msgErr}");` ]; -var ret; +let ret; function checkSpawnSyncRet(ret) { @@ -51,7 +51,7 @@ if (process.argv.indexOf('spawnchild') !== -1) { verifyBufOutput(spawnSync(process.execPath, [__filename, 'spawnchild', 1])); verifyBufOutput(spawnSync(process.execPath, [__filename, 'spawnchild', 2])); -var options = { +let options = { input: 1234 }; diff --git a/test/parallel/test-child-process-spawnsync-timeout.js b/test/parallel/test-child-process-spawnsync-timeout.js index 207315c531afd0..abebe41e6e9640 100644 --- a/test/parallel/test-child-process-spawnsync-timeout.js +++ b/test/parallel/test-child-process-spawnsync-timeout.js @@ -4,8 +4,8 @@ const assert = require('assert'); const spawnSync = require('child_process').spawnSync; -var TIMER = 200; -var SLEEP = 5000; +const TIMER = 200; +const SLEEP = 5000; switch (process.argv[2]) { case 'child': @@ -15,12 +15,12 @@ switch (process.argv[2]) { }, SLEEP); break; default: - var start = Date.now(); - var ret = spawnSync(process.execPath, [__filename, 'child'], + const start = Date.now(); + const ret = spawnSync(process.execPath, [__filename, 'child'], {timeout: TIMER}); assert.strictEqual(ret.error.errno, 'ETIMEDOUT'); console.log(ret); - var end = Date.now() - start; + const end = Date.now() - start; assert(end < SLEEP); assert(ret.status > 128 || ret.signal); break; diff --git a/test/parallel/test-child-process-stdin-ipc.js b/test/parallel/test-child-process-stdin-ipc.js index c4a8064680e69f..2623e2deeeee8a 100644 --- a/test/parallel/test-child-process-stdin-ipc.js +++ b/test/parallel/test-child-process-stdin-ipc.js @@ -10,7 +10,7 @@ if (process.argv[2] === 'child') { return; } -var proc = spawn(process.execPath, [__filename, 'child'], { +const proc = spawn(process.execPath, [__filename, 'child'], { stdio: ['ipc', 'inherit', 'inherit'] }); diff --git a/test/parallel/test-child-process-stdio-big-write-end.js b/test/parallel/test-child-process-stdio-big-write-end.js index 4c9f4159d0d8bc..24991492f63d32 100644 --- a/test/parallel/test-child-process-stdio-big-write-end.js +++ b/test/parallel/test-child-process-stdio-big-write-end.js @@ -28,8 +28,9 @@ function parent() { }); // Write until the buffer fills up. + let buf; do { - var buf = Buffer.alloc(BUFSIZE, '.'); + buf = Buffer.alloc(BUFSIZE, '.'); sent += BUFSIZE; } while (child.stdin.write(buf)); diff --git a/test/parallel/test-child-process-stdio-inherit.js b/test/parallel/test-child-process-stdio-inherit.js index f7b992e4e76c26..d2b64aeb30dd31 100644 --- a/test/parallel/test-child-process-stdio-inherit.js +++ b/test/parallel/test-child-process-stdio-inherit.js @@ -9,10 +9,10 @@ else grandparent(); function grandparent() { - var child = spawn(process.execPath, [__filename, 'parent']); + const child = spawn(process.execPath, [__filename, 'parent']); child.stderr.pipe(process.stderr); - var output = ''; - var input = 'asdfasdf'; + let output = ''; + const input = 'asdfasdf'; child.stdout.on('data', function(chunk) { output += chunk; diff --git a/test/parallel/test-cli-eval.js b/test/parallel/test-cli-eval.js index d00092186b8184..fdd0cc33f068d9 100644 --- a/test/parallel/test-cli-eval.js +++ b/test/parallel/test-cli-eval.js @@ -14,7 +14,7 @@ const nodejs = '"' + process.execPath + '"'; // replace \ by / because windows uses backslashes in paths, but they're still // interpreted as the escape character when put between quotes. -var filename = __filename.replace(/\\/g, '/'); +const filename = __filename.replace(/\\/g, '/'); // assert that nothing is written to stdout child.exec(nodejs + ' --eval 42', @@ -34,7 +34,7 @@ child.exec(nodejs + ' --eval "console.error(42)"', // assert that the expected output is written to stdout ['--print', '-p -e', '-pe', '-p'].forEach(function(s) { - var cmd = nodejs + ' ' + s + ' '; + const cmd = nodejs + ' ' + s + ' '; child.exec(cmd + '42', function(err, stdout, stderr) { diff --git a/test/parallel/test-cli-syntax.js b/test/parallel/test-cli-syntax.js index 839e50d7d94b40..d7781eddffbb42 100644 --- a/test/parallel/test-cli-syntax.js +++ b/test/parallel/test-cli-syntax.js @@ -5,10 +5,10 @@ const assert = require('assert'); const spawnSync = require('child_process').spawnSync; const path = require('path'); -var node = process.execPath; +const node = process.execPath; // test both sets of arguments that check syntax -var syntaxArgs = [ +const syntaxArgs = [ ['-c'], ['--check'] ]; @@ -25,8 +25,8 @@ var syntaxArgs = [ // loop each possible option, `-c` or `--check` syntaxArgs.forEach(function(args) { - var _args = args.concat(file); - var c = spawnSync(node, _args, {encoding: 'utf8'}); + const _args = args.concat(file); + const c = spawnSync(node, _args, {encoding: 'utf8'}); // no output should be produced assert.strictEqual(c.stdout, '', 'stdout produced'); @@ -46,14 +46,14 @@ var syntaxArgs = [ // loop each possible option, `-c` or `--check` syntaxArgs.forEach(function(args) { - var _args = args.concat(file); - var c = spawnSync(node, _args, {encoding: 'utf8'}); + const _args = args.concat(file); + const c = spawnSync(node, _args, {encoding: 'utf8'}); // no stdout should be produced assert.strictEqual(c.stdout, '', 'stdout produced'); // stderr should have a syntax error message - var match = c.stderr.match(/^SyntaxError: Unexpected identifier$/m); + const match = c.stderr.match(/^SyntaxError: Unexpected identifier$/m); assert(match, 'stderr incorrect'); assert.strictEqual(c.status, 1, 'code == ' + c.status); @@ -69,14 +69,14 @@ var syntaxArgs = [ // loop each possible option, `-c` or `--check` syntaxArgs.forEach(function(args) { - var _args = args.concat(file); - var c = spawnSync(node, _args, {encoding: 'utf8'}); + const _args = args.concat(file); + const c = spawnSync(node, _args, {encoding: 'utf8'}); // no stdout should be produced assert.strictEqual(c.stdout, '', 'stdout produced'); // stderr should have a module not found error message - var match = c.stderr.match(/^Error: Cannot find module/m); + const match = c.stderr.match(/^Error: Cannot find module/m); assert(match, 'stderr incorrect'); assert.strictEqual(c.status, 1, 'code == ' + c.status); diff --git a/test/parallel/test-cluster-basic.js b/test/parallel/test-cluster-basic.js index 0ffdcf180bd8a8..92251b7324bf5f 100644 --- a/test/parallel/test-cluster-basic.js +++ b/test/parallel/test-cluster-basic.js @@ -56,7 +56,6 @@ if (cluster.isWorker) { } }; - var worker; const stateNames = Object.keys(checks.worker.states); //Check events, states, and emit arguments @@ -72,7 +71,7 @@ if (cluster.isWorker) { checks.cluster.equal[name] = worker === arguments[0]; //Check state - var state = stateNames[index]; + const state = stateNames[index]; checks.worker.states[state] = (state === worker.state); })); }); @@ -86,7 +85,7 @@ if (cluster.isWorker) { cluster.on('exit', common.mustCall(() => {})); //Create worker - worker = cluster.fork(); + const worker = cluster.fork(); assert.strictEqual(worker.id, 1); assert(worker instanceof cluster.Worker, 'the worker is not a instance of the Worker constructor'); diff --git a/test/parallel/test-cluster-bind-privileged-port.js b/test/parallel/test-cluster-bind-privileged-port.js index 228e1f0f1eaab0..3e062697fd2fea 100644 --- a/test/parallel/test-cluster-bind-privileged-port.js +++ b/test/parallel/test-cluster-bind-privileged-port.js @@ -19,7 +19,7 @@ if (cluster.isMaster) { assert.strictEqual(exitCode, 0); })); } else { - var s = net.createServer(common.fail); + const s = net.createServer(common.fail); s.listen(42, common.fail.bind(null, 'listen should have failed')); s.on('error', common.mustCall((err) => { assert.strictEqual(err.code, 'EACCES'); diff --git a/test/parallel/test-cluster-dgram-1.js b/test/parallel/test-cluster-dgram-1.js index 3b27fa8e20cb6c..25391997755f6b 100644 --- a/test/parallel/test-cluster-dgram-1.js +++ b/test/parallel/test-cluster-dgram-1.js @@ -21,10 +21,10 @@ else function master() { - var listening = 0; + let listening = 0; // Fork 4 workers. - for (var i = 0; i < NUM_WORKERS; i++) + for (let i = 0; i < NUM_WORKERS; i++) cluster.fork(); // Wait until all workers are listening. @@ -35,7 +35,7 @@ function master() { // Start sending messages. const buf = Buffer.from('hello world'); const socket = dgram.createSocket('udp4'); - var sent = 0; + let sent = 0; doSend(); function doSend() { @@ -60,7 +60,7 @@ function master() { } function setupWorker(worker) { - var received = 0; + let received = 0; worker.on('message', common.mustCall((msg) => { received = msg.received; @@ -75,10 +75,10 @@ function master() { function worker() { - var received = 0; + let received = 0; // Create udp socket and start listening. - var socket = dgram.createSocket('udp4'); + const socket = dgram.createSocket('udp4'); socket.on('message', common.mustCall((data, info) => { received++; diff --git a/test/parallel/test-cluster-dgram-2.js b/test/parallel/test-cluster-dgram-2.js index 863e0fa358c73e..37aea29e1a4263 100644 --- a/test/parallel/test-cluster-dgram-2.js +++ b/test/parallel/test-cluster-dgram-2.js @@ -20,10 +20,10 @@ else function master() { - var received = 0; + let received = 0; // Start listening on a socket. - var socket = dgram.createSocket('udp4'); + const socket = dgram.createSocket('udp4'); socket.bind(common.PORT); // Disconnect workers when the expected number of messages have been @@ -42,7 +42,7 @@ function master() { }, NUM_WORKERS * PACKETS_PER_WORKER)); // Fork workers. - for (var i = 0; i < NUM_WORKERS; i++) + for (let i = 0; i < NUM_WORKERS; i++) cluster.fork(); } diff --git a/test/parallel/test-cluster-dgram-reuse.js b/test/parallel/test-cluster-dgram-reuse.js index 27fc1be985d4b7..aed565a3806e97 100644 --- a/test/parallel/test-cluster-dgram-reuse.js +++ b/test/parallel/test-cluster-dgram-reuse.js @@ -25,16 +25,16 @@ function next() { // Work around health check issue process.nextTick(() => { - for (var i = 0; i < sockets.length; i++) + for (let i = 0; i < sockets.length; i++) sockets[i].close(close); }); } -var waiting = 2; +let waiting = 2; function close() { if (--waiting === 0) cluster.worker.disconnect(); } -for (var i = 0; i < 2; i++) +for (let i = 0; i < 2; i++) dgram.createSocket({ type: 'udp4', reuseAddr: true }).bind(common.PORT, next); diff --git a/test/parallel/test-cluster-disconnect-race.js b/test/parallel/test-cluster-disconnect-race.js index e89b9e134fa83f..09966cbab84496 100644 --- a/test/parallel/test-cluster-disconnect-race.js +++ b/test/parallel/test-cluster-disconnect-race.js @@ -16,9 +16,9 @@ if (common.isWindows) { cluster.schedulingPolicy = cluster.SCHED_NONE; if (cluster.isMaster) { - var worker1, worker2; + let worker2; - worker1 = cluster.fork(); + const worker1 = cluster.fork(); worker1.on('message', common.mustCall(function() { worker2 = cluster.fork(); worker1.disconnect(); @@ -32,7 +32,7 @@ if (cluster.isMaster) { return; } -var server = net.createServer(); +const server = net.createServer(); server.listen(common.PORT, function() { process.send('listening'); diff --git a/test/parallel/test-cluster-disconnect-suicide-race.js b/test/parallel/test-cluster-disconnect-suicide-race.js index 6f23b23fd2d4ff..15d07002252ee9 100644 --- a/test/parallel/test-cluster-disconnect-suicide-race.js +++ b/test/parallel/test-cluster-disconnect-suicide-race.js @@ -14,7 +14,7 @@ if (cluster.isMaster) { return cluster.fork(); } -var eventFired = false; +let eventFired = false; cluster.worker.disconnect(); diff --git a/test/parallel/test-cluster-disconnect-with-no-workers.js b/test/parallel/test-cluster-disconnect-with-no-workers.js index 4b38720d71e984..15c5898a7d6f69 100644 --- a/test/parallel/test-cluster-disconnect-with-no-workers.js +++ b/test/parallel/test-cluster-disconnect-with-no-workers.js @@ -3,7 +3,7 @@ require('../common'); const assert = require('assert'); const cluster = require('cluster'); -var disconnected; +let disconnected; process.on('exit', function() { assert(disconnected); diff --git a/test/parallel/test-cluster-disconnect.js b/test/parallel/test-cluster-disconnect.js index 4609724130f2ec..0fc1611e2d9577 100644 --- a/test/parallel/test-cluster-disconnect.js +++ b/test/parallel/test-cluster-disconnect.js @@ -14,13 +14,13 @@ if (cluster.isWorker) { }).listen(common.PORT + 1, '127.0.0.1'); } else if (cluster.isMaster) { - var servers = 2; + const servers = 2; // test a single TCP server const testConnection = function(port, cb) { - var socket = net.connect(port, '127.0.0.1', () => { + const socket = net.connect(port, '127.0.0.1', () => { // buffer result - var result = ''; + let result = ''; socket.on('data', common.mustCall((chunk) => { result += chunk; })); // check result @@ -32,9 +32,9 @@ if (cluster.isWorker) { // test both servers created in the cluster const testCluster = function(cb) { - var done = 0; + let done = 0; - for (var i = 0, l = servers; i < l; i++) { + for (let i = 0, l = servers; i < l; i++) { testConnection(common.PORT + i, (success) => { assert.ok(success); done += 1; @@ -47,10 +47,10 @@ if (cluster.isWorker) { // start two workers and execute callback when both is listening const startCluster = function(cb) { - var workers = 8; - var online = 0; + const workers = 8; + let online = 0; - for (var i = 0, l = workers; i < l; i++) { + for (let i = 0, l = workers; i < l; i++) { cluster.fork().on('listening', common.mustCall(() => { online += 1; if (online === workers * servers) { diff --git a/test/parallel/test-cluster-eaccess.js b/test/parallel/test-cluster-eaccess.js index 2de4af8b1a108b..75b60248a22381 100644 --- a/test/parallel/test-cluster-eaccess.js +++ b/test/parallel/test-cluster-eaccess.js @@ -37,7 +37,7 @@ if (cluster.isMaster) { } else { common.refreshTmpDir(); - var cp = fork(common.fixturesDir + '/listen-on-socket-and-exit.js', + const cp = fork(common.fixturesDir + '/listen-on-socket-and-exit.js', { stdio: 'inherit' }); // message from the child indicates it's ready and listening diff --git a/test/parallel/test-cluster-eaddrinuse.js b/test/parallel/test-cluster-eaddrinuse.js index 8b94845635f822..a0936ef4b9d471 100644 --- a/test/parallel/test-cluster-eaddrinuse.js +++ b/test/parallel/test-cluster-eaddrinuse.js @@ -8,12 +8,12 @@ const assert = require('assert'); const fork = require('child_process').fork; const net = require('net'); -var id = '' + process.argv[2]; +const id = '' + process.argv[2]; if (id === 'undefined') { const server = net.createServer(common.fail); server.listen(common.PORT, function() { - var worker = fork(__filename, ['worker']); + const worker = fork(__filename, ['worker']); worker.on('message', function(msg) { if (msg !== 'stop-listening') return; server.close(function() { diff --git a/test/parallel/test-cluster-fork-env.js b/test/parallel/test-cluster-fork-env.js index 735ff73d2a5c16..55ea684f3b4ce3 100644 --- a/test/parallel/test-cluster-fork-env.js +++ b/test/parallel/test-cluster-fork-env.js @@ -12,7 +12,7 @@ if (cluster.isWorker) { assert.strictEqual(result, true); } else if (cluster.isMaster) { - var checks = { + const checks = { using: false, overwrite: false }; @@ -22,7 +22,7 @@ if (cluster.isWorker) { process.env['cluster_test_overwrite'] = 'old'; // Fork worker - var worker = cluster.fork({ + const worker = cluster.fork({ 'cluster_test_prop': 'custom', 'cluster_test_overwrite': 'new' }); diff --git a/test/parallel/test-cluster-master-error.js b/test/parallel/test-cluster-master-error.js index 6f9c78a7ba601f..11ed09c64ed04e 100644 --- a/test/parallel/test-cluster-master-error.js +++ b/test/parallel/test-cluster-master-error.js @@ -15,7 +15,7 @@ if (cluster.isWorker) { } else if (process.argv[2] === 'cluster') { // Send PID to testcase process - var forkNum = 0; + let forkNum = 0; cluster.on('fork', common.mustCall(function forkEvent(worker) { // Send PID @@ -31,7 +31,7 @@ if (cluster.isWorker) { })); // Throw accidental error when all workers are listening - var listeningNum = 0; + let listeningNum = 0; cluster.on('listening', common.mustCall(function listeningEvent() { // When all workers are listening @@ -56,8 +56,8 @@ if (cluster.isWorker) { const fork = require('child_process').fork; - var masterExited = false; - var workersExited = false; + let masterExited = false; + let workersExited = false; // List all workers const workers = []; @@ -82,7 +82,7 @@ if (cluster.isWorker) { const pollWorkers = function() { // When master is dead all workers should be dead too - var alive = false; + let alive = false; workers.forEach((pid) => alive = common.isAlive(pid)); if (alive) { setTimeout(pollWorkers, 50); diff --git a/test/parallel/test-cluster-master-kill.js b/test/parallel/test-cluster-master-kill.js index 44eedec47b58e5..094e5ad256de7d 100644 --- a/test/parallel/test-cluster-master-kill.js +++ b/test/parallel/test-cluster-master-kill.js @@ -34,13 +34,13 @@ if (cluster.isWorker) { const master = fork(process.argv[1], ['cluster']); // get pid info - var pid = null; + let pid = null; master.once('message', (data) => { pid = data.pid; }); // When master is dead - var alive = true; + let alive = true; master.on('exit', common.mustCall((code) => { // make sure that the master died on purpose diff --git a/test/parallel/test-cluster-message.js b/test/parallel/test-cluster-message.js index a86b469e331dbe..5b537bbe73a755 100644 --- a/test/parallel/test-cluster-message.js +++ b/test/parallel/test-cluster-message.js @@ -13,8 +13,8 @@ function forEach(obj, fn) { if (cluster.isWorker) { // Create a tcp server. This will be used as cluster-shared-server and as an // alternative IPC channel. - var server = net.Server(); - var socket, message; + const server = net.Server(); + let socket, message; function maybeReply() { if (!socket || !message) return; @@ -42,7 +42,7 @@ if (cluster.isWorker) { server.listen(common.PORT, '127.0.0.1'); } else if (cluster.isMaster) { - var checks = { + const checks = { global: { 'receive': false, 'correct': false @@ -58,13 +58,13 @@ if (cluster.isWorker) { }; - var client; - var check = function(type, result) { + let client; + const check = function(type, result) { checks[type].receive = true; checks[type].correct = result; console.error('check', checks); - var missing = false; + let missing = false; forEach(checks, function(type) { if (type.receive === false) missing = true; }); @@ -76,7 +76,7 @@ if (cluster.isWorker) { }; // Spawn worker - var worker = cluster.fork(); + const worker = cluster.fork(); // When a IPC message is received from the worker worker.on('message', function(message) { diff --git a/test/parallel/test-cluster-rr-domain-listen.js b/test/parallel/test-cluster-rr-domain-listen.js index 0f39c47ed2e67d..10b0530b505a95 100644 --- a/test/parallel/test-cluster-rr-domain-listen.js +++ b/test/parallel/test-cluster-rr-domain-listen.js @@ -7,14 +7,13 @@ const domain = require('domain'); // cluster.schedulingPolicy = cluster.SCHED_RR; if (cluster.isWorker) { - var d = domain.create(); + const d = domain.create(); d.run(function() { }); const http = require('http'); http.Server(function() { }).listen(common.PORT, '127.0.0.1'); } else if (cluster.isMaster) { - var worker; //Kill worker when listening cluster.on('listening', function() { @@ -27,5 +26,5 @@ if (cluster.isWorker) { }); //Create worker - worker = cluster.fork(); + const worker = cluster.fork(); } diff --git a/test/parallel/test-cluster-send-deadlock.js b/test/parallel/test-cluster-send-deadlock.js index 062ebf2b131911..3fa64ac0b5d4d0 100644 --- a/test/parallel/test-cluster-send-deadlock.js +++ b/test/parallel/test-cluster-send-deadlock.js @@ -8,14 +8,14 @@ const cluster = require('cluster'); const net = require('net'); if (cluster.isMaster) { - var worker = cluster.fork(); + const worker = cluster.fork(); worker.on('exit', function(code, signal) { assert.strictEqual(code, 0, 'Worker exited with an error code'); assert(!signal, 'Worker exited by a signal'); server.close(); }); - var server = net.createServer(function(socket) { + const server = net.createServer(function(socket) { worker.send('handle', socket); }); @@ -25,9 +25,9 @@ if (cluster.isMaster) { } else { process.on('message', function(msg, handle) { if (msg === 'listen') { - var client1 = net.connect({ host: 'localhost', port: common.PORT }); - var client2 = net.connect({ host: 'localhost', port: common.PORT }); - var waiting = 2; + const client1 = net.connect({ host: 'localhost', port: common.PORT }); + const client2 = net.connect({ host: 'localhost', port: common.PORT }); + let waiting = 2; client1.on('close', onclose); client2.on('close', onclose); function onclose() { diff --git a/test/parallel/test-cluster-setup-master-argv.js b/test/parallel/test-cluster-setup-master-argv.js index 32c5a91b3caab4..72211918eff0cb 100644 --- a/test/parallel/test-cluster-setup-master-argv.js +++ b/test/parallel/test-cluster-setup-master-argv.js @@ -6,8 +6,8 @@ const cluster = require('cluster'); setTimeout(common.fail.bind(assert, 'setup not emitted'), 1000).unref(); cluster.on('setup', common.mustCall(function() { - var clusterArgs = cluster.settings.args; - var realArgs = process.argv; + const clusterArgs = cluster.settings.args; + const realArgs = process.argv; assert.strictEqual(clusterArgs[clusterArgs.length - 1], realArgs[realArgs.length - 1]); })); diff --git a/test/parallel/test-cluster-setup-master-multiple.js b/test/parallel/test-cluster-setup-master-multiple.js index a7611b3c23ad4d..25cff7cb33e0c1 100644 --- a/test/parallel/test-cluster-setup-master-multiple.js +++ b/test/parallel/test-cluster-setup-master-multiple.js @@ -13,7 +13,7 @@ function cheapClone(obj) { return JSON.parse(JSON.stringify(obj)); } -var configs = []; +const configs = []; // Capture changes cluster.on('setup', function() { @@ -21,7 +21,7 @@ cluster.on('setup', function() { configs.push(cheapClone(cluster.settings)); }); -var execs = [ +const execs = [ 'node-next', 'node-next-2', 'node-next-3', diff --git a/test/parallel/test-cluster-setup-master.js b/test/parallel/test-cluster-setup-master.js index 4590309f936218..5a92b988e61e5e 100644 --- a/test/parallel/test-cluster-setup-master.js +++ b/test/parallel/test-cluster-setup-master.js @@ -10,14 +10,14 @@ if (cluster.isWorker) { } else if (cluster.isMaster) { - var checks = { + const checks = { args: false, setupEvent: false, settingsObject: false }; - var totalWorkers = 2; - var onlineWorkers = 0; + const totalWorkers = 2; + let onlineWorkers = 0; // Setup master cluster.setupMaster({ @@ -28,7 +28,7 @@ if (cluster.isWorker) { cluster.once('setup', function() { checks.setupEvent = true; - var settings = cluster.settings; + const settings = cluster.settings; if (settings && settings.args && settings.args[0] === 'custom argument' && settings.silent === true && @@ -37,7 +37,7 @@ if (cluster.isWorker) { } }); - var correctIn = 0; + let correctIn = 0; cluster.on('online', function lisenter(worker) { @@ -66,7 +66,7 @@ if (cluster.isWorker) { assert.ok(checks.workers, 'Not all workers went online'); assert.ok(checks.args, 'The arguments was noy send to the worker'); assert.ok(checks.setupEvent, 'The setup event was never emitted'); - var m = 'The settingsObject do not have correct properties'; + const m = 'The settingsObject do not have correct properties'; assert.ok(checks.settingsObject, m); }); diff --git a/test/parallel/test-cluster-shared-leak.js b/test/parallel/test-cluster-shared-leak.js index ad13a869b2b8e0..d578ee6373f3b6 100644 --- a/test/parallel/test-cluster-shared-leak.js +++ b/test/parallel/test-cluster-shared-leak.js @@ -10,9 +10,9 @@ const cluster = require('cluster'); cluster.schedulingPolicy = cluster.SCHED_NONE; if (cluster.isMaster) { - var conn, worker1, worker2; + let conn, worker2; - worker1 = cluster.fork(); + const worker1 = cluster.fork(); worker1.on('message', common.mustCall(function() { worker2 = cluster.fork(); worker2.on('online', function() { diff --git a/test/parallel/test-cluster-worker-death.js b/test/parallel/test-cluster-worker-death.js index 6435232a8103af..7a33721a9aba17 100644 --- a/test/parallel/test-cluster-worker-death.js +++ b/test/parallel/test-cluster-worker-death.js @@ -6,7 +6,7 @@ const cluster = require('cluster'); if (!cluster.isMaster) { process.exit(42); } else { - var worker = cluster.fork(); + const worker = cluster.fork(); worker.on('exit', common.mustCall(function(exitCode, signalCode) { assert.strictEqual(exitCode, 42); assert.strictEqual(signalCode, null); diff --git a/test/parallel/test-cluster-worker-destroy.js b/test/parallel/test-cluster-worker-destroy.js index 30da5954b23971..62000254247a1f 100644 --- a/test/parallel/test-cluster-worker-destroy.js +++ b/test/parallel/test-cluster-worker-destroy.js @@ -10,7 +10,7 @@ const common = require('../common'); const assert = require('assert'); const cluster = require('cluster'); -var worker1, worker2; +let worker1, worker2; if (cluster.isMaster) { worker1 = cluster.fork(); diff --git a/test/parallel/test-cluster-worker-events.js b/test/parallel/test-cluster-worker-events.js index b77a32353b3ce6..6c2e278f5e4639 100644 --- a/test/parallel/test-cluster-worker-events.js +++ b/test/parallel/test-cluster-worker-events.js @@ -3,11 +3,11 @@ require('../common'); const assert = require('assert'); const cluster = require('cluster'); -var OK = 2; +const OK = 2; if (cluster.isMaster) { - var worker = cluster.fork(); + const worker = cluster.fork(); worker.on('exit', function(code) { assert.strictEqual(code, OK); @@ -25,8 +25,8 @@ if (cluster.isMaster) { assert(cluster.isWorker); -var sawProcess; -var sawWorker; +let sawProcess; +let sawWorker; process.on('message', function(m) { assert(!sawProcess); @@ -40,7 +40,7 @@ cluster.worker.on('message', function(m) { check(m); }); -var messages = []; +const messages = []; function check(m) { messages.push(m); diff --git a/test/parallel/test-cluster-worker-forced-exit.js b/test/parallel/test-cluster-worker-forced-exit.js index 1d553a9269b332..828188254724ae 100644 --- a/test/parallel/test-cluster-worker-forced-exit.js +++ b/test/parallel/test-cluster-worker-forced-exit.js @@ -3,7 +3,7 @@ const common = require('../common'); const assert = require('assert'); const cluster = require('cluster'); -var SENTINEL = 42; +const SENTINEL = 42; // workers forcibly exit when control channel is disconnected, if // their .exitedAfterDisconnect flag isn't set diff --git a/test/parallel/test-cluster-worker-isconnected.js b/test/parallel/test-cluster-worker-isconnected.js index 3b17b53e8ae1ae..8b2ad865899c60 100644 --- a/test/parallel/test-cluster-worker-isconnected.js +++ b/test/parallel/test-cluster-worker-isconnected.js @@ -4,7 +4,7 @@ const cluster = require('cluster'); const assert = require('assert'); if (cluster.isMaster) { - var worker = cluster.fork(); + const worker = cluster.fork(); assert.ok(worker.isConnected(), 'isConnected() should return true as soon as the worker has ' + diff --git a/test/parallel/test-cluster-worker-isdead.js b/test/parallel/test-cluster-worker-isdead.js index a80f8410b11a4f..cd360ff248aa13 100644 --- a/test/parallel/test-cluster-worker-isdead.js +++ b/test/parallel/test-cluster-worker-isdead.js @@ -4,7 +4,7 @@ const cluster = require('cluster'); const assert = require('assert'); if (cluster.isMaster) { - var worker = cluster.fork(); + const worker = cluster.fork(); assert.ok(!worker.isDead(), 'isDead() should return false right after the worker has been ' + 'created.'); diff --git a/test/parallel/test-cluster-worker-no-exit.js b/test/parallel/test-cluster-worker-no-exit.js index 9921256c4a74d0..9cfd8401a0c678 100644 --- a/test/parallel/test-cluster-worker-no-exit.js +++ b/test/parallel/test-cluster-worker-no-exit.js @@ -4,10 +4,10 @@ const assert = require('assert'); const cluster = require('cluster'); const net = require('net'); -var destroyed; -var success; -var worker; -var server; +let destroyed; +let success; +let worker; +let server; // workers do not exit on disconnect, they exit under normal node rules: when // they have nothing keeping their loop alive, like an active connection @@ -35,7 +35,7 @@ if (cluster.isMaster) { }); }).listen(common.PORT, function() { - var port = this.address().port; + const port = this.address().port; worker = cluster.fork() .on('online', function() { diff --git a/test/parallel/test-cluster-worker-wait-server-close.js b/test/parallel/test-cluster-worker-wait-server-close.js index cb925822a06f6b..d1a0d73678d67a 100644 --- a/test/parallel/test-cluster-worker-wait-server-close.js +++ b/test/parallel/test-cluster-worker-wait-server-close.js @@ -5,10 +5,10 @@ const assert = require('assert'); const cluster = require('cluster'); const net = require('net'); -var serverClosed = false; +let serverClosed = false; if (cluster.isWorker) { - var server = net.createServer(function(socket) { + const server = net.createServer(function(socket) { // Wait for any data, then close connection socket.write('.'); socket.on('data', function discard() {}); @@ -20,7 +20,7 @@ if (cluster.isWorker) { // Although not typical, the worker process can exit before the disconnect // event fires. Use this to keep the process open until the event has fired. - var keepOpen = setInterval(function() {}, 9999); + const keepOpen = setInterval(function() {}, 9999); // Check worker events and properties process.once('disconnect', function() { @@ -30,7 +30,7 @@ if (cluster.isWorker) { }); } else if (cluster.isMaster) { // start worker - var worker = cluster.fork(); + const worker = cluster.fork(); // Disconnect worker when it is ready worker.once('listening', function() { diff --git a/test/parallel/test-console-instance.js b/test/parallel/test-console-instance.js index 4d2727d96b1a55..4488e893732751 100644 --- a/test/parallel/test-console-instance.js +++ b/test/parallel/test-console-instance.js @@ -3,7 +3,7 @@ require('../common'); const assert = require('assert'); const Stream = require('stream'); const Console = require('console').Console; -var called = false; +let called = false; const out = new Stream(); const err = new Stream(); @@ -32,7 +32,7 @@ assert.throws(function() { out.write = err.write = function(d) {}; -var c = new Console(out, err); +const c = new Console(out, err); out.write = err.write = function(d) { assert.strictEqual(d, 'test\n'); diff --git a/test/parallel/test-console-not-call-toString.js b/test/parallel/test-console-not-call-toString.js index bf8a59072f965b..0c1c209374ac17 100644 --- a/test/parallel/test-console-not-call-toString.js +++ b/test/parallel/test-console-not-call-toString.js @@ -2,8 +2,8 @@ require('../common'); const assert = require('assert'); -var func = function() {}; -var toStringCalled = false; +const func = function() {}; +let toStringCalled = false; func.toString = function() { toStringCalled = true; }; diff --git a/test/parallel/test-crypto-binary-default.js b/test/parallel/test-crypto-binary-default.js index 33a0783fe99963..6ee3aeac36dd89 100644 --- a/test/parallel/test-crypto-binary-default.js +++ b/test/parallel/test-crypto-binary-default.js @@ -53,7 +53,7 @@ const hmacHash = crypto.createHmac('sha1', 'Node') assert.strictEqual(hmacHash, '19fd6e1ba73d9ed2224dd5094a71babe85d9a892'); // Test HMAC-SHA-* (rfc 4231 Test Cases) -var rfc4231 = [ +const rfc4231 = [ { key: Buffer.from('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'), data: Buffer.from('4869205468657265', 'hex'), // 'Hi There' @@ -200,8 +200,8 @@ var rfc4231 = [ ]; for (let i = 0, l = rfc4231.length; i < l; i++) { - for (var hash in rfc4231[i]['hmac']) { - var result = crypto.createHmac(hash, rfc4231[i]['key']) + for (const hash in rfc4231[i]['hmac']) { + let result = crypto.createHmac(hash, rfc4231[i]['key']) .update(rfc4231[i]['data']) .digest('hex'); if (rfc4231[i]['truncate']) { @@ -216,7 +216,7 @@ for (let i = 0, l = rfc4231.length; i < l; i++) { } // Test HMAC-MD5/SHA1 (rfc 2202 Test Cases) -var rfc2202_md5 = [ +const rfc2202_md5 = [ { key: Buffer.from('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'), data: 'Hi There', @@ -269,7 +269,7 @@ var rfc2202_md5 = [ hmac: '6f630fad67cda0ee1fb1f562db3aa53e' } ]; -var rfc2202_sha1 = [ +const rfc2202_sha1 = [ { key: Buffer.from('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'), data: 'Hi There', @@ -346,13 +346,13 @@ for (let i = 0, l = rfc2202_sha1.length; i < l; i++) { } // Test hashing -var a1 = crypto.createHash('sha1').update('Test123').digest('hex'); -var a2 = crypto.createHash('sha256').update('Test123').digest('base64'); -var a3 = crypto.createHash('sha512').update('Test123').digest(); // binary -var a4 = crypto.createHash('sha1').update('Test123').digest('buffer'); +const a1 = crypto.createHash('sha1').update('Test123').digest('hex'); +const a2 = crypto.createHash('sha256').update('Test123').digest('base64'); +const a3 = crypto.createHash('sha512').update('Test123').digest(); // binary +const a4 = crypto.createHash('sha1').update('Test123').digest('buffer'); if (!common.hasFipsCrypto) { - var a0 = crypto.createHash('md5').update('Test123').digest('latin1'); + const a0 = crypto.createHash('md5').update('Test123').digest('latin1'); assert.strictEqual( a0, 'h\u00ea\u00cb\u0097\u00d8o\fF!\u00fa+\u000e\u0017\u00ca\u00bd\u008c', @@ -382,14 +382,14 @@ assert.deepStrictEqual( ); // Test multiple updates to same hash -var h1 = crypto.createHash('sha1').update('Test123').digest('hex'); -var h2 = crypto.createHash('sha1').update('Test').update('123').digest('hex'); +const h1 = crypto.createHash('sha1').update('Test123').digest('hex'); +const h2 = crypto.createHash('sha1').update('Test').update('123').digest('hex'); assert.strictEqual(h1, h2, 'multipled updates'); // Test hashing for binary files -var fn = path.join(common.fixturesDir, 'sample.png'); -var sha1Hash = crypto.createHash('sha1'); -var fileStream = fs.createReadStream(fn); +const fn = path.join(common.fixturesDir, 'sample.png'); +const sha1Hash = crypto.createHash('sha1'); +const fileStream = fs.createReadStream(fn); fileStream.on('data', function(data) { sha1Hash.update(data); }); @@ -407,28 +407,28 @@ assert.throws(function() { }, /^Error: Digest method not supported$/); // Test signing and verifying -var s1 = crypto.createSign('RSA-SHA1') +const s1 = crypto.createSign('RSA-SHA1') .update('Test123') .sign(keyPem, 'base64'); -var s1Verified = crypto.createVerify('RSA-SHA1') +const s1Verified = crypto.createVerify('RSA-SHA1') .update('Test') .update('123') .verify(certPem, s1, 'base64'); assert.strictEqual(s1Verified, true, 'sign and verify (base 64)'); -var s2 = crypto.createSign('RSA-SHA256') +const s2 = crypto.createSign('RSA-SHA256') .update('Test123') .sign(keyPem); // binary -var s2Verified = crypto.createVerify('RSA-SHA256') +const s2Verified = crypto.createVerify('RSA-SHA256') .update('Test') .update('123') .verify(certPem, s2); // binary assert.strictEqual(s2Verified, true, 'sign and verify (binary)'); -var s3 = crypto.createSign('RSA-SHA1') +const s3 = crypto.createSign('RSA-SHA1') .update('Test123') .sign(keyPem, 'buffer'); -var s3Verified = crypto.createVerify('RSA-SHA1') +const s3Verified = crypto.createVerify('RSA-SHA1') .update('Test') .update('123') .verify(certPem, s3); @@ -437,17 +437,17 @@ assert.strictEqual(s3Verified, true, 'sign and verify (buffer)'); function testCipher1(key) { // Test encryption and decryption - var plaintext = 'Keep this a secret? No! Tell everyone about node.js!'; - var cipher = crypto.createCipher('aes192', key); + const plaintext = 'Keep this a secret? No! Tell everyone about node.js!'; + const cipher = crypto.createCipher('aes192', key); // encrypt plaintext which is in utf8 format // to a ciphertext which will be in hex - var ciph = cipher.update(plaintext, 'utf8', 'hex'); + let ciph = cipher.update(plaintext, 'utf8', 'hex'); // Only use binary or hex, not base64. ciph += cipher.final('hex'); - var decipher = crypto.createDecipher('aes192', key); - var txt = decipher.update(ciph, 'hex', 'utf8'); + const decipher = crypto.createDecipher('aes192', key); + let txt = decipher.update(ciph, 'hex', 'utf8'); txt += decipher.final('utf8'); assert.strictEqual(txt, plaintext, 'encryption and decryption'); @@ -457,19 +457,19 @@ function testCipher1(key) { function testCipher2(key) { // encryption and decryption with Base64 // reported in https://github.com/joyent/node/issues/738 - var plaintext = + const plaintext = '32|RmVZZkFUVmpRRkp0TmJaUm56ZU9qcnJkaXNNWVNpTTU*|iXmckfRWZBGWWELw' + 'eCBsThSsfUHLeRe0KCsK8ooHgxie0zOINpXxfZi/oNG7uq9JWFVCk70gfzQH8ZUJ' + 'jAfaFg**'; - var cipher = crypto.createCipher('aes256', key); + const cipher = crypto.createCipher('aes256', key); // encrypt plaintext which is in utf8 format // to a ciphertext which will be in Base64 - var ciph = cipher.update(plaintext, 'utf8', 'base64'); + let ciph = cipher.update(plaintext, 'utf8', 'base64'); ciph += cipher.final('base64'); - var decipher = crypto.createDecipher('aes256', key); - var txt = decipher.update(ciph, 'base64', 'utf8'); + const decipher = crypto.createDecipher('aes256', key); + let txt = decipher.update(ciph, 'base64', 'utf8'); txt += decipher.final('utf8'); assert.strictEqual(txt, plaintext, 'encryption and decryption with Base64'); @@ -478,16 +478,16 @@ function testCipher2(key) { function testCipher3(key, iv) { // Test encyrption and decryption with explicit key and iv - var plaintext = + const plaintext = '32|RmVZZkFUVmpRRkp0TmJaUm56ZU9qcnJkaXNNWVNpTTU*|iXmckfRWZBGWWELw' + 'eCBsThSsfUHLeRe0KCsK8ooHgxie0zOINpXxfZi/oNG7uq9JWFVCk70gfzQH8ZUJ' + 'jAfaFg**'; - var cipher = crypto.createCipheriv('des-ede3-cbc', key, iv); - var ciph = cipher.update(plaintext, 'utf8', 'hex'); + const cipher = crypto.createCipheriv('des-ede3-cbc', key, iv); + let ciph = cipher.update(plaintext, 'utf8', 'hex'); ciph += cipher.final('hex'); - var decipher = crypto.createDecipheriv('des-ede3-cbc', key, iv); - var txt = decipher.update(ciph, 'hex', 'utf8'); + const decipher = crypto.createDecipheriv('des-ede3-cbc', key, iv); + let txt = decipher.update(ciph, 'hex', 'utf8'); txt += decipher.final('utf8'); assert.strictEqual(txt, plaintext, @@ -497,16 +497,16 @@ function testCipher3(key, iv) { function testCipher4(key, iv) { // Test encyrption and decryption with explicit key and iv - var plaintext = + const plaintext = '32|RmVZZkFUVmpRRkp0TmJaUm56ZU9qcnJkaXNNWVNpTTU*|iXmckfRWZBGWWELw' + 'eCBsThSsfUHLeRe0KCsK8ooHgxie0zOINpXxfZi/oNG7uq9JWFVCk70gfzQH8ZUJ' + 'jAfaFg**'; - var cipher = crypto.createCipheriv('des-ede3-cbc', key, iv); - var ciph = cipher.update(plaintext, 'utf8', 'buffer'); + const cipher = crypto.createCipheriv('des-ede3-cbc', key, iv); + let ciph = cipher.update(plaintext, 'utf8', 'buffer'); ciph = Buffer.concat([ciph, cipher.final('buffer')]); - var decipher = crypto.createDecipheriv('des-ede3-cbc', key, iv); - var txt = decipher.update(ciph, 'buffer', 'utf8'); + const decipher = crypto.createDecipheriv('des-ede3-cbc', key, iv); + let txt = decipher.update(ciph, 'buffer', 'utf8'); txt += decipher.final('utf8'); assert.strictEqual(txt, plaintext, @@ -537,20 +537,20 @@ assert.throws(function() { // Test Diffie-Hellman with two parties sharing a secret, // using various encodings as we go along -var dh1 = crypto.createDiffieHellman(common.hasFipsCrypto ? 1024 : 256); -var p1 = dh1.getPrime('buffer'); -var dh2 = crypto.createDiffieHellman(p1, 'base64'); -var key1 = dh1.generateKeys(); -var key2 = dh2.generateKeys('hex'); -var secret1 = dh1.computeSecret(key2, 'hex', 'base64'); -var secret2 = dh2.computeSecret(key1, 'latin1', 'buffer'); +const dh1 = crypto.createDiffieHellman(common.hasFipsCrypto ? 1024 : 256); +const p1 = dh1.getPrime('buffer'); +const dh2 = crypto.createDiffieHellman(p1, 'base64'); +const key1 = dh1.generateKeys(); +const key2 = dh2.generateKeys('hex'); +const secret1 = dh1.computeSecret(key2, 'hex', 'base64'); +const secret2 = dh2.computeSecret(key1, 'latin1', 'buffer'); assert.strictEqual(secret1, secret2.toString('base64')); // Create "another dh1" using generated keys from dh1, // and compute secret again -var dh3 = crypto.createDiffieHellman(p1, 'buffer'); -var privkey1 = dh1.getPrivateKey(); +const dh3 = crypto.createDiffieHellman(p1, 'buffer'); +const privkey1 = dh1.getPrivateKey(); dh3.setPublicKey(key1); dh3.setPrivateKey(privkey1); @@ -559,26 +559,26 @@ assert.strictEqual(dh1.getGenerator(), dh3.getGenerator()); assert.strictEqual(dh1.getPublicKey(), dh3.getPublicKey()); assert.strictEqual(dh1.getPrivateKey(), dh3.getPrivateKey()); -var secret3 = dh3.computeSecret(key2, 'hex', 'base64'); +const secret3 = dh3.computeSecret(key2, 'hex', 'base64'); assert.strictEqual(secret1, secret3); // https://github.com/joyent/node/issues/2338 -var p = 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74' + - '020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F1437' + - '4FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' + - 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF'; -var d = crypto.createDiffieHellman(p, 'hex'); +const p = 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74' + + '020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F1437' + + '4FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' + + 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF'; +const d = crypto.createDiffieHellman(p, 'hex'); assert.strictEqual(d.verifyError, DH_NOT_SUITABLE_GENERATOR); // Test RSA key signing/verification -var rsaSign = crypto.createSign('RSA-SHA1'); -var rsaVerify = crypto.createVerify('RSA-SHA1'); +const rsaSign = crypto.createSign('RSA-SHA1'); +const rsaVerify = crypto.createVerify('RSA-SHA1'); assert.ok(rsaSign instanceof crypto.Sign); assert.ok(rsaVerify instanceof crypto.Verify); rsaSign.update(rsaPubPem); -var rsaSignature = rsaSign.sign(rsaKeyPem, 'hex'); +const rsaSignature = rsaSign.sign(rsaKeyPem, 'hex'); assert.strictEqual( rsaSignature, '5c50e3145c4e2497aadb0eabc83b342d0b0021ece0d4c4a064b7c' + diff --git a/test/parallel/test-crypto-certificate.js b/test/parallel/test-crypto-certificate.js index 24c3163e3b2d90..ebd83b019ba146 100644 --- a/test/parallel/test-crypto-certificate.js +++ b/test/parallel/test-crypto-certificate.js @@ -13,11 +13,11 @@ crypto.DEFAULT_ENCODING = 'buffer'; const fs = require('fs'); // Test Certificates -var spkacValid = fs.readFileSync(common.fixturesDir + '/spkac.valid'); -var spkacFail = fs.readFileSync(common.fixturesDir + '/spkac.fail'); -var spkacPem = fs.readFileSync(common.fixturesDir + '/spkac.pem'); +const spkacValid = fs.readFileSync(common.fixturesDir + '/spkac.valid'); +const spkacFail = fs.readFileSync(common.fixturesDir + '/spkac.fail'); +const spkacPem = fs.readFileSync(common.fixturesDir + '/spkac.pem'); -var certificate = new crypto.Certificate(); +const certificate = new crypto.Certificate(); assert.strictEqual(certificate.verifySpkac(spkacValid), true); assert.strictEqual(certificate.verifySpkac(spkacFail), false); diff --git a/test/parallel/test-crypto-dh-odd-key.js b/test/parallel/test-crypto-dh-odd-key.js index 92fab2b8c2a178..f6bfcf72c0fd7e 100644 --- a/test/parallel/test-crypto-dh-odd-key.js +++ b/test/parallel/test-crypto-dh-odd-key.js @@ -9,9 +9,9 @@ if (!common.hasCrypto) { const crypto = require('crypto'); function test() { - var odd = Buffer.alloc(39, 'A'); + const odd = Buffer.alloc(39, 'A'); - var c = crypto.createDiffieHellman(32); + const c = crypto.createDiffieHellman(32); c.setPrivateKey(odd); c.generateKeys(); } diff --git a/test/parallel/test-crypto-dh.js b/test/parallel/test-crypto-dh.js index 6a067bef1be066..2a06fc6e7b86d6 100644 --- a/test/parallel/test-crypto-dh.js +++ b/test/parallel/test-crypto-dh.js @@ -11,13 +11,13 @@ const DH_NOT_SUITABLE_GENERATOR = crypto.constants.DH_NOT_SUITABLE_GENERATOR; // Test Diffie-Hellman with two parties sharing a secret, // using various encodings as we go along -var dh1 = crypto.createDiffieHellman(common.hasFipsCrypto ? 1024 : 256); -var p1 = dh1.getPrime('buffer'); -var dh2 = crypto.createDiffieHellman(p1, 'buffer'); -var key1 = dh1.generateKeys(); -var key2 = dh2.generateKeys('hex'); -var secret1 = dh1.computeSecret(key2, 'hex', 'base64'); -var secret2 = dh2.computeSecret(key1, 'latin1', 'buffer'); +const dh1 = crypto.createDiffieHellman(common.hasFipsCrypto ? 1024 : 256); +const p1 = dh1.getPrime('buffer'); +const dh2 = crypto.createDiffieHellman(p1, 'buffer'); +let key1 = dh1.generateKeys(); +let key2 = dh2.generateKeys('hex'); +let secret1 = dh1.computeSecret(key2, 'hex', 'base64'); +let secret2 = dh2.computeSecret(key1, 'latin1', 'buffer'); assert.equal(secret1, secret2.toString('base64')); assert.equal(dh1.verifyError, 0); @@ -41,8 +41,8 @@ assert.throws(function() { // Create "another dh1" using generated keys from dh1, // and compute secret again -var dh3 = crypto.createDiffieHellman(p1, 'buffer'); -var privkey1 = dh1.getPrivateKey(); +const dh3 = crypto.createDiffieHellman(p1, 'buffer'); +const privkey1 = dh1.getPrivateKey(); dh3.setPublicKey(key1); dh3.setPrivateKey(privkey1); @@ -52,7 +52,7 @@ assert.deepStrictEqual(dh1.getPublicKey(), dh3.getPublicKey()); assert.deepStrictEqual(dh1.getPrivateKey(), dh3.getPrivateKey()); assert.equal(dh3.verifyError, 0); -var secret3 = dh3.computeSecret(key2, 'hex', 'base64'); +const secret3 = dh3.computeSecret(key2, 'hex', 'base64'); assert.equal(secret1, secret3); @@ -72,12 +72,12 @@ assert.throws(function() { } // Create a shared using a DH group. -var alice = crypto.createDiffieHellmanGroup('modp5'); -var bob = crypto.createDiffieHellmanGroup('modp5'); +const alice = crypto.createDiffieHellmanGroup('modp5'); +const bob = crypto.createDiffieHellmanGroup('modp5'); alice.generateKeys(); bob.generateKeys(); -var aSecret = alice.computeSecret(bob.getPublicKey()).toString('hex'); -var bSecret = bob.computeSecret(alice.getPublicKey()).toString('hex'); +const aSecret = alice.computeSecret(bob.getPublicKey()).toString('hex'); +const bSecret = bob.computeSecret(alice.getPublicKey()).toString('hex'); assert.equal(aSecret, bSecret); assert.equal(alice.verifyError, DH_NOT_SUITABLE_GENERATOR); assert.equal(bob.verifyError, DH_NOT_SUITABLE_GENERATOR); @@ -85,8 +85,8 @@ assert.equal(bob.verifyError, DH_NOT_SUITABLE_GENERATOR); /* Ensure specific generator (buffer) works as expected. * The values below (modp2/modp2buf) are for a 1024 bits long prime from * RFC 2412 E.2, see https://tools.ietf.org/html/rfc2412. */ -var modp2 = crypto.createDiffieHellmanGroup('modp2'); -var modp2buf = Buffer.from([ +const modp2 = crypto.createDiffieHellmanGroup('modp2'); +const modp2buf = Buffer.from([ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9, 0x0f, 0xda, 0xa2, 0x21, 0x68, 0xc2, 0x34, 0xc4, 0xc6, 0x62, 0x8b, 0x80, 0xdc, 0x1c, 0xd1, 0x29, 0x02, 0x4e, 0x08, 0x8a, 0x67, @@ -101,51 +101,52 @@ var modp2buf = Buffer.from([ 0x1f, 0xe6, 0x49, 0x28, 0x66, 0x51, 0xec, 0xe6, 0x53, 0x81, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff ]); -var exmodp2 = crypto.createDiffieHellman(modp2buf, Buffer.from([2])); +const exmodp2 = crypto.createDiffieHellman(modp2buf, Buffer.from([2])); modp2.generateKeys(); exmodp2.generateKeys(); -var modp2Secret = modp2.computeSecret(exmodp2.getPublicKey()).toString('hex'); -var exmodp2Secret = exmodp2.computeSecret(modp2.getPublicKey()).toString('hex'); +let modp2Secret = modp2.computeSecret(exmodp2.getPublicKey()).toString('hex'); +const exmodp2Secret = exmodp2.computeSecret(modp2.getPublicKey()) + .toString('hex'); assert.equal(modp2Secret, exmodp2Secret); assert.equal(modp2.verifyError, DH_NOT_SUITABLE_GENERATOR); assert.equal(exmodp2.verifyError, DH_NOT_SUITABLE_GENERATOR); // Ensure specific generator (string with encoding) works as expected. -var exmodp2_2 = crypto.createDiffieHellman(modp2buf, '02', 'hex'); +const exmodp2_2 = crypto.createDiffieHellman(modp2buf, '02', 'hex'); exmodp2_2.generateKeys(); modp2Secret = modp2.computeSecret(exmodp2_2.getPublicKey()).toString('hex'); -var exmodp2_2Secret = exmodp2_2.computeSecret(modp2.getPublicKey()) - .toString('hex'); +const exmodp2_2Secret = exmodp2_2.computeSecret(modp2.getPublicKey()) + .toString('hex'); assert.equal(modp2Secret, exmodp2_2Secret); assert.equal(exmodp2_2.verifyError, DH_NOT_SUITABLE_GENERATOR); // Ensure specific generator (string without encoding) works as expected. -var exmodp2_3 = crypto.createDiffieHellman(modp2buf, '\x02'); +const exmodp2_3 = crypto.createDiffieHellman(modp2buf, '\x02'); exmodp2_3.generateKeys(); modp2Secret = modp2.computeSecret(exmodp2_3.getPublicKey()).toString('hex'); -var exmodp2_3Secret = exmodp2_3.computeSecret(modp2.getPublicKey()) +const exmodp2_3Secret = exmodp2_3.computeSecret(modp2.getPublicKey()) .toString('hex'); assert.equal(modp2Secret, exmodp2_3Secret); assert.equal(exmodp2_3.verifyError, DH_NOT_SUITABLE_GENERATOR); // Ensure specific generator (numeric) works as expected. -var exmodp2_4 = crypto.createDiffieHellman(modp2buf, 2); +const exmodp2_4 = crypto.createDiffieHellman(modp2buf, 2); exmodp2_4.generateKeys(); modp2Secret = modp2.computeSecret(exmodp2_4.getPublicKey()).toString('hex'); -var exmodp2_4Secret = exmodp2_4.computeSecret(modp2.getPublicKey()) +const exmodp2_4Secret = exmodp2_4.computeSecret(modp2.getPublicKey()) .toString('hex'); assert.equal(modp2Secret, exmodp2_4Secret); assert.equal(exmodp2_4.verifyError, DH_NOT_SUITABLE_GENERATOR); -var p = 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74' + - '020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F1437' + - '4FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' + - 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF'; -var bad_dh = crypto.createDiffieHellman(p, 'hex'); +const p = 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74' + + '020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F1437' + + '4FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' + + 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF'; +const bad_dh = crypto.createDiffieHellman(p, 'hex'); assert.equal(bad_dh.verifyError, DH_NOT_SUITABLE_GENERATOR); diff --git a/test/parallel/test-crypto-domain.js b/test/parallel/test-crypto-domain.js index fcbbcb8e0524f2..6586f7d48a94ce 100644 --- a/test/parallel/test-crypto-domain.js +++ b/test/parallel/test-crypto-domain.js @@ -10,12 +10,12 @@ if (!common.hasCrypto) { const crypto = require('crypto'); function test(fn) { - var ex = new Error('BAM'); - var d = domain.create(); + const ex = new Error('BAM'); + const d = domain.create(); d.on('error', common.mustCall(function(err) { assert.strictEqual(err, ex); })); - var cb = common.mustCall(function() { + const cb = common.mustCall(function() { throw ex; }); d.run(cb); diff --git a/test/parallel/test-crypto-domains.js b/test/parallel/test-crypto-domains.js index 738ed15323ba01..2749382fa5c780 100644 --- a/test/parallel/test-crypto-domains.js +++ b/test/parallel/test-crypto-domains.js @@ -2,8 +2,8 @@ const common = require('../common'); const domain = require('domain'); const assert = require('assert'); -var d = domain.create(); -var expect = ['pbkdf2', 'randomBytes', 'pseudoRandomBytes']; +const d = domain.create(); +const expect = ['pbkdf2', 'randomBytes', 'pseudoRandomBytes']; if (!common.hasCrypto) { common.skip('missing crypto'); diff --git a/test/parallel/test-crypto-fips.js b/test/parallel/test-crypto-fips.js index f27c59624730d2..6fd3352740c8c3 100644 --- a/test/parallel/test-crypto-fips.js +++ b/test/parallel/test-crypto-fips.js @@ -15,14 +15,14 @@ const FIPS_ERROR_STRING = 'Error: Cannot set FIPS mode'; const OPTION_ERROR_STRING = 'bad option'; const CNF_FIPS_ON = path.join(common.fixturesDir, 'openssl_fips_enabled.cnf'); const CNF_FIPS_OFF = path.join(common.fixturesDir, 'openssl_fips_disabled.cnf'); -var num_children_ok = 0; +let num_children_ok = 0; function compiledWithFips() { return process.config.variables.openssl_fips ? true : false; } function addToEnv(newVar, value) { - var envCopy = {}; + const envCopy = {}; for (const e in process.env) { envCopy[e] = process.env[e]; } diff --git a/test/parallel/test-crypto-from-binary.js b/test/parallel/test-crypto-from-binary.js index ec39606506b7b7..485735e83ce5cc 100644 --- a/test/parallel/test-crypto-from-binary.js +++ b/test/parallel/test-crypto-from-binary.js @@ -12,10 +12,10 @@ if (!common.hasCrypto) { } const crypto = require('crypto'); -var EXTERN_APEX = 0xFBEE9; +const EXTERN_APEX = 0xFBEE9; // manually controlled string for checking binary output -var ucs2_control = 'a\u0000'; +let ucs2_control = 'a\u0000'; // grow the strings to proper length while (ucs2_control.length <= EXTERN_APEX) { @@ -24,7 +24,7 @@ while (ucs2_control.length <= EXTERN_APEX) { // check resultant buffer and output string -var b = Buffer.from(ucs2_control + ucs2_control, 'ucs2'); +const b = Buffer.from(ucs2_control + ucs2_control, 'ucs2'); // // Test updating from birant data diff --git a/test/parallel/test-crypto-hash.js b/test/parallel/test-crypto-hash.js index 10135d2950c212..0d55d4236a656e 100644 --- a/test/parallel/test-crypto-hash.js +++ b/test/parallel/test-crypto-hash.js @@ -11,34 +11,34 @@ if (!common.hasCrypto) { const crypto = require('crypto'); // Test hashing -var a1 = crypto.createHash('sha1').update('Test123').digest('hex'); -var a2 = crypto.createHash('sha256').update('Test123').digest('base64'); -var a3 = crypto.createHash('sha512').update('Test123').digest(); // buffer -var a4 = crypto.createHash('sha1').update('Test123').digest('buffer'); +const a1 = crypto.createHash('sha1').update('Test123').digest('hex'); +const a2 = crypto.createHash('sha256').update('Test123').digest('base64'); +const a3 = crypto.createHash('sha512').update('Test123').digest(); // buffer +const a4 = crypto.createHash('sha1').update('Test123').digest('buffer'); // stream interface -var a5 = crypto.createHash('sha512'); +let a5 = crypto.createHash('sha512'); a5.end('Test123'); a5 = a5.read(); -var a6 = crypto.createHash('sha512'); +let a6 = crypto.createHash('sha512'); a6.write('Te'); a6.write('st'); a6.write('123'); a6.end(); a6 = a6.read(); -var a7 = crypto.createHash('sha512'); +let a7 = crypto.createHash('sha512'); a7.end(); a7 = a7.read(); -var a8 = crypto.createHash('sha512'); +let a8 = crypto.createHash('sha512'); a8.write(''); a8.end(); a8 = a8.read(); if (!common.hasFipsCrypto) { - var a0 = crypto.createHash('md5').update('Test123').digest('latin1'); + const a0 = crypto.createHash('md5').update('Test123').digest('latin1'); assert.strictEqual( a0, 'h\u00ea\u00cb\u0097\u00d8o\fF!\u00fa+\u000e\u0017\u00ca\u00bd\u008c', @@ -71,14 +71,14 @@ assert.notStrictEqual(a7, undefined, 'no data should return data'); assert.notStrictEqual(a8, undefined, 'empty string should generate data'); // Test multiple updates to same hash -var h1 = crypto.createHash('sha1').update('Test123').digest('hex'); -var h2 = crypto.createHash('sha1').update('Test').update('123').digest('hex'); +const h1 = crypto.createHash('sha1').update('Test123').digest('hex'); +const h2 = crypto.createHash('sha1').update('Test').update('123').digest('hex'); assert.strictEqual(h1, h2, 'multipled updates'); // Test hashing for binary files -var fn = path.join(common.fixturesDir, 'sample.png'); -var sha1Hash = crypto.createHash('sha1'); -var fileStream = fs.createReadStream(fn); +const fn = path.join(common.fixturesDir, 'sample.png'); +const sha1Hash = crypto.createHash('sha1'); +const fileStream = fs.createReadStream(fn); fileStream.on('data', function(data) { sha1Hash.update(data); }); @@ -94,7 +94,7 @@ assert.throws(function() { }, /Digest method not supported/); // Default UTF-8 encoding -var hutf8 = crypto.createHash('sha512').update('УТФ-8 text').digest('hex'); +const hutf8 = crypto.createHash('sha512').update('УТФ-8 text').digest('hex'); assert.strictEqual( hutf8, '4b21bbd1a68e690a730ddcb5a8bc94ead9879ffe82580767ad7ec6fa8ba2dea6' + @@ -104,7 +104,7 @@ assert.notStrictEqual( hutf8, crypto.createHash('sha512').update('УТФ-8 text', 'latin1').digest('hex')); -var h3 = crypto.createHash('sha256'); +const h3 = crypto.createHash('sha256'); h3.digest(); assert.throws(function() { h3.digest(); diff --git a/test/parallel/test-crypto-hmac.js b/test/parallel/test-crypto-hmac.js index ef4e59a1dd944c..a3372bcb7242b9 100644 --- a/test/parallel/test-crypto-hmac.js +++ b/test/parallel/test-crypto-hmac.js @@ -17,14 +17,14 @@ const crypto = require('crypto'); } // Test HMAC -var h1 = crypto.createHmac('sha1', 'Node') +const h1 = crypto.createHmac('sha1', 'Node') .update('some data') .update('to hmac') .digest('hex'); assert.strictEqual(h1, '19fd6e1ba73d9ed2224dd5094a71babe85d9a892', 'test HMAC'); // Test HMAC (Wikipedia Test Cases) -var wikipedia = [ +const wikipedia = [ { key: 'key', data: 'The quick brown fox jumps over the lazy dog', hmac: { // HMACs lifted from Wikipedia. @@ -83,7 +83,7 @@ for (let i = 0, l = wikipedia.length; i < l; i++) { // Test HMAC-SHA-* (rfc 4231 Test Cases) -var rfc4231 = [ +const rfc4231 = [ { key: Buffer.from('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'), data: Buffer.from('4869205468657265', 'hex'), // 'Hi There' @@ -249,7 +249,7 @@ for (let i = 0, l = rfc4231.length; i < l; i++) { } // Test HMAC-MD5/SHA1 (rfc 2202 Test Cases) -var rfc2202_md5 = [ +const rfc2202_md5 = [ { key: Buffer.from('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'), data: 'Hi There', @@ -302,7 +302,7 @@ var rfc2202_md5 = [ hmac: '6f630fad67cda0ee1fb1f562db3aa53e' } ]; -var rfc2202_sha1 = [ +const rfc2202_sha1 = [ { key: Buffer.from('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'), data: 'Hi There', diff --git a/test/parallel/test-crypto-rsa-dsa.js b/test/parallel/test-crypto-rsa-dsa.js index d894e0dcafd9eb..bb529f2454dbc8 100644 --- a/test/parallel/test-crypto-rsa-dsa.js +++ b/test/parallel/test-crypto-rsa-dsa.js @@ -158,7 +158,7 @@ assert.strictEqual(rsaVerify.verify(rsaPubPem, rsaSignature, 'hex'), true); rsaSign = crypto.createSign('RSA-SHA1'); rsaSign.update(rsaPubPem); assert.doesNotThrow(() => { - var signOptions = { key: rsaKeyPemEncrypted, passphrase: 'password' }; + const signOptions = { key: rsaKeyPemEncrypted, passphrase: 'password' }; rsaSignature = rsaSign.sign(signOptions, 'hex'); }); assert.strictEqual(rsaSignature, expectedSignature); @@ -170,7 +170,7 @@ assert.strictEqual(rsaVerify.verify(rsaPubPem, rsaSignature, 'hex'), true); rsaSign = crypto.createSign('RSA-SHA1'); rsaSign.update(rsaPubPem); assert.throws(() => { - var signOptions = { key: rsaKeyPemEncrypted, passphrase: 'wrong' }; + const signOptions = { key: rsaKeyPemEncrypted, passphrase: 'wrong' }; rsaSign.sign(signOptions, 'hex'); }, decryptError); diff --git a/test/parallel/test-crypto-sign-verify.js b/test/parallel/test-crypto-sign-verify.js index 05f29a710466ee..ae78cd9d8b3420 100644 --- a/test/parallel/test-crypto-sign-verify.js +++ b/test/parallel/test-crypto-sign-verify.js @@ -10,8 +10,8 @@ if (!common.hasCrypto) { const crypto = require('crypto'); // Test certificates -var certPem = fs.readFileSync(common.fixturesDir + '/test_cert.pem', 'ascii'); -var keyPem = fs.readFileSync(common.fixturesDir + '/test_key.pem', 'ascii'); +const certPem = fs.readFileSync(common.fixturesDir + '/test_cert.pem', 'ascii'); +const keyPem = fs.readFileSync(common.fixturesDir + '/test_key.pem', 'ascii'); // Test signing and verifying { diff --git a/test/parallel/test-crypto-stream.js b/test/parallel/test-crypto-stream.js index 06b483b326279f..f558851b7940a0 100644 --- a/test/parallel/test-crypto-stream.js +++ b/test/parallel/test-crypto-stream.js @@ -28,7 +28,7 @@ Stream2buffer.prototype._write = function(data, encodeing, done) { if (!common.hasFipsCrypto) { // Create an md5 hash of "Hallo world" - var hasher1 = crypto.createHash('md5'); + const hasher1 = crypto.createHash('md5'); hasher1.pipe(new Stream2buffer(common.mustCall(function end(err, hash) { assert.strictEqual(err, null); assert.strictEqual( diff --git a/test/parallel/test-crypto-verify-failure.js b/test/parallel/test-crypto-verify-failure.js index f840c017b4b2d4..c171814dd3c3a6 100644 --- a/test/parallel/test-crypto-verify-failure.js +++ b/test/parallel/test-crypto-verify-failure.js @@ -12,14 +12,14 @@ crypto.DEFAULT_ENCODING = 'buffer'; const fs = require('fs'); -var certPem = fs.readFileSync(common.fixturesDir + '/test_cert.pem', 'ascii'); +const certPem = fs.readFileSync(common.fixturesDir + '/test_cert.pem', 'ascii'); -var options = { +const options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }; -var server = tls.Server(options, function(socket) { +const server = tls.Server(options, function(socket) { setImmediate(function() { console.log('sending'); verify(); diff --git a/test/parallel/test-cwd-enoent-repl.js b/test/parallel/test-cwd-enoent-repl.js index da7729b286519e..942fc07b64a90b 100644 --- a/test/parallel/test-cwd-enoent-repl.js +++ b/test/parallel/test-cwd-enoent-repl.js @@ -10,13 +10,13 @@ if (common.isSunOS || common.isWindows || common.isAix) { return; } -var dirname = common.tmpDir + '/cwd-does-not-exist-' + process.pid; +const dirname = common.tmpDir + '/cwd-does-not-exist-' + process.pid; common.refreshTmpDir(); fs.mkdirSync(dirname); process.chdir(dirname); fs.rmdirSync(dirname); -var proc = spawn(process.execPath, ['--interactive']); +const proc = spawn(process.execPath, ['--interactive']); proc.stdout.pipe(process.stdout); proc.stderr.pipe(process.stderr); proc.stdin.write('require("path");\n'); diff --git a/test/parallel/test-cwd-enoent.js b/test/parallel/test-cwd-enoent.js index bb26a6e879784b..736121a7c89d6e 100644 --- a/test/parallel/test-cwd-enoent.js +++ b/test/parallel/test-cwd-enoent.js @@ -10,13 +10,13 @@ if (common.isSunOS || common.isWindows || common.isAix) { return; } -var dirname = common.tmpDir + '/cwd-does-not-exist-' + process.pid; +const dirname = common.tmpDir + '/cwd-does-not-exist-' + process.pid; common.refreshTmpDir(); fs.mkdirSync(dirname); process.chdir(dirname); fs.rmdirSync(dirname); -var proc = spawn(process.execPath, ['-e', '0']); +const proc = spawn(process.execPath, ['-e', '0']); proc.stdout.pipe(process.stdout); proc.stderr.pipe(process.stderr); diff --git a/test/parallel/test-debug-brk.js b/test/parallel/test-debug-brk.js index 89d9c892145676..769e3a6c5b504e 100644 --- a/test/parallel/test-debug-brk.js +++ b/test/parallel/test-debug-brk.js @@ -7,13 +7,13 @@ let run = () => {}; function test(extraArgs, stdoutPattern) { const next = run; run = () => { - var procStdout = ''; - var procStderr = ''; - var agentStdout = ''; - var debuggerListening = false; - var outputMatched = false; - var needToSpawnAgent = true; - var needToExit = true; + let procStdout = ''; + let procStderr = ''; + let agentStdout = ''; + let debuggerListening = false; + let outputMatched = false; + let needToSpawnAgent = true; + let needToExit = true; const procArgs = [`--debug-brk=${common.PORT}`].concat(extraArgs); const proc = spawn(process.execPath, procArgs); diff --git a/test/parallel/test-debug-port-from-cmdline.js b/test/parallel/test-debug-port-from-cmdline.js index f0ff853b16df82..53f35877a2f382 100644 --- a/test/parallel/test-debug-port-from-cmdline.js +++ b/test/parallel/test-debug-port-from-cmdline.js @@ -3,15 +3,15 @@ const common = require('../common'); const assert = require('assert'); const spawn = require('child_process').spawn; -var debugPort = common.PORT; -var args = ['--interactive', '--debug-port=' + debugPort]; -var childOptions = { stdio: ['pipe', 'pipe', 'pipe', 'ipc'] }; -var child = spawn(process.execPath, args, childOptions); +const debugPort = common.PORT; +const args = ['--interactive', '--debug-port=' + debugPort]; +const childOptions = { stdio: ['pipe', 'pipe', 'pipe', 'ipc'] }; +const child = spawn(process.execPath, args, childOptions); child.stdin.write("process.send({ msg: 'childready' });\n"); child.stderr.on('data', function(data) { - var lines = data.toString().replace(/\r/g, '').trim().split('\n'); + const lines = data.toString().replace(/\r/g, '').trim().split('\n'); lines.forEach(processStderrLine); }); @@ -26,7 +26,7 @@ process.on('exit', function() { assertOutputLines(); }); -var outputLines = []; +const outputLines = []; function processStderrLine(line) { console.log('> ' + line); outputLines.push(line); @@ -37,12 +37,12 @@ function processStderrLine(line) { } function assertOutputLines() { - var expectedLines = [ + const expectedLines = [ 'Starting debugger agent.', 'Debugger listening on 127.0.0.1:' + debugPort, ]; assert.strictEqual(outputLines.length, expectedLines.length); - for (var i = 0; i < expectedLines.length; i++) + for (let i = 0; i < expectedLines.length; i++) assert(expectedLines[i].includes(outputLines[i])); } diff --git a/test/parallel/test-debug-signal-cluster.js b/test/parallel/test-debug-signal-cluster.js index 24b362a687988a..89b3ca456d3248 100644 --- a/test/parallel/test-debug-signal-cluster.js +++ b/test/parallel/test-debug-signal-cluster.js @@ -12,7 +12,7 @@ const args = [`--debug-port=${port}`, serverPath]; const options = { stdio: ['inherit', 'inherit', 'pipe', 'ipc'] }; const child = spawn(process.execPath, args, options); -var expectedContent = [ +let expectedContent = [ 'Starting debugger agent.', 'Debugger listening on 127.0.0.1:' + (port + 0), 'Starting debugger agent.', @@ -22,10 +22,10 @@ var expectedContent = [ ].join(os.EOL); expectedContent += os.EOL; // the last line also contains an EOL character -var debuggerAgentsOutput = ''; -var debuggerAgentsStarted = false; +let debuggerAgentsOutput = ''; +let debuggerAgentsStarted = false; -var pids; +let pids; child.stderr.on('data', function(data) { const childStderrOutputString = data.toString(); diff --git a/test/parallel/test-debug-uncaught-exception-async.js b/test/parallel/test-debug-uncaught-exception-async.js index 29947cfd92fbb9..8d0d7957c22e12 100644 --- a/test/parallel/test-debug-uncaught-exception-async.js +++ b/test/parallel/test-debug-uncaught-exception-async.js @@ -7,7 +7,7 @@ const spawn = require('child_process').spawn; const emitUncaught = path.join(common.fixturesDir, 'debug-uncaught-async.js'); const result = spawn(process.execPath, [emitUncaught], {encoding: 'utf8'}); -var stderr = ''; +let stderr = ''; result.stderr.on('data', (data) => { stderr += data; }); diff --git a/test/parallel/test-debug-usage.js b/test/parallel/test-debug-usage.js index 5406a82cc8d229..67ee08ce729431 100644 --- a/test/parallel/test-debug-usage.js +++ b/test/parallel/test-debug-usage.js @@ -10,7 +10,7 @@ const expectedUsageMessage = `Usage: node debug script.js node debug : node debug -p `; -var actualUsageMessage = ''; +let actualUsageMessage = ''; child.stderr.on('data', function(data) { actualUsageMessage += data.toString(); }); diff --git a/test/parallel/test-debugger-pid.js b/test/parallel/test-debugger-pid.js index 2b81da700f50a0..e8ba516bfc0f9e 100644 --- a/test/parallel/test-debugger-pid.js +++ b/test/parallel/test-debugger-pid.js @@ -3,15 +3,15 @@ const common = require('../common'); const assert = require('assert'); const spawn = require('child_process').spawn; -var buffer = ''; +let buffer = ''; // connect to debug agent -var interfacer = spawn(process.execPath, ['debug', '-p', '655555']); +const interfacer = spawn(process.execPath, ['debug', '-p', '655555']); console.error(process.execPath, 'debug', '-p', '655555'); interfacer.stdout.setEncoding('utf-8'); interfacer.stderr.setEncoding('utf-8'); -var onData = function(data) { +const onData = function(data) { data = (buffer + data).split('\n'); buffer = data.pop(); data.forEach(function(line) { @@ -21,9 +21,9 @@ var onData = function(data) { interfacer.stdout.on('data', onData); interfacer.stderr.on('data', onData); -var lineCount = 0; +let lineCount = 0; interfacer.on('line', function(line) { - var expected; + let expected; const pid = interfacer.pid; if (common.isWindows) { switch (++lineCount) { diff --git a/test/parallel/test-debugger-repeat-last.js b/test/parallel/test-debugger-repeat-last.js index 7a43bbb6c767ae..cacedbbd7c6e99 100644 --- a/test/parallel/test-debugger-repeat-last.js +++ b/test/parallel/test-debugger-repeat-last.js @@ -17,11 +17,11 @@ const args = [ const proc = spawn(process.execPath, args, { stdio: 'pipe' }); proc.stdout.setEncoding('utf8'); -var stdout = ''; +let stdout = ''; -var sentCommand = false; -var sentEmpty = false; -var sentExit = false; +let sentCommand = false; +let sentEmpty = false; +let sentExit = false; proc.stdout.on('data', (data) => { stdout += data; diff --git a/test/parallel/test-dgram-address.js b/test/parallel/test-dgram-address.js index 03fcdf3446ac83..09c5ba31f6c5b5 100644 --- a/test/parallel/test-dgram-address.js +++ b/test/parallel/test-dgram-address.js @@ -4,11 +4,11 @@ const assert = require('assert'); const dgram = require('dgram'); // IPv4 Test -var socket_ipv4 = dgram.createSocket('udp4'); -var family_ipv4 = 'IPv4'; +const socket_ipv4 = dgram.createSocket('udp4'); +const family_ipv4 = 'IPv4'; socket_ipv4.on('listening', function() { - var address_ipv4 = socket_ipv4.address(); + const address_ipv4 = socket_ipv4.address(); assert.strictEqual(address_ipv4.address, common.localhostIPv4); assert.strictEqual(typeof address_ipv4.port, 'number'); assert.ok(isFinite(address_ipv4.port)); @@ -25,12 +25,12 @@ socket_ipv4.on('error', function(e) { socket_ipv4.bind(0, common.localhostIPv4); // IPv6 Test -var localhost_ipv6 = '::1'; -var socket_ipv6 = dgram.createSocket('udp6'); -var family_ipv6 = 'IPv6'; +const localhost_ipv6 = '::1'; +const socket_ipv6 = dgram.createSocket('udp6'); +const family_ipv6 = 'IPv6'; socket_ipv6.on('listening', function() { - var address_ipv6 = socket_ipv6.address(); + const address_ipv6 = socket_ipv6.address(); assert.strictEqual(address_ipv6.address, localhost_ipv6); assert.strictEqual(typeof address_ipv6.port, 'number'); assert.ok(isFinite(address_ipv6.port)); diff --git a/test/parallel/test-dgram-bind.js b/test/parallel/test-dgram-bind.js index 6df102b32d09e1..882f2e87bdd7ee 100644 --- a/test/parallel/test-dgram-bind.js +++ b/test/parallel/test-dgram-bind.js @@ -3,12 +3,12 @@ require('../common'); const assert = require('assert'); const dgram = require('dgram'); -var socket = dgram.createSocket('udp4'); +const socket = dgram.createSocket('udp4'); socket.on('listening', function() { socket.close(); }); -var result = socket.bind(); // should not throw +const result = socket.bind(); // should not throw assert.strictEqual(result, socket); // should have returned itself diff --git a/test/parallel/test-dgram-bytes-length.js b/test/parallel/test-dgram-bytes-length.js index da686d850ee129..07a8bb0e43452b 100644 --- a/test/parallel/test-dgram-bytes-length.js +++ b/test/parallel/test-dgram-bytes-length.js @@ -3,8 +3,8 @@ require('../common'); const assert = require('assert'); const dgram = require('dgram'); -var message = Buffer.from('Some bytes'); -var client = dgram.createSocket('udp4'); +const message = Buffer.from('Some bytes'); +const client = dgram.createSocket('udp4'); client.send( message, 0, diff --git a/test/parallel/test-dgram-close-is-not-callback.js b/test/parallel/test-dgram-close-is-not-callback.js index beccc2420d36bc..d0f23d5808c7b7 100644 --- a/test/parallel/test-dgram-close-is-not-callback.js +++ b/test/parallel/test-dgram-close-is-not-callback.js @@ -2,9 +2,9 @@ const common = require('../common'); const dgram = require('dgram'); -var buf = Buffer.alloc(1024, 42); +const buf = Buffer.alloc(1024, 42); -var socket = dgram.createSocket('udp4'); +const socket = dgram.createSocket('udp4'); socket.send(buf, 0, buf.length, common.PORT, 'localhost'); diff --git a/test/parallel/test-dgram-close.js b/test/parallel/test-dgram-close.js index 41d28553ca8cb7..43047db697a2eb 100644 --- a/test/parallel/test-dgram-close.js +++ b/test/parallel/test-dgram-close.js @@ -6,10 +6,10 @@ const common = require('../common'); const assert = require('assert'); const dgram = require('dgram'); -var buf = Buffer.alloc(1024, 42); +const buf = Buffer.alloc(1024, 42); -var socket = dgram.createSocket('udp4'); -var handle = socket._handle; +let socket = dgram.createSocket('udp4'); +const handle = socket._handle; socket.send(buf, 0, buf.length, common.PORT, 'localhost'); assert.strictEqual(socket.close(common.mustCall(function() {})), socket); diff --git a/test/parallel/test-dgram-exclusive-implicit-bind.js b/test/parallel/test-dgram-exclusive-implicit-bind.js index 97fd6bed5d6e33..927c9f815fc046 100644 --- a/test/parallel/test-dgram-exclusive-implicit-bind.js +++ b/test/parallel/test-dgram-exclusive-implicit-bind.js @@ -40,11 +40,11 @@ const dgram = require('dgram'); // with ENOTSUP. if (cluster.isMaster) { - var messages = 0; + let messages = 0; const ports = {}; const pids = []; - var target = dgram.createSocket('udp4'); + const target = dgram.createSocket('udp4'); const done = common.mustCall(function() { cluster.disconnect(); @@ -84,7 +84,6 @@ if (cluster.isMaster) { } const source = dgram.createSocket('udp4'); -var interval; source.on('close', function() { clearInterval(interval); @@ -100,6 +99,6 @@ if (process.env.BOUND === 'y') { } const buf = Buffer.from(process.pid.toString()); -interval = setInterval(() => { +const interval = setInterval(() => { source.send(buf, common.PORT, '127.0.0.1'); }, 1).unref(); diff --git a/test/parallel/test-dgram-implicit-bind.js b/test/parallel/test-dgram-implicit-bind.js index 25c61903e884de..bfc86803b463f1 100644 --- a/test/parallel/test-dgram-implicit-bind.js +++ b/test/parallel/test-dgram-implicit-bind.js @@ -2,9 +2,9 @@ const common = require('../common'); const dgram = require('dgram'); -var source = dgram.createSocket('udp4'); -var target = dgram.createSocket('udp4'); -var messages = 0; +const source = dgram.createSocket('udp4'); +const target = dgram.createSocket('udp4'); +let messages = 0; target.on('message', common.mustCall(function(buf) { if (buf.toString() === 'abc') ++messages; diff --git a/test/parallel/test-dgram-listen-after-bind.js b/test/parallel/test-dgram-listen-after-bind.js index 2060a4738012a2..e60687649cda30 100644 --- a/test/parallel/test-dgram-listen-after-bind.js +++ b/test/parallel/test-dgram-listen-after-bind.js @@ -3,12 +3,12 @@ require('../common'); const assert = require('assert'); const dgram = require('dgram'); -var socket = dgram.createSocket('udp4'); +const socket = dgram.createSocket('udp4'); socket.bind(); -var fired = false; -var timer = setTimeout(function() { +let fired = false; +const timer = setTimeout(function() { socket.close(); }, 100); diff --git a/test/parallel/test-dgram-oob-buffer.js b/test/parallel/test-dgram-oob-buffer.js index 0bf302e7e3ce6e..247a35588c3ff7 100644 --- a/test/parallel/test-dgram-oob-buffer.js +++ b/test/parallel/test-dgram-oob-buffer.js @@ -6,8 +6,8 @@ const common = require('../common'); const dgram = require('dgram'); -var socket = dgram.createSocket('udp4'); -var buf = Buffer.from([1, 2, 3, 4]); +const socket = dgram.createSocket('udp4'); +const buf = Buffer.from([1, 2, 3, 4]); function ok() {} socket.send(buf, 0, 0, common.PORT, '127.0.0.1', ok); // useful? no diff --git a/test/parallel/test-dgram-regress-4496.js b/test/parallel/test-dgram-regress-4496.js index 2b509d79076911..b4ec8195d7e7f0 100644 --- a/test/parallel/test-dgram-regress-4496.js +++ b/test/parallel/test-dgram-regress-4496.js @@ -6,7 +6,7 @@ const assert = require('assert'); const dgram = require('dgram'); // Should throw but not crash. -var socket = dgram.createSocket('udp4'); +const socket = dgram.createSocket('udp4'); assert.throws(function() { socket.send(true, 0, 1, 1, 'host'); }, TypeError); assert.throws(function() { socket.sendto(5, 0, 1, 1, 'host'); }, TypeError); socket.close(); diff --git a/test/parallel/test-dgram-send-bad-arguments.js b/test/parallel/test-dgram-send-bad-arguments.js index 8505c8bb67e8c0..c7ec6b51eecfa8 100644 --- a/test/parallel/test-dgram-send-bad-arguments.js +++ b/test/parallel/test-dgram-send-bad-arguments.js @@ -3,9 +3,9 @@ require('../common'); const assert = require('assert'); const dgram = require('dgram'); -var buf = Buffer.from('test'); -var host = '127.0.0.1'; -var sock = dgram.createSocket('udp4'); +const buf = Buffer.from('test'); +const host = '127.0.0.1'; +const sock = dgram.createSocket('udp4'); assert.throws(function() { sock.send(); diff --git a/test/parallel/test-dgram-send-empty-array.js b/test/parallel/test-dgram-send-empty-array.js index 442803e6db8632..1bfcacd9a40497 100644 --- a/test/parallel/test-dgram-send-empty-array.js +++ b/test/parallel/test-dgram-send-empty-array.js @@ -12,7 +12,7 @@ const dgram = require('dgram'); const client = dgram.createSocket('udp4'); -var interval; +let interval; client.on('message', common.mustCall(function onMessage(buf, info) { const expected = Buffer.alloc(0); diff --git a/test/parallel/test-dgram-send-empty-buffer.js b/test/parallel/test-dgram-send-empty-buffer.js index 70e7e46e0a327e..d612dbc7e56c83 100644 --- a/test/parallel/test-dgram-send-empty-buffer.js +++ b/test/parallel/test-dgram-send-empty-buffer.js @@ -21,7 +21,7 @@ client.bind(0, common.mustCall(function() { })); const buf = Buffer.alloc(0); - var interval = setInterval(function() { + const interval = setInterval(function() { client.send(buf, 0, 0, port, '127.0.0.1', common.mustCall(function() {})); }, 10); })); diff --git a/test/parallel/test-dgram-setTTL.js b/test/parallel/test-dgram-setTTL.js index 9393e53c7f1912..3985297217d8b7 100644 --- a/test/parallel/test-dgram-setTTL.js +++ b/test/parallel/test-dgram-setTTL.js @@ -6,7 +6,7 @@ const socket = dgram.createSocket('udp4'); socket.bind(0); socket.on('listening', function() { - var result = socket.setTTL(16); + const result = socket.setTTL(16); assert.strictEqual(result, 16); assert.throws(function() { diff --git a/test/parallel/test-dgram-unref.js b/test/parallel/test-dgram-unref.js index 1b95487a302cdb..ee463d7ab8da77 100644 --- a/test/parallel/test-dgram-unref.js +++ b/test/parallel/test-dgram-unref.js @@ -2,7 +2,7 @@ const common = require('../common'); const dgram = require('dgram'); -var s = dgram.createSocket('udp4'); +const s = dgram.createSocket('udp4'); s.bind(); s.unref(); diff --git a/test/parallel/test-dh-padding.js b/test/parallel/test-dh-padding.js index 35202f6a5191a8..1d9d47ec0e10a3 100644 --- a/test/parallel/test-dh-padding.js +++ b/test/parallel/test-dh-padding.js @@ -45,7 +45,7 @@ const crypto = require('crypto'); * } */ -var apub = +const apub = '5484455905d3eff34c70980e871f27f05448e66f5a6efbb97cbcba4e927196c2bd9ea272cded91\ 10a4977afa8d9b16c9139a444ed2d954a794650e5d7cb525204f385e1af81530518563822ecd0f9\ 524a958d02b3c269e79d6d69850f0968ad567a4404fbb0b19efc8bc73e267b6136b88cafb33299f\ @@ -53,7 +53,7 @@ f7c7cace3ffab1a88c2c9ee841f88b4c3679b4efc465f5c93cca11d487be57373e4c5926f634c4e\ efee6721d01db91cd66321615b2522f96368dbc818875d422140d0edf30bdb97d9721feddcb9ff6\ 453741a4f687ee46fc54bf1198801f1210ac789879a5ee123f79e2d2ce1209df2445d32166bc9e4\ 8f89e944ec9c3b2e16c8066cd8eebd4e33eb941'; -var bpub = +const bpub = '3fca64510e36bc7da8a3a901c7b74c2eabfa25deaf7cbe1d0c50235866136ad677317279e1fb0\ 06e9c0a07f63e14a3363c8e016fbbde2b2c7e79fed1cc3e08e95f7459f547a8cd0523ee9dc744d\ e5a956d92b937db4448917e1f6829437f05e408ee7aea70c0362b37370c7c75d14449d8b2d2133\ @@ -61,7 +61,7 @@ e5a956d92b937db4448917e1f6829437f05e408ee7aea70c0362b37370c7c75d14449d8b2d2133\ 788a1fdc6cdf17f5fffaf024ce8711a2ebde0b52e9f1cb56224483826d6e5ac6ecfaae07b75d20\ 6e8ac97f5be1a5b68f20382f2a7dac189cf169325c4cf845b26a0cd616c31fec905c5d9035e5f7\ 8e9880c812374ac0f3ca3d365f06e4be526b5affd4b79'; -var apriv = +const apriv = '62411e34704637d99c6c958a7db32ac22fcafafbe1c33d2cfdb76e12ded41f38fc16b792b9041\ 2e4c82755a3815ba52f780f0ee296ad46e348fc4d1dcd6b64f4eea1b231b2b7d95c5b1c2e26d34\ 83520558b9860a6eb668f01422a54e6604aa7702b4e67511397ef3ecb912bff1a83899c5a5bfb2\ @@ -69,7 +69,7 @@ var apriv = 08c3b3e6fc60668f7be81cce6784482af228dd7f489005253a165e292802cfd0399924f6c56827\ 7012f68255207722355634290acc7fddeefbba75650a85ece95b6a12de67eac016ba78960108dd\ 5dbadfaa43cc9fed515a1f307b7d90ae0623bc7b8cefb'; -var secret = +const secret = '00c37b1e06a436d6717816a40e6d72907a6f255638b93032267dcb9a5f0b4a9aa0236f3dce63b\ 1c418c60978a00acd1617dfeecf1661d8a3fafb4d0d8824386750f4853313400e7e4afd22847e4\ fa56bc9713872021265111906673b38db83d10cbfa1dea3b6b4c97c8655f4ae82125281af7f234\ @@ -79,7 +79,7 @@ dc8fe984ddaf532fc1531ce43155fa0ab32532bf1ece5356b8a3447b5267798a904f16f3f4e635\ 8612314311231f905f91c63a1aea52e0b60cead8b57df'; /* FIPS-friendly 2048 bit prime */ -var p = crypto.createDiffieHellman( +const p = crypto.createDiffieHellman( crypto.getDiffieHellman('modp14').getPrime()); p.setPublicKey(apub, 'hex'); diff --git a/test/parallel/test-dns-lookup-cb-error.js b/test/parallel/test-dns-lookup-cb-error.js index 212f037868309e..d866a8a13bf622 100644 --- a/test/parallel/test-dns-lookup-cb-error.js +++ b/test/parallel/test-dns-lookup-cb-error.js @@ -11,7 +11,7 @@ cares.getaddrinfo = function() { }; assert.doesNotThrow(() => { - var tickValue = 0; + let tickValue = 0; dns.lookup('example.com', common.mustCall((error, result, addressType) => { assert(error); diff --git a/test/parallel/test-domain-abort-on-uncaught.js b/test/parallel/test-domain-abort-on-uncaught.js index d9183af60bc278..f754541f37462b 100644 --- a/test/parallel/test-domain-abort-on-uncaught.js +++ b/test/parallel/test-domain-abort-on-uncaught.js @@ -9,7 +9,7 @@ const assert = require('assert'); const domain = require('domain'); const child_process = require('child_process'); -var errorHandlerCalled = false; +let errorHandlerCalled = false; const tests = [ function nextTick() { @@ -232,7 +232,7 @@ if (process.argv[2] === 'child') { } else { tests.forEach(function(test, testIndex) { - var testCmd = ''; + let testCmd = ''; if (!common.isWindows) { // Do not create core files, as it can take a lot of disk space on // continuous testing and developers' machines @@ -245,7 +245,7 @@ if (process.argv[2] === 'child') { testCmd += ' ' + 'child'; testCmd += ' ' + testIndex; - var child = child_process.exec(testCmd); + const child = child_process.exec(testCmd); child.on('exit', function onExit(code, signal) { assert.strictEqual(code, 0, 'Test at index ' + testIndex + diff --git a/test/parallel/test-domain-enter-exit.js b/test/parallel/test-domain-enter-exit.js index 5f12a0bd4ca08c..4a11c3a206a5fe 100644 --- a/test/parallel/test-domain-enter-exit.js +++ b/test/parallel/test-domain-enter-exit.js @@ -11,11 +11,11 @@ function names(array) { }).join(', '); } -var a = domain.create(); +const a = domain.create(); a.name = 'a'; -var b = domain.create(); +const b = domain.create(); b.name = 'b'; -var c = domain.create(); +const c = domain.create(); c.name = 'c'; a.enter(); // push diff --git a/test/parallel/test-domain-exit-dispose-again.js b/test/parallel/test-domain-exit-dispose-again.js index 2a4ffd655c3e52..542950f8af428e 100644 --- a/test/parallel/test-domain-exit-dispose-again.js +++ b/test/parallel/test-domain-exit-dispose-again.js @@ -8,20 +8,20 @@ require('../common'); const assert = require('assert'); const domain = require('domain'); -var disposalFailed = false; +let disposalFailed = false; // Repeatedly schedule a timer with a delay different than the timers attached // to a domain that will eventually be disposed to make sure that they are // called, regardless of what happens with those timers attached to domains // that will eventually be disposed. -var a = 0; +let a = 0; log(); function log() { console.log(a++, process.domain); if (a < 10) setTimeout(log, 20); } -var secondTimerRan = false; +let secondTimerRan = false; // Use the same timeout duration for both "firstTimer" and "secondTimer" // callbacks so that they are called during the same invocation of the diff --git a/test/parallel/test-domain-exit-dispose.js b/test/parallel/test-domain-exit-dispose.js index c53b840bf556c3..e1797cb660a0c0 100644 --- a/test/parallel/test-domain-exit-dispose.js +++ b/test/parallel/test-domain-exit-dispose.js @@ -5,7 +5,7 @@ const assert = require('assert'); const domain = require('domain'); // no matter what happens, we should increment a 10 times. -var a = 0; +let a = 0; log(); function log() { console.log(a++, process.domain); @@ -15,7 +15,7 @@ function log() { // in 50ms we'll throw an error. setTimeout(err, 50); function err() { - var d = domain.create(); + const d = domain.create(); d.on('error', handle); d.run(err2); diff --git a/test/parallel/test-domain-http-server.js b/test/parallel/test-domain-http-server.js index ee0388b3cd7f88..d8bb5c843662b8 100644 --- a/test/parallel/test-domain-http-server.js +++ b/test/parallel/test-domain-http-server.js @@ -4,14 +4,14 @@ const domain = require('domain'); const http = require('http'); const assert = require('assert'); -var objects = { foo: 'bar', baz: {}, num: 42, arr: [1, 2, 3] }; +const objects = { foo: 'bar', baz: {}, num: 42, arr: [1, 2, 3] }; objects.baz.asdf = objects; -var serverCaught = 0; -var clientCaught = 0; +let serverCaught = 0; +let clientCaught = 0; -var server = http.createServer(function(req, res) { - var dom = domain.create(); +const server = http.createServer(function(req, res) { + const dom = domain.create(); req.resume(); dom.add(req); dom.add(res); @@ -27,7 +27,7 @@ var server = http.createServer(function(req, res) { dom.run(function() { // Now, an action that has the potential to fail! // if you request 'baz', then it'll throw a JSON circular ref error. - var data = JSON.stringify(objects[req.url.replace(/[^a-z]/g, '')]); + const data = JSON.stringify(objects[req.url.replace(/[^a-z]/g, '')]); // this line will throw if you pick an unknown key assert.notStrictEqual(data, undefined, 'Data should not be undefined'); @@ -43,8 +43,8 @@ function next() { const port = this.address().port; console.log('listening on localhost:%d', port); - var requests = 0; - var responses = 0; + let requests = 0; + let responses = 0; makeReq('/'); makeReq('/foo'); @@ -55,14 +55,14 @@ function next() { function makeReq(p) { requests++; - var dom = domain.create(); + const dom = domain.create(); dom.on('error', function(er) { clientCaught++; console.log('client error', er); req.socket.destroy(); }); - var req = http.get({ host: 'localhost', port: port, path: p }); + const req = http.get({ host: 'localhost', port: port, path: p }); dom.add(req); req.on('response', function(res) { responses++; @@ -74,7 +74,7 @@ function next() { } dom.add(res); - var d = ''; + let d = ''; res.on('data', function(c) { d += c; }); diff --git a/test/parallel/test-domain-implicit-fs.js b/test/parallel/test-domain-implicit-fs.js index 7773bc46d76137..265d291f61941b 100644 --- a/test/parallel/test-domain-implicit-fs.js +++ b/test/parallel/test-domain-implicit-fs.js @@ -5,7 +5,7 @@ const common = require('../common'); const assert = require('assert'); const domain = require('domain'); -var d = new domain.Domain(); +const d = new domain.Domain(); d.on('error', common.mustCall(function(er) { console.error('caught', er); diff --git a/test/parallel/test-domain-multi.js b/test/parallel/test-domain-multi.js index 2e541ab5e4dc3c..b8005726219519 100644 --- a/test/parallel/test-domain-multi.js +++ b/test/parallel/test-domain-multi.js @@ -5,12 +5,12 @@ require('../common'); const assert = require('assert'); const domain = require('domain'); -var caughtA = false; -var caughtB = false; -var caughtC = false; +let caughtA = false; +let caughtB = false; +let caughtC = false; -var a = domain.create(); +const a = domain.create(); a.enter(); // this will be our "root" domain a.on('error', function(er) { caughtA = true; @@ -20,9 +20,9 @@ a.on('error', function(er) { const http = require('http'); -var server = http.createServer(function(req, res) { +const server = http.createServer(function(req, res) { // child domain of a. - var b = domain.create(); + const b = domain.create(); a.add(b); // treat these EE objects as if they are a part of the b domain @@ -50,8 +50,8 @@ var server = http.createServer(function(req, res) { })); }).listen(0, function() { - var c = domain.create(); - var req = http.get({ host: 'localhost', port: this.address().port }); + const c = domain.create(); + const req = http.get({ host: 'localhost', port: this.address().port }); // add the request to the C domain c.add(req); diff --git a/test/parallel/test-domain-nested-throw.js b/test/parallel/test-domain-nested-throw.js index 008eaaa5f7496f..39507446a3acfc 100644 --- a/test/parallel/test-domain-nested-throw.js +++ b/test/parallel/test-domain-nested-throw.js @@ -4,7 +4,7 @@ const assert = require('assert'); const domain = require('domain'); -var dispose; +let dispose; switch (process.argv[2]) { case 'true': dispose = true; @@ -18,10 +18,10 @@ switch (process.argv[2]) { } function parent() { - var node = process.execPath; + const node = process.execPath; const spawn = require('child_process').spawn; - var opt = { stdio: 'inherit' }; - var child = spawn(node, [__filename, 'true'], opt); + const opt = { stdio: 'inherit' }; + let child = spawn(node, [__filename, 'true'], opt); child.on('exit', function(c) { assert(!c); child = spawn(node, [__filename, 'false'], opt); @@ -32,11 +32,11 @@ function parent() { }); } -var gotDomain1Error = false; -var gotDomain2Error = false; +let gotDomain1Error = false; +let gotDomain2Error = false; -var threw1 = false; -var threw2 = false; +let threw1 = false; +let threw2 = false; function throw1() { threw1 = true; @@ -49,7 +49,7 @@ function throw2() { } function inner(throw1, throw2) { - var domain1 = domain.createDomain(); + const domain1 = domain.createDomain(); domain1.on('error', function(err) { if (gotDomain1Error) { @@ -67,7 +67,7 @@ function inner(throw1, throw2) { } function outer() { - var domain2 = domain.createDomain(); + const domain2 = domain.createDomain(); domain2.on('error', function(err) { if (gotDomain2Error) { diff --git a/test/parallel/test-domain-safe-exit.js b/test/parallel/test-domain-safe-exit.js index c00aa306f10e7a..bbc3b2fe22cae8 100644 --- a/test/parallel/test-domain-safe-exit.js +++ b/test/parallel/test-domain-safe-exit.js @@ -5,8 +5,8 @@ require('../common'); const assert = require('assert'); const domain = require('domain'); -var a = domain.create(); -var b = domain.create(); +const a = domain.create(); +const b = domain.create(); a.enter(); // push b.enter(); // push diff --git a/test/parallel/test-domain-stack.js b/test/parallel/test-domain-stack.js index 5772a56e39b77e..43152a4a3bb1c9 100644 --- a/test/parallel/test-domain-stack.js +++ b/test/parallel/test-domain-stack.js @@ -4,7 +4,7 @@ require('../common'); const domain = require('domain'); -var a = domain.create(); +const a = domain.create(); a.name = 'a'; a.on('error', function() { @@ -14,11 +14,11 @@ a.on('error', function() { } }); -var foo = a.bind(function() { +const foo = a.bind(function() { throw new Error('error from foo'); }); -for (var i = 0; i < 1000; i++) { +for (let i = 0; i < 1000; i++) { process.nextTick(foo); } diff --git a/test/parallel/test-domain-throw-error-then-throw-from-uncaught-exception-handler.js b/test/parallel/test-domain-throw-error-then-throw-from-uncaught-exception-handler.js index d2277cfc0f74b7..e35d247c3a8a34 100644 --- a/test/parallel/test-domain-throw-error-then-throw-from-uncaught-exception-handler.js +++ b/test/parallel/test-domain-throw-error-then-throw-from-uncaught-exception-handler.js @@ -81,7 +81,7 @@ function runTestWithAbortOnUncaughtException() { } function createTestCmdLine(options) { - var testCmd = ''; + let testCmd = ''; if (!common.isWindows) { // Do not create core files, as it can take a lot of disk space on diff --git a/test/parallel/test-domain-timers.js b/test/parallel/test-domain-timers.js index 6ddec404cd20ac..79bd300545bf96 100644 --- a/test/parallel/test-domain-timers.js +++ b/test/parallel/test-domain-timers.js @@ -3,9 +3,7 @@ const common = require('../common'); const domain = require('domain'); const assert = require('assert'); -var timeout; - -var timeoutd = domain.create(); +const timeoutd = domain.create(); timeoutd.on('error', common.mustCall(function(e) { assert.strictEqual(e.message, 'Timeout UNREFd', @@ -19,7 +17,7 @@ timeoutd.run(function() { }, 0).unref(); }); -var immediated = domain.create(); +const immediated = domain.create(); immediated.on('error', common.mustCall(function(e) { assert.strictEqual(e.message, 'Immediate Error', @@ -32,4 +30,4 @@ immediated.run(function() { }); }); -timeout = setTimeout(function() {}, 10 * 1000); +const timeout = setTimeout(function() {}, 10 * 1000); diff --git a/test/parallel/test-domain-top-level-error-handler-throw.js b/test/parallel/test-domain-top-level-error-handler-throw.js index 8062d107367dfe..53a73eac426232 100644 --- a/test/parallel/test-domain-top-level-error-handler-throw.js +++ b/test/parallel/test-domain-top-level-error-handler-throw.js @@ -14,7 +14,7 @@ const internalExMessage = 'You should NOT see me'; if (process.argv[2] === 'child') { const domain = require('domain'); - var d = domain.create(); + const d = domain.create(); d.on('error', function() { throw new Error(domainErrHandlerExMessage); @@ -29,8 +29,8 @@ if (process.argv[2] === 'child') { const fork = require('child_process').fork; const assert = require('assert'); - var child = fork(process.argv[1], ['child'], {silent: true}); - var stderrOutput = ''; + const child = fork(process.argv[1], ['child'], {silent: true}); + let stderrOutput = ''; if (child) { child.stderr.on('data', function onStderrData(data) { stderrOutput += data.toString(); @@ -45,8 +45,8 @@ if (process.argv[2] === 'child') { }); child.on('exit', function onChildExited(exitCode, signal) { - var expectedExitCode = 7; - var expectedSignal = null; + const expectedExitCode = 7; + const expectedSignal = null; assert.strictEqual(exitCode, expectedExitCode); assert.strictEqual(signal, expectedSignal); diff --git a/test/parallel/test-domain-with-abort-on-uncaught-exception.js b/test/parallel/test-domain-with-abort-on-uncaught-exception.js index e11935be68704e..0da8f1368f7c98 100644 --- a/test/parallel/test-domain-with-abort-on-uncaught-exception.js +++ b/test/parallel/test-domain-with-abort-on-uncaught-exception.js @@ -30,7 +30,7 @@ const domainErrHandlerExMessage = 'exception from domain error handler'; if (process.argv[2] === 'child') { const domain = require('domain'); - var d = domain.create(); + const d = domain.create(); process.on('uncaughtException', function onUncaughtException() { // The process' uncaughtException event must not be emitted when @@ -88,18 +88,18 @@ if (process.argv[2] === 'child') { cmdLineOption = undefined; } - var throwInDomainErrHandlerOpt; + let throwInDomainErrHandlerOpt; if (options.throwInDomainErrHandler) throwInDomainErrHandlerOpt = 'throwInDomainErrHandler'; - var cmdToExec = ''; + let cmdToExec = ''; if (!common.isWindows) { // Do not create core files, as it can take a lot of disk space on // continuous testing and developers' machines cmdToExec += 'ulimit -c 0 && '; } - var useTryCatchOpt; + let useTryCatchOpt; if (options.useTryCatch) useTryCatchOpt = 'useTryCatch'; @@ -112,7 +112,7 @@ if (process.argv[2] === 'child') { useTryCatchOpt ].join(' '); - var child = exec(cmdToExec); + const child = exec(cmdToExec); if (child) { child.on('exit', function onChildExited(exitCode, signal) { diff --git a/test/parallel/test-domain.js b/test/parallel/test-domain.js index 73ab3b96168930..11c14f3c011eb7 100644 --- a/test/parallel/test-domain.js +++ b/test/parallel/test-domain.js @@ -6,24 +6,24 @@ const assert = require('assert'); const domain = require('domain'); const events = require('events'); const fs = require('fs'); -var caught = 0; -var expectCaught = 0; +let caught = 0; +let expectCaught = 0; -var d = new domain.Domain(); -var e = new events.EventEmitter(); +const d = new domain.Domain(); +const e = new events.EventEmitter(); d.on('error', function(er) { console.error('caught', er && (er.message || er)); - var er_message = er.message; - var er_path = er.path; + let er_message = er.message; + let er_path = er.path; // On windows, error messages can contain full path names. If this is the // case, remove the directory part. if (typeof er_path === 'string') { - var slash = er_path.lastIndexOf('\\'); + const slash = er_path.lastIndexOf('\\'); if (slash !== -1) { - var dir = er_path.slice(0, slash + 1); + const dir = er_path.slice(0, slash + 1); er_path = er_path.replace(dir, ''); er_message = er_message.replace(dir, ''); } @@ -129,7 +129,7 @@ expectCaught++; // set up while in the scope of the d domain. d.run(function() { process.nextTick(function() { - var i = setInterval(function() { + const i = setInterval(function() { clearInterval(i); setTimeout(function() { fs.stat('this file does not exist', function(er, stat) { @@ -166,7 +166,7 @@ function fn() { throw new Error('This function should never be called!'); } -var bound = d.intercept(fn); +let bound = d.intercept(fn); bound(new Error('bound')); expectCaught++; @@ -210,7 +210,7 @@ expectCaught++; // implicit addition by being created within a domain-bound context. -var implicit; +let implicit; d.run(function() { implicit = new events.EventEmitter(); @@ -223,7 +223,7 @@ setTimeout(function() { expectCaught++; -var result = d.run(function() { +let result = d.run(function() { return 'return value'; }); assert.strictEqual(result, 'return value'); @@ -236,12 +236,12 @@ result = d.run(function(a, b) { assert.strictEqual(result, 'return value'); -var fst = fs.createReadStream('stream for nonexistent file'); +const fst = fs.createReadStream('stream for nonexistent file'); d.add(fst); expectCaught++; [42, null, , false, function() {}, 'string'].forEach(function(something) { - var d = new domain.Domain(); + const d = new domain.Domain(); d.run(function() { process.nextTick(function() { throw something; diff --git a/test/parallel/test-dsa-fips-invalid-key.js b/test/parallel/test-dsa-fips-invalid-key.js index d0716a3e21eb08..6055a9b4c47862 100644 --- a/test/parallel/test-dsa-fips-invalid-key.js +++ b/test/parallel/test-dsa-fips-invalid-key.js @@ -10,11 +10,11 @@ if (!common.hasFipsCrypto) { const crypto = require('crypto'); const fs = require('fs'); -var input = 'hello'; +const input = 'hello'; -var dsapri = fs.readFileSync(common.fixturesDir + +const dsapri = fs.readFileSync(common.fixturesDir + '/keys/dsa_private_1025.pem'); -var sign = crypto.createSign('DSS1'); +const sign = crypto.createSign('DSS1'); sign.update(input); assert.throws(function() { diff --git a/test/parallel/test-error-reporting.js b/test/parallel/test-error-reporting.js index 058f99126a7d1b..fa7332a67a482b 100644 --- a/test/parallel/test-error-reporting.js +++ b/test/parallel/test-error-reporting.js @@ -5,8 +5,8 @@ const exec = require('child_process').exec; const path = require('path'); function errExec(script, callback) { - var cmd = '"' + process.argv[0] + '" "' + - path.join(common.fixturesDir, script) + '"'; + const cmd = '"' + process.argv[0] + '" "' + + path.join(common.fixturesDir, script) + '"'; return exec(cmd, function(err, stdout, stderr) { // There was some error assert.ok(err); diff --git a/test/parallel/test-event-emitter-check-listener-leaks.js b/test/parallel/test-event-emitter-check-listener-leaks.js index 18d2d065b8b1f4..5b9787f1b83bba 100644 --- a/test/parallel/test-event-emitter-check-listener-leaks.js +++ b/test/parallel/test-event-emitter-check-listener-leaks.js @@ -3,7 +3,7 @@ require('../common'); const assert = require('assert'); const events = require('events'); -var e = new events.EventEmitter(); +let e = new events.EventEmitter(); // default for (let i = 0; i < 10; i++) { diff --git a/test/parallel/test-event-emitter-errors.js b/test/parallel/test-event-emitter-errors.js index e2c9fa2a0c2c1e..2b4a93ae9808df 100644 --- a/test/parallel/test-event-emitter-errors.js +++ b/test/parallel/test-event-emitter-errors.js @@ -3,7 +3,7 @@ require('../common'); const EventEmitter = require('events'); const assert = require('assert'); -var EE = new EventEmitter(); +const EE = new EventEmitter(); assert.throws(function() { EE.emit('error', 'Accepts a string'); diff --git a/test/parallel/test-event-emitter-get-max-listeners.js b/test/parallel/test-event-emitter-get-max-listeners.js index 13f1dcb97c39c3..9acc71fd7920e3 100644 --- a/test/parallel/test-event-emitter-get-max-listeners.js +++ b/test/parallel/test-event-emitter-get-max-listeners.js @@ -3,7 +3,7 @@ require('../common'); const assert = require('assert'); const EventEmitter = require('events'); -var emitter = new EventEmitter(); +const emitter = new EventEmitter(); assert.strictEqual(emitter.getMaxListeners(), EventEmitter.defaultMaxListeners); @@ -14,6 +14,6 @@ emitter.setMaxListeners(3); assert.strictEqual(emitter.getMaxListeners(), 3); // https://github.com/nodejs/node/issues/523 - second call should not throw. -var recv = {}; +const recv = {}; EventEmitter.prototype.on.call(recv, 'event', function() {}); EventEmitter.prototype.on.call(recv, 'event', function() {}); diff --git a/test/parallel/test-event-emitter-listeners-side-effects.js b/test/parallel/test-event-emitter-listeners-side-effects.js index 60d64c6614df80..022750da406500 100644 --- a/test/parallel/test-event-emitter-listeners-side-effects.js +++ b/test/parallel/test-event-emitter-listeners-side-effects.js @@ -5,8 +5,8 @@ const assert = require('assert'); const EventEmitter = require('events').EventEmitter; -var e = new EventEmitter(); -var fl; // foo listeners +const e = new EventEmitter(); +let fl; // foo listeners fl = e.listeners('foo'); assert(Array.isArray(fl)); diff --git a/test/parallel/test-event-emitter-method-names.js b/test/parallel/test-event-emitter-method-names.js index 27c01b2a0781c5..d0464b80a44fe1 100644 --- a/test/parallel/test-event-emitter-method-names.js +++ b/test/parallel/test-event-emitter-method-names.js @@ -3,7 +3,7 @@ require('../common'); const assert = require('assert'); const events = require('events'); -var E = events.EventEmitter.prototype; +const E = events.EventEmitter.prototype; assert.strictEqual(E.constructor.name, 'EventEmitter'); assert.strictEqual(E.on, E.addListener); // Same method. Object.getOwnPropertyNames(E).forEach(function(name) { diff --git a/test/parallel/test-event-emitter-no-error-provided-to-error-event.js b/test/parallel/test-event-emitter-no-error-provided-to-error-event.js index 99bdeea79dc5bb..3e7242915e1854 100644 --- a/test/parallel/test-event-emitter-no-error-provided-to-error-event.js +++ b/test/parallel/test-event-emitter-no-error-provided-to-error-event.js @@ -3,9 +3,9 @@ const common = require('../common'); const assert = require('assert'); const events = require('events'); const domain = require('domain'); -var e = new events.EventEmitter(); +const e = new events.EventEmitter(); -var d = domain.create(); +const d = domain.create(); d.add(e); d.on('error', common.mustCall(function(er) { assert(er instanceof Error, 'error created'); diff --git a/test/parallel/test-event-emitter-num-args.js b/test/parallel/test-event-emitter-num-args.js index a5660b259ef483..d1027befa3f4ad 100644 --- a/test/parallel/test-event-emitter-num-args.js +++ b/test/parallel/test-event-emitter-num-args.js @@ -7,7 +7,7 @@ const e = new events.EventEmitter(); const num_args_emited = []; e.on('numArgs', function() { - var numArgs = arguments.length; + const numArgs = arguments.length; console.log('numArgs: ' + numArgs); num_args_emited.push(numArgs); }); diff --git a/test/parallel/test-event-emitter-once.js b/test/parallel/test-event-emitter-once.js index cca21a454b43bc..724b2ffd16aad1 100644 --- a/test/parallel/test-event-emitter-once.js +++ b/test/parallel/test-event-emitter-once.js @@ -12,7 +12,7 @@ e.emit('hello', 'a', 'b'); e.emit('hello', 'a', 'b'); e.emit('hello', 'a', 'b'); -var remove = function() { +const remove = function() { common.fail('once->foo should not be emitted'); }; diff --git a/test/parallel/test-event-emitter-prepend.js b/test/parallel/test-event-emitter-prepend.js index aa755a723c583e..5a3b66b0cb3250 100644 --- a/test/parallel/test-event-emitter-prepend.js +++ b/test/parallel/test-event-emitter-prepend.js @@ -5,7 +5,7 @@ const EventEmitter = require('events'); const assert = require('assert'); const myEE = new EventEmitter(); -var m = 0; +let m = 0; // This one comes last. myEE.on('foo', common.mustCall(() => assert.equal(m, 2))); diff --git a/test/parallel/test-event-emitter-remove-all-listeners.js b/test/parallel/test-event-emitter-remove-all-listeners.js index 076c1ea1d7b80f..38f9b7101eb775 100644 --- a/test/parallel/test-event-emitter-remove-all-listeners.js +++ b/test/parallel/test-event-emitter-remove-all-listeners.js @@ -66,7 +66,7 @@ function listener() {} { const ee = new events.EventEmitter(); - var expectLength = 2; + let expectLength = 2; ee.on('removeListener', function(name, listener) { assert.strictEqual(expectLength--, this.listeners('baz').length); }); diff --git a/test/parallel/test-event-emitter-set-max-listeners-side-effects.js b/test/parallel/test-event-emitter-set-max-listeners-side-effects.js index 64f7420fb2cfe6..5235d05638441b 100644 --- a/test/parallel/test-event-emitter-set-max-listeners-side-effects.js +++ b/test/parallel/test-event-emitter-set-max-listeners-side-effects.js @@ -3,7 +3,7 @@ require('../common'); const assert = require('assert'); const events = require('events'); -var e = new events.EventEmitter(); +const e = new events.EventEmitter(); assert(!(e._events instanceof Object)); assert.deepStrictEqual(Object.keys(e._events), []); diff --git a/test/parallel/test-event-emitter-subclass.js b/test/parallel/test-event-emitter-subclass.js index 27532dae46e4e4..d35802b413136b 100644 --- a/test/parallel/test-event-emitter-subclass.js +++ b/test/parallel/test-event-emitter-subclass.js @@ -13,7 +13,7 @@ function MyEE(cb) { EventEmitter.call(this); } -var myee = new MyEE(common.mustCall(function() {})); +const myee = new MyEE(common.mustCall(function() {})); util.inherits(ErrorEE, EventEmitter); @@ -38,8 +38,8 @@ function MyEE2() { MyEE2.prototype = new EventEmitter(); -var ee1 = new MyEE2(); -var ee2 = new MyEE2(); +const ee1 = new MyEE2(); +const ee2 = new MyEE2(); ee1.on('x', function() {}); diff --git a/test/parallel/test-exception-handler.js b/test/parallel/test-exception-handler.js index 1e2b2b89010d4e..506fbaed0ebf63 100644 --- a/test/parallel/test-exception-handler.js +++ b/test/parallel/test-exception-handler.js @@ -2,7 +2,7 @@ const common = require('../common'); const assert = require('assert'); -var MESSAGE = 'catch me if you can'; +const MESSAGE = 'catch me if you can'; process.on('uncaughtException', common.mustCall(function(e) { console.log('uncaught exception! 1'); diff --git a/test/parallel/test-file-write-stream2.js b/test/parallel/test-file-write-stream2.js index 77e8119d25b8a7..504a572dde67d7 100644 --- a/test/parallel/test-file-write-stream2.js +++ b/test/parallel/test-file-write-stream2.js @@ -7,14 +7,13 @@ const fs = require('fs'); const filepath = path.join(common.tmpDir, 'write.txt'); -var file; const EXPECTED = '012345678910'; const cb_expected = 'write open drain write drain close error '; -var cb_occurred = ''; +let cb_occurred = ''; -var countDrains = 0; +let countDrains = 0; process.on('exit', function() { @@ -41,7 +40,7 @@ function removeTestFile() { common.refreshTmpDir(); // drain at 0, return false at 10. -file = fs.createWriteStream(filepath, { +const file = fs.createWriteStream(filepath, { highWaterMark: 11 }); @@ -80,7 +79,7 @@ file.on('error', function(err) { }); -for (var i = 0; i < 11; i++) { +for (let i = 0; i < 11; i++) { const ret = file.write(i + ''); console.error('%d %j', i, ret); diff --git a/test/parallel/test-force-repl-with-eval.js b/test/parallel/test-force-repl-with-eval.js index e5044ba59df4d5..8c75818508d17e 100644 --- a/test/parallel/test-force-repl-with-eval.js +++ b/test/parallel/test-force-repl-with-eval.js @@ -5,11 +5,11 @@ const spawn = require('child_process').spawn; // spawn a node child process in "interactive" mode (force the repl) and eval const cp = spawn(process.execPath, ['-i', '-e', 'console.log("42")']); -var gotToEnd = false; +let gotToEnd = false; cp.stdout.setEncoding('utf8'); -var output = ''; +let output = ''; cp.stdout.on('data', function(b) { output += b; if (output === '> 42\n') { diff --git a/test/parallel/test-force-repl.js b/test/parallel/test-force-repl.js index 37f2f603342a1c..5507d7401b72d3 100644 --- a/test/parallel/test-force-repl.js +++ b/test/parallel/test-force-repl.js @@ -5,7 +5,7 @@ const spawn = require('child_process').spawn; // spawn a node child process in "interactive" mode (force the repl) const cp = spawn(process.execPath, ['-i']); -var timeoutId = setTimeout(function() { +const timeoutId = setTimeout(function() { common.fail('timeout!'); }, common.platformTimeout(5000)); // give node + the repl 5 seconds to start diff --git a/test/parallel/test-freelist.js b/test/parallel/test-freelist.js index 65758bd7114de8..8ec7134dad0eb5 100644 --- a/test/parallel/test-freelist.js +++ b/test/parallel/test-freelist.js @@ -12,7 +12,7 @@ assert.strictEqual(typeof freelist.FreeList, 'function'); const flist1 = new freelist.FreeList('flist1', 3, String); // Allocating when empty, should not change the list size -var result = flist1.alloc('test'); +const result = flist1.alloc('test'); assert.strictEqual(typeof result, 'string'); assert.strictEqual(result, 'test'); assert.strictEqual(flist1.list.length, 0); diff --git a/test/parallel/test-fs-access.js b/test/parallel/test-fs-access.js index a74ad9dccec271..4157f92f8b9021 100644 --- a/test/parallel/test-fs-access.js +++ b/test/parallel/test-fs-access.js @@ -107,7 +107,7 @@ assert.doesNotThrow(() => { }); assert.doesNotThrow(() => { - var mode = fs.F_OK | fs.R_OK | fs.W_OK; + const mode = fs.F_OK | fs.R_OK | fs.W_OK; fs.accessSync(readWriteFile, mode); }); diff --git a/test/parallel/test-fs-chmod.js b/test/parallel/test-fs-chmod.js index 2e5d839ae97720..5121fd89f99466 100644 --- a/test/parallel/test-fs-chmod.js +++ b/test/parallel/test-fs-chmod.js @@ -99,7 +99,7 @@ fs.open(file2, 'a', common.mustCall((err, fd) => { // lchmod if (fs.lchmod) { - var link = path.join(common.tmpDir, 'symbolic-link'); + const link = path.join(common.tmpDir, 'symbolic-link'); common.refreshTmpDir(); fs.symlinkSync(file2, link); diff --git a/test/parallel/test-fs-exists.js b/test/parallel/test-fs-exists.js index 5f9e9f50bf5d2f..14e1446f5a6d3d 100644 --- a/test/parallel/test-fs-exists.js +++ b/test/parallel/test-fs-exists.js @@ -2,7 +2,7 @@ const common = require('../common'); const assert = require('assert'); const fs = require('fs'); -var f = __filename; +const f = __filename; fs.exists(f, common.mustCall(function(y) { assert.strictEqual(y, true); diff --git a/test/parallel/test-fs-long-path.js b/test/parallel/test-fs-long-path.js index dd091ae1b1a94c..8d22159e24bd79 100644 --- a/test/parallel/test-fs-long-path.js +++ b/test/parallel/test-fs-long-path.js @@ -10,9 +10,9 @@ if (!common.isWindows) { } // make a path that will be at least 260 chars long. -var fileNameLen = Math.max(260 - common.tmpDir.length - 1, 1); -var fileName = path.join(common.tmpDir, new Array(fileNameLen + 1).join('x')); -var fullPath = path.resolve(fileName); +const fileNameLen = Math.max(260 - common.tmpDir.length - 1, 1); +const fileName = path.join(common.tmpDir, new Array(fileNameLen + 1).join('x')); +const fullPath = path.resolve(fileName); common.refreshTmpDir(); diff --git a/test/parallel/test-fs-open-flags.js b/test/parallel/test-fs-open-flags.js index 6c2fa9d2806dde..c8d6dd5eee4783 100644 --- a/test/parallel/test-fs-open-flags.js +++ b/test/parallel/test-fs-open-flags.js @@ -5,13 +5,13 @@ const assert = require('assert'); const fs = require('fs'); -var O_APPEND = fs.constants.O_APPEND || 0; -var O_CREAT = fs.constants.O_CREAT || 0; -var O_EXCL = fs.constants.O_EXCL || 0; -var O_RDONLY = fs.constants.O_RDONLY || 0; -var O_RDWR = fs.constants.O_RDWR || 0; -var O_TRUNC = fs.constants.O_TRUNC || 0; -var O_WRONLY = fs.constants.O_WRONLY || 0; +const O_APPEND = fs.constants.O_APPEND || 0; +const O_CREAT = fs.constants.O_CREAT || 0; +const O_EXCL = fs.constants.O_EXCL || 0; +const O_RDONLY = fs.constants.O_RDONLY || 0; +const O_RDWR = fs.constants.O_RDWR || 0; +const O_TRUNC = fs.constants.O_TRUNC || 0; +const O_WRONLY = fs.constants.O_WRONLY || 0; const { stringToFlags } = require('internal/fs'); diff --git a/test/parallel/test-fs-read-buffer-tostring-fail.js b/test/parallel/test-fs-read-buffer-tostring-fail.js index cce33edf4e6947..3ef058e4aa031e 100644 --- a/test/parallel/test-fs-read-buffer-tostring-fail.js +++ b/test/parallel/test-fs-read-buffer-tostring-fail.js @@ -14,7 +14,7 @@ const path = require('path'); const Buffer = require('buffer').Buffer; const kStringMaxLength = process.binding('buffer').kStringMaxLength; -var fd; +let fd; common.refreshTmpDir(); @@ -26,7 +26,7 @@ const stream = fs.createWriteStream(file, { const size = kStringMaxLength / 200; const a = Buffer.alloc(size, 'a'); -for (var i = 0; i < 201; i++) { +for (let i = 0; i < 201; i++) { stream.write(a); } diff --git a/test/parallel/test-fs-read-stream-fd-leak.js b/test/parallel/test-fs-read-stream-fd-leak.js index 45847270097348..0a7a42a3bab3c1 100644 --- a/test/parallel/test-fs-read-stream-fd-leak.js +++ b/test/parallel/test-fs-read-stream-fd-leak.js @@ -5,7 +5,7 @@ const assert = require('assert'); const fs = require('fs'); const path = require('path'); -var openCount = 0; +let openCount = 0; const _fsopen = fs.open; const _fsclose = fs.close; @@ -26,8 +26,8 @@ fs.close = function() { function testLeak(endFn, callback) { console.log('testing for leaks from fs.createReadStream().%s()...', endFn); - var i = 0; - var check = 0; + let i = 0; + let check = 0; const checkFunction = function() { if (openCount !== 0 && check < totalCheck) { diff --git a/test/parallel/test-fs-read-stream-resume.js b/test/parallel/test-fs-read-stream-resume.js index 3ff89644e5c018..6c8b2c2421c8e3 100644 --- a/test/parallel/test-fs-read-stream-resume.js +++ b/test/parallel/test-fs-read-stream-resume.js @@ -9,7 +9,7 @@ const file = path.join(common.fixturesDir, 'x.txt'); let data = ''; let first = true; -var stream = fs.createReadStream(file); +const stream = fs.createReadStream(file); stream.setEncoding('utf8'); stream.on('data', function(chunk) { data += chunk; diff --git a/test/parallel/test-fs-read-stream.js b/test/parallel/test-fs-read-stream.js index c8da0275c53c9b..d4fad6e6f79c07 100644 --- a/test/parallel/test-fs-read-stream.js +++ b/test/parallel/test-fs-read-stream.js @@ -7,13 +7,13 @@ const fs = require('fs'); const fn = path.join(common.fixturesDir, 'elipses.txt'); const rangeFile = path.join(common.fixturesDir, 'x.txt'); -var callbacks = { open: 0, end: 0, close: 0 }; +const callbacks = { open: 0, end: 0, close: 0 }; -var paused = false; -var bytesRead = 0; +let paused = false; +let bytesRead = 0; -var file = fs.ReadStream(fn); -var fileSize = fs.statSync(fn).size; +const file = fs.ReadStream(fn); +const fileSize = fs.statSync(fn).size; assert.strictEqual(file.bytesRead, 0); @@ -64,13 +64,13 @@ file.on('close', function() { //assert.equal(fs.readFileSync(fn), fileContent); }); -var file3 = fs.createReadStream(fn, {encoding: 'utf8'}); +const file3 = fs.createReadStream(fn, {encoding: 'utf8'}); file3.length = 0; file3.on('data', function(data) { assert.strictEqual('string', typeof data); file3.length += data.length; - for (var i = 0; i < data.length; i++) { + for (let i = 0; i < data.length; i++) { // http://www.fileformat.info/info/unicode/char/2026/index.htm assert.strictEqual('\u2026', data[i]); } @@ -89,8 +89,8 @@ process.on('exit', function() { console.error('ok'); }); -var file4 = fs.createReadStream(rangeFile, {bufferSize: 1, start: 1, end: 2}); -var contentRead = ''; +const file4 = fs.createReadStream(rangeFile, {bufferSize: 1, start: 1, end: 2}); +let contentRead = ''; file4.on('data', function(data) { contentRead += data.toString('utf-8'); }); @@ -98,7 +98,7 @@ file4.on('end', function(data) { assert.strictEqual(contentRead, 'yz'); }); -var file5 = fs.createReadStream(rangeFile, {bufferSize: 1, start: 1}); +const file5 = fs.createReadStream(rangeFile, {bufferSize: 1, start: 1}); file5.data = ''; file5.on('data', function(data) { file5.data += data.toString('utf-8'); @@ -108,7 +108,7 @@ file5.on('end', function() { }); // https://github.com/joyent/node/issues/2320 -var file6 = fs.createReadStream(rangeFile, {bufferSize: 1.23, start: 1}); +const file6 = fs.createReadStream(rangeFile, {bufferSize: 1.23, start: 1}); file6.data = ''; file6.on('data', function(data) { file6.data += data.toString('utf-8'); @@ -121,7 +121,7 @@ assert.throws(function() { fs.createReadStream(rangeFile, {start: 10, end: 2}); }, /"start" option must be <= "end" option/); -var stream = fs.createReadStream(rangeFile, { start: 0, end: 0 }); +const stream = fs.createReadStream(rangeFile, { start: 0, end: 0 }); stream.data = ''; stream.on('data', function(chunk) { @@ -133,11 +133,11 @@ stream.on('end', function() { }); // pause and then resume immediately. -var pauseRes = fs.createReadStream(rangeFile); +const pauseRes = fs.createReadStream(rangeFile); pauseRes.pause(); pauseRes.resume(); -var file7 = fs.createReadStream(rangeFile, {autoClose: false }); +let file7 = fs.createReadStream(rangeFile, {autoClose: false }); file7.on('data', function() {}); file7.on('end', function() { process.nextTick(function() { @@ -160,12 +160,12 @@ function file7Next() { } // Just to make sure autoClose won't close the stream because of error. -var file8 = fs.createReadStream(null, {fd: 13337, autoClose: false }); +const file8 = fs.createReadStream(null, {fd: 13337, autoClose: false }); file8.on('data', function() {}); file8.on('error', common.mustCall(function() {})); // Make sure stream is destroyed when file does not exist. -var file9 = fs.createReadStream('/path/to/file/that/does/not/exist'); +const file9 = fs.createReadStream('/path/to/file/that/does/not/exist'); file9.on('data', function() {}); file9.on('error', common.mustCall(function() {})); diff --git a/test/parallel/test-fs-read.js b/test/parallel/test-fs-read.js index 41957c228ea944..06755c0d6e050f 100644 --- a/test/parallel/test-fs-read.js +++ b/test/parallel/test-fs-read.js @@ -17,6 +17,6 @@ fs.read(fd, assert.strictEqual(bytesRead, expected.length); })); -var r = fs.readSync(fd, expected.length, 0, 'utf-8'); +const r = fs.readSync(fd, expected.length, 0, 'utf-8'); assert.strictEqual(r[0], expected); assert.strictEqual(r[1], expected.length); diff --git a/test/parallel/test-fs-readfile-fd.js b/test/parallel/test-fs-readfile-fd.js index 190a10fc538fd6..85fc6ebef5235d 100644 --- a/test/parallel/test-fs-readfile-fd.js +++ b/test/parallel/test-fs-readfile-fd.js @@ -39,7 +39,7 @@ function tempFd(callback) { } function tempFdSync(callback) { - var fd = fs.openSync(fn, 'r'); + const fd = fs.openSync(fn, 'r'); callback(fd); fs.closeSync(fd); } diff --git a/test/parallel/test-fs-realpath-buffer-encoding.js b/test/parallel/test-fs-realpath-buffer-encoding.js index fd7b0d5c3d42f3..0ce6ec576dac69 100644 --- a/test/parallel/test-fs-realpath-buffer-encoding.js +++ b/test/parallel/test-fs-realpath-buffer-encoding.js @@ -8,14 +8,15 @@ const buffer_dir = Buffer.from(string_dir); const encodings = ['ascii', 'utf8', 'utf16le', 'ucs2', 'base64', 'binary', 'hex']; -var expected = {}; +const expected = {}; encodings.forEach((encoding) => { expected[encoding] = buffer_dir.toString(encoding); }); // test sync version -for (var encoding in expected) { +let encoding; +for (encoding in expected) { const expected_value = expected[encoding]; let result; diff --git a/test/parallel/test-fs-realpath-on-substed-drive.js b/test/parallel/test-fs-realpath-on-substed-drive.js index ae2895553ed2f6..f8d9e86de5e618 100644 --- a/test/parallel/test-fs-realpath-on-substed-drive.js +++ b/test/parallel/test-fs-realpath-on-substed-drive.js @@ -14,7 +14,8 @@ let result; // create a subst drive const driveLetters = 'ABCDEFGHIJKLMNOPQRSTUWXYZ'; let drive; -for (var i = 0; i < driveLetters.length; ++i) { +let i; +for (i = 0; i < driveLetters.length; ++i) { drive = `${driveLetters[i]}:`; result = spawnSync('subst', [drive, common.fixturesDir]); if (result.status === 0) diff --git a/test/parallel/test-fs-realpath.js b/test/parallel/test-fs-realpath.js index 986e2089b44ab9..a444bf49846b1e 100644 --- a/test/parallel/test-fs-realpath.js +++ b/test/parallel/test-fs-realpath.js @@ -4,13 +4,14 @@ const assert = require('assert'); const fs = require('fs'); const path = require('path'); const exec = require('child_process').exec; -var async_completed = 0, async_expected = 0, unlink = []; -var skipSymlinks = false; +let async_completed = 0, async_expected = 0; +const unlink = []; +let skipSymlinks = false; common.refreshTmpDir(); -var root = '/'; -var assertEqualPath = assert.strictEqual; +let root = '/'; +let assertEqualPath = assert.strictEqual; if (common.isWindows) { // something like "C:\\" root = process.cwd().substr(0, 3); @@ -54,7 +55,7 @@ fs.mkdirSync(path.join(targetsAbsDir, 'nested-index', 'two')); function asynctest(testBlock, args, callback, assertBlock) { async_expected++; testBlock.apply(testBlock, args.concat(function(err) { - var ignoreError = false; + let ignoreError = false; if (assertBlock) { try { ignoreError = assertBlock.apply(assertBlock, arguments); @@ -216,7 +217,7 @@ function test_cyclic_link_overprotection(callback) { const expected = fs.realpathSync(cycles); const folder = cycles + '/folder'; const link = folder + '/cycles'; - var testPath = cycles; + let testPath = cycles; testPath += '/folder/cycles'.repeat(10); try { fs.unlinkSync(link); } catch (ex) {} fs.symlinkSync(cycles, link, 'dir'); @@ -474,7 +475,7 @@ const tests = [ test_up_multiple ]; const numtests = tests.length; -var testsRun = 0; +let testsRun = 0; function runNextTest(err) { assert.ifError(err); const test = tests.shift(); diff --git a/test/parallel/test-fs-sir-writes-alot.js b/test/parallel/test-fs-sir-writes-alot.js index 85feac59dda321..7bf97ff1d5cba3 100644 --- a/test/parallel/test-fs-sir-writes-alot.js +++ b/test/parallel/test-fs-sir-writes-alot.js @@ -4,33 +4,35 @@ const fs = require('fs'); const assert = require('assert'); const join = require('path').join; -var filename = join(common.tmpDir, 'out.txt'); +const filename = join(common.tmpDir, 'out.txt'); common.refreshTmpDir(); -var fd = fs.openSync(filename, 'w'); +const fd = fs.openSync(filename, 'w'); -var line = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n'; +const line = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n'; -var N = 10240, complete = 0; -for (var i = 0; i < N; i++) { +const N = 10240; +let complete = 0; + +for (let i = 0; i < N; i++) { // Create a new buffer for each write. Before the write is actually // executed by the thread pool, the buffer will be collected. - var buffer = Buffer.from(line); + const buffer = Buffer.from(line); fs.write(fd, buffer, 0, buffer.length, null, function(er, written) { complete++; if (complete === N) { fs.closeSync(fd); - var s = fs.createReadStream(filename); + const s = fs.createReadStream(filename); s.on('data', testBuffer); } }); } -var bytesChecked = 0; +let bytesChecked = 0; function testBuffer(b) { - for (var i = 0; i < b.length; i++) { + for (let i = 0; i < b.length; i++) { bytesChecked++; if (b[i] !== 'a'.charCodeAt(0) && b[i] !== '\n'.charCodeAt(0)) { throw new Error('invalid char ' + i + ',' + b[i]); diff --git a/test/parallel/test-fs-stat.js b/test/parallel/test-fs-stat.js index 48e59b884096f5..32ba47c2fe0c1e 100644 --- a/test/parallel/test-fs-stat.js +++ b/test/parallel/test-fs-stat.js @@ -37,7 +37,7 @@ fs.open('.', 'r', undefined, common.mustCall(function(err, fd) { // fstatSync fs.open('.', 'r', undefined, common.mustCall(function(err, fd) { - var stats; + let stats; try { stats = fs.fstatSync(fd); } catch (err) { diff --git a/test/parallel/test-fs-symlink-dir-junction-relative.js b/test/parallel/test-fs-symlink-dir-junction-relative.js index 166894c97ed846..3a2ba1a06c78db 100644 --- a/test/parallel/test-fs-symlink-dir-junction-relative.js +++ b/test/parallel/test-fs-symlink-dir-junction-relative.js @@ -6,10 +6,10 @@ const assert = require('assert'); const path = require('path'); const fs = require('fs'); -var linkPath1 = path.join(common.tmpDir, 'junction1'); -var linkPath2 = path.join(common.tmpDir, 'junction2'); -var linkTarget = path.join(common.fixturesDir); -var linkData = path.join(common.fixturesDir); +const linkPath1 = path.join(common.tmpDir, 'junction1'); +const linkPath2 = path.join(common.tmpDir, 'junction2'); +const linkTarget = path.join(common.fixturesDir); +const linkData = path.join(common.fixturesDir); common.refreshTmpDir(); @@ -24,11 +24,11 @@ fs.symlinkSync(linkData, linkPath2, 'junction'); verifyLink(linkPath2); function verifyLink(linkPath) { - var stats = fs.lstatSync(linkPath); + const stats = fs.lstatSync(linkPath); assert.ok(stats.isSymbolicLink()); - var data1 = fs.readFileSync(linkPath + '/x.txt', 'ascii'); - var data2 = fs.readFileSync(linkTarget + '/x.txt', 'ascii'); + const data1 = fs.readFileSync(linkPath + '/x.txt', 'ascii'); + const data2 = fs.readFileSync(linkTarget + '/x.txt', 'ascii'); assert.strictEqual(data1, data2); // Clean up. diff --git a/test/parallel/test-fs-symlink.js b/test/parallel/test-fs-symlink.js index 69b78dad3d2797..c8c6fc933d367b 100644 --- a/test/parallel/test-fs-symlink.js +++ b/test/parallel/test-fs-symlink.js @@ -4,8 +4,8 @@ const assert = require('assert'); const path = require('path'); const fs = require('fs'); -var linkTime; -var fileTime; +let linkTime; +let fileTime; if (!common.canCreateSymLink()) { common.skip('insufficient privileges'); diff --git a/test/parallel/test-fs-sync-fd-leak.js b/test/parallel/test-fs-sync-fd-leak.js index 67150f637dd7cc..353519593e2c4e 100644 --- a/test/parallel/test-fs-sync-fd-leak.js +++ b/test/parallel/test-fs-sync-fd-leak.js @@ -22,6 +22,7 @@ fs.fstatSync = function() { throw new Error('BAM'); }; +let close_called = 0; ensureThrows(function() { fs.readFileSync('dummy'); }); @@ -32,9 +33,8 @@ ensureThrows(function() { fs.appendFileSync('dummy', 'xxx'); }); -var close_called = 0; function ensureThrows(cb) { - var got_exception = false; + let got_exception = false; close_called = 0; try { diff --git a/test/parallel/test-fs-truncate-GH-6233.js b/test/parallel/test-fs-truncate-GH-6233.js index ee6ca1ca132b03..95eaf12cbb77f9 100644 --- a/test/parallel/test-fs-truncate-GH-6233.js +++ b/test/parallel/test-fs-truncate-GH-6233.js @@ -3,7 +3,7 @@ const common = require('../common'); const assert = require('assert'); const fs = require('fs'); -var filename = common.tmpDir + '/truncate-file.txt'; +const filename = common.tmpDir + '/truncate-file.txt'; common.refreshTmpDir(); diff --git a/test/parallel/test-fs-watch-recursive.js b/test/parallel/test-fs-watch-recursive.js index 97c65fccf4a1fb..5fb13623dff543 100644 --- a/test/parallel/test-fs-watch-recursive.js +++ b/test/parallel/test-fs-watch-recursive.js @@ -22,7 +22,7 @@ const filepathOne = path.join(testsubdir, filenameOne); const watcher = fs.watch(testDir, {recursive: true}); -var watcherClosed = false; +let watcherClosed = false; watcher.on('change', function(event, filename) { assert.ok('change' === event || 'rename' === event); @@ -37,8 +37,9 @@ watcher.on('change', function(event, filename) { watcherClosed = true; }); +let interval; if (common.isOSX) { - var interval = setInterval(function() { + interval = setInterval(function() { fs.writeFileSync(filepathOne, 'world'); }, 10); } else { diff --git a/test/parallel/test-fs-watchfile.js b/test/parallel/test-fs-watchfile.js index d30261859c39b7..fcd28be0c1f126 100644 --- a/test/parallel/test-fs-watchfile.js +++ b/test/parallel/test-fs-watchfile.js @@ -40,7 +40,7 @@ common.refreshTmpDir(); // If the file initially didn't exist, and gets created at a later point of // time, the callback should be invoked again with proper values in stat object -var fileExists = false; +let fileExists = false; fs.watchFile(enoentFile, {interval: 0}, common.mustCall(function(curr, prev) { if (!fileExists) { diff --git a/test/parallel/test-fs-write-buffer.js b/test/parallel/test-fs-write-buffer.js index 927ebb15412bc8..89570314cc504c 100644 --- a/test/parallel/test-fs-write-buffer.js +++ b/test/parallel/test-fs-write-buffer.js @@ -19,7 +19,7 @@ common.refreshTmpDir(); assert.strictEqual(expected.length, written); fs.closeSync(fd); - var found = fs.readFileSync(filename, 'utf8'); + const found = fs.readFileSync(filename, 'utf8'); assert.strictEqual(expected.toString(), found); }); diff --git a/test/parallel/test-fs-write-file-buffer.js b/test/parallel/test-fs-write-file-buffer.js index e2c7b1d01e4241..409ddf1d51f557 100644 --- a/test/parallel/test-fs-write-file-buffer.js +++ b/test/parallel/test-fs-write-file-buffer.js @@ -4,7 +4,7 @@ const join = require('path').join; const util = require('util'); const fs = require('fs'); -var data = [ +let data = [ '/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAUDBAQEAwUEBAQFBQUGBwwIBwcH', 'Bw8LCwkMEQ8SEhEPERETFhwXExQaFRERGCEYGh0dHx8fExciJCIeJBweHx7/', '2wBDAQUFBQcGBw4ICA4eFBEUHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4e', @@ -27,7 +27,7 @@ data = data.join('\n'); common.refreshTmpDir(); -var buf = Buffer.from(data, 'base64'); +const buf = Buffer.from(data, 'base64'); fs.writeFileSync(join(common.tmpDir, 'test.jpg'), buf); util.log('Done!'); diff --git a/test/parallel/test-fs-write-stream-change-open.js b/test/parallel/test-fs-write-stream-change-open.js index a9d31a3074dcd6..f68cc0a6d386e2 100644 --- a/test/parallel/test-fs-write-stream-change-open.js +++ b/test/parallel/test-fs-write-stream-change-open.js @@ -4,7 +4,7 @@ const assert = require('assert'); const path = require('path'); const fs = require('fs'); -var file = path.join(common.tmpDir, 'write.txt'); +const file = path.join(common.tmpDir, 'write.txt'); common.refreshTmpDir(); diff --git a/test/parallel/test-fs-write-stream-err.js b/test/parallel/test-fs-write-stream-err.js index 22137329bfa181..d50fd07103222e 100644 --- a/test/parallel/test-fs-write-stream-err.js +++ b/test/parallel/test-fs-write-stream-err.js @@ -5,13 +5,13 @@ const fs = require('fs'); common.refreshTmpDir(); -var stream = fs.createWriteStream(common.tmpDir + '/out', { +const stream = fs.createWriteStream(common.tmpDir + '/out', { highWaterMark: 10 }); -var err = new Error('BAM'); +const err = new Error('BAM'); -var write = fs.write; -var writeCalls = 0; +const write = fs.write; +let writeCalls = 0; fs.write = function() { switch (writeCalls++) { case 0: @@ -21,7 +21,7 @@ fs.write = function() { case 1: // then it breaks console.error('second write'); - var cb = arguments[arguments.length - 1]; + const cb = arguments[arguments.length - 1]; return process.nextTick(function() { cb(err); }); diff --git a/test/parallel/test-fs-write-stream.js b/test/parallel/test-fs-write-stream.js index 71aaaa75dd5845..a3ba0377e2e26e 100644 --- a/test/parallel/test-fs-write-stream.js +++ b/test/parallel/test-fs-write-stream.js @@ -4,7 +4,7 @@ const assert = require('assert'); const path = require('path'); const fs = require('fs'); -var file = path.join(common.tmpDir, 'write.txt'); +const file = path.join(common.tmpDir, 'write.txt'); common.refreshTmpDir(); diff --git a/test/parallel/test-fs-write-string-coerce.js b/test/parallel/test-fs-write-string-coerce.js index 4179ba0332121f..2694312b863571 100644 --- a/test/parallel/test-fs-write-string-coerce.js +++ b/test/parallel/test-fs-write-string-coerce.js @@ -7,9 +7,9 @@ const fs = require('fs'); common.refreshTmpDir(); -var fn = path.join(common.tmpDir, 'write-string-coerce.txt'); -var data = true; -var expected = data + ''; +const fn = path.join(common.tmpDir, 'write-string-coerce.txt'); +const data = true; +const expected = data + ''; fs.open(fn, 'w', 0o644, common.mustCall(function(err, fd) { assert.ifError(err); diff --git a/test/parallel/test-global-console-exists.js b/test/parallel/test-global-console-exists.js index 32e640cc52f7fc..d4a7c21222b807 100644 --- a/test/parallel/test-global-console-exists.js +++ b/test/parallel/test-global-console-exists.js @@ -9,7 +9,7 @@ const assert = require('assert'); const EventEmitter = require('events'); const leak_warning = /EventEmitter memory leak detected\. 2 hello listeners/; -var write_calls = 0; +let write_calls = 0; process.on('warning', (warning) => { // This will be called after the default internal diff --git a/test/parallel/test-http-1.0-keep-alive.js b/test/parallel/test-http-1.0-keep-alive.js index 301c054fc9a246..dea5f65c54184d 100644 --- a/test/parallel/test-http-1.0-keep-alive.js +++ b/test/parallel/test-http-1.0-keep-alive.js @@ -83,12 +83,12 @@ check([{ }]); function check(tests) { - var test = tests[0]; - var server; + const test = tests[0]; + let server; if (test) { server = http.createServer(serverHandler).listen(0, '127.0.0.1', client); } - var current = 0; + let current = 0; function next() { check(tests.slice(1)); @@ -96,7 +96,7 @@ function check(tests) { function serverHandler(req, res) { if (current + 1 === test.responses.length) this.close(); - var ctx = test.responses[current]; + const ctx = test.responses[current]; console.error('< SERVER SENDING RESPONSE', ctx); res.writeHead(200, ctx.headers); ctx.chunks.slice(0, -1).forEach(function(chunk) { res.write(chunk); }); @@ -106,10 +106,10 @@ function check(tests) { function client() { if (current === test.requests.length) return next(); const port = server.address().port; - var conn = net.createConnection(port, '127.0.0.1', connected); + const conn = net.createConnection(port, '127.0.0.1', connected); function connected() { - var ctx = test.requests[current]; + const ctx = test.requests[current]; console.error(' > CLIENT SENDING REQUEST', ctx); conn.setEncoding('utf8'); conn.write(ctx.data); diff --git a/test/parallel/test-http-1.0.js b/test/parallel/test-http-1.0.js index 926497d002e473..d98da182a9fee5 100644 --- a/test/parallel/test-http-1.0.js +++ b/test/parallel/test-http-1.0.js @@ -4,17 +4,17 @@ const assert = require('assert'); const net = require('net'); const http = require('http'); -var body = 'hello world\n'; +const body = 'hello world\n'; function test(handler, request_generator, response_validator) { - var server = http.createServer(handler); + const server = http.createServer(handler); - var client_got_eof = false; - var server_response = ''; + let client_got_eof = false; + let server_response = ''; server.listen(0); server.on('listening', function() { - var c = net.createConnection(this.address().port); + const c = net.createConnection(this.address().port); c.setEncoding('utf8'); diff --git a/test/parallel/test-http-abort-before-end.js b/test/parallel/test-http-abort-before-end.js index 5e0baf3cdfdbd6..046f439cb33195 100644 --- a/test/parallel/test-http-abort-before-end.js +++ b/test/parallel/test-http-abort-before-end.js @@ -3,10 +3,10 @@ const common = require('../common'); const http = require('http'); const assert = require('assert'); -var server = http.createServer(common.fail); +const server = http.createServer(common.fail); server.listen(0, function() { - var req = http.request({ + const req = http.request({ method: 'GET', host: '127.0.0.1', port: this.address().port diff --git a/test/parallel/test-http-abort-client.js b/test/parallel/test-http-abort-client.js index 9ee2974c46514d..6c00a1e6c64328 100644 --- a/test/parallel/test-http-abort-client.js +++ b/test/parallel/test-http-abort-client.js @@ -2,7 +2,7 @@ const common = require('../common'); const http = require('http'); -var server = http.Server(function(req, res) { +const server = http.Server(function(req, res) { console.log('Server accepted request.'); res.writeHead(200); res.write('Part of my res.'); diff --git a/test/parallel/test-http-abort-queued.js b/test/parallel/test-http-abort-queued.js index 0a993a2658ca11..8e8339aa82d3dd 100644 --- a/test/parallel/test-http-abort-queued.js +++ b/test/parallel/test-http-abort-queued.js @@ -3,9 +3,9 @@ require('../common'); const assert = require('assert'); const http = require('http'); -var complete; +let complete; -var server = http.createServer(function(req, res) { +const server = http.createServer(function(req, res) { // We should not see the queued /thatotherone request within the server // as it should be aborted before it is sent. assert.equal(req.url, '/'); @@ -22,10 +22,10 @@ var server = http.createServer(function(req, res) { server.listen(0, function() { console.log('listen', server.address().port); - var agent = new http.Agent({maxSockets: 1}); + const agent = new http.Agent({maxSockets: 1}); assert.equal(Object.keys(agent.sockets).length, 0); - var options = { + const options = { hostname: 'localhost', port: server.address().port, method: 'GET', @@ -33,12 +33,12 @@ server.listen(0, function() { agent: agent }; - var req1 = http.request(options); + const req1 = http.request(options); req1.on('response', function(res1) { assert.equal(Object.keys(agent.sockets).length, 1); assert.equal(Object.keys(agent.requests).length, 0); - var req2 = http.request({ + const req2 = http.request({ method: 'GET', host: 'localhost', port: server.address().port, diff --git a/test/parallel/test-http-after-connect.js b/test/parallel/test-http-after-connect.js index 0580f428ed70f5..a93d0b83aa6f4f 100644 --- a/test/parallel/test-http-after-connect.js +++ b/test/parallel/test-http-after-connect.js @@ -3,7 +3,7 @@ const common = require('../common'); const assert = require('assert'); const http = require('http'); -var clientResponses = 0; +let clientResponses = 0; const server = http.createServer(common.mustCall(function(req, res) { console.error('Server got GET request'); @@ -46,7 +46,7 @@ function doRequest(i) { path: '/request' + i }, common.mustCall(function(res) { console.error('Client got GET response'); - var data = ''; + let data = ''; res.setEncoding('utf8'); res.on('data', function(chunk) { data += chunk; diff --git a/test/parallel/test-http-agent-destroyed-socket.js b/test/parallel/test-http-agent-destroyed-socket.js index 3a6cc5365812f0..d983d447934e41 100644 --- a/test/parallel/test-http-agent-destroyed-socket.js +++ b/test/parallel/test-http-agent-destroyed-socket.js @@ -3,26 +3,26 @@ require('../common'); const assert = require('assert'); const http = require('http'); -var server = http.createServer(function(req, res) { +const server = http.createServer(function(req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World\n'); }).listen(0, function() { - var agent = new http.Agent({maxSockets: 1}); + const agent = new http.Agent({maxSockets: 1}); agent.on('free', function(socket, host, port) { console.log('freeing socket. destroyed? ', socket.destroyed); }); - var requestOptions = { + const requestOptions = { agent: agent, host: 'localhost', port: this.address().port, path: '/' }; - var request1 = http.get(requestOptions, function(response) { + const request1 = http.get(requestOptions, function(response) { // assert request2 is queued in the agent - var key = agent.getName(requestOptions); + const key = agent.getName(requestOptions); assert.strictEqual(agent.requests[key].length, 1); console.log('got response1'); request1.socket.on('close', function() { @@ -58,14 +58,14 @@ var server = http.createServer(function(req, res) { }); }); - var request2 = http.get(requestOptions, function(response) { + const request2 = http.get(requestOptions, function(response) { assert(!request2.socket.destroyed); assert(request1.socket.destroyed); // assert not reusing the same socket, since it was destroyed. assert.notStrictEqual(request1.socket, request2.socket); console.log('got response2'); - var gotClose = false; - var gotResponseEnd = false; + let gotClose = false; + let gotResponseEnd = false; request2.socket.on('close', function() { console.log('request2 socket closed'); gotClose = true; diff --git a/test/parallel/test-http-agent-error-on-idle.js b/test/parallel/test-http-agent-error-on-idle.js index 14a058a6f8f2d9..b2bf6334dcbc1b 100644 --- a/test/parallel/test-http-agent-error-on-idle.js +++ b/test/parallel/test-http-agent-error-on-idle.js @@ -2,37 +2,37 @@ require('../common'); const assert = require('assert'); const http = require('http'); -var Agent = http.Agent; +const Agent = http.Agent; -var server = http.createServer(function(req, res) { +const server = http.createServer(function(req, res) { res.end('hello world'); }); server.listen(0, function() { - var agent = new Agent({ + const agent = new Agent({ keepAlive: true, }); - var requestParams = { + const requestParams = { host: 'localhost', port: this.address().port, agent: agent, path: '/' }; - var socketKey = agent.getName(requestParams); + const socketKey = agent.getName(requestParams); get(function(res) { assert.equal(res.statusCode, 200); res.resume(); res.on('end', function() { process.nextTick(function() { - var freeSockets = agent.freeSockets[socketKey]; + const freeSockets = agent.freeSockets[socketKey]; assert.equal(freeSockets.length, 1, 'expect a free socket on ' + socketKey); //generate a random error on the free socket - var freeSocket = freeSockets[0]; + const freeSocket = freeSockets[0]; freeSocket.emit('error', new Error('ECONNRESET: test')); get(done); diff --git a/test/parallel/test-http-agent-false.js b/test/parallel/test-http-agent-false.js index 65da4b836a9fe1..5c9907bb706d32 100644 --- a/test/parallel/test-http-agent-false.js +++ b/test/parallel/test-http-agent-false.js @@ -6,7 +6,7 @@ const http = require('http'); // sending `agent: false` when `port: null` is also passed in (i.e. the result // of a `url.parse()` call with the default port used, 80 or 443), should not // result in an assertion error... -var opts = { +const opts = { host: '127.0.0.1', port: null, path: '/', @@ -14,7 +14,7 @@ var opts = { agent: false }; -var good = false; +let good = false; process.on('exit', function() { assert(good, 'expected either an "error" or "response" event'); }); @@ -22,7 +22,7 @@ process.on('exit', function() { // we just want an "error" (no local HTTP server on port 80) or "response" // to happen (user happens ot have HTTP server running on port 80). // As long as the process doesn't crash from a C++ assertion then we're good. -var req = http.request(opts); +const req = http.request(opts); req.on('response', function(res) { good = true; }); diff --git a/test/parallel/test-http-agent-maxsockets-regress-4050.js b/test/parallel/test-http-agent-maxsockets-regress-4050.js index 0ba3d1304f0d68..fd3a8c33f3e39a 100644 --- a/test/parallel/test-http-agent-maxsockets-regress-4050.js +++ b/test/parallel/test-http-agent-maxsockets-regress-4050.js @@ -26,9 +26,9 @@ function get(path, callback) { } server.listen(0, function() { - var finished = 0; + let finished = 0; const num_requests = 6; - for (var i = 0; i < num_requests; i++) { + for (let i = 0; i < num_requests; i++) { const request = get('/1', function() { }); request.on('response', function() { diff --git a/test/parallel/test-http-agent-maxsockets.js b/test/parallel/test-http-agent-maxsockets.js index b71cbd95c4556c..6814aca3e76fbc 100644 --- a/test/parallel/test-http-agent-maxsockets.js +++ b/test/parallel/test-http-agent-maxsockets.js @@ -3,14 +3,14 @@ require('../common'); const assert = require('assert'); const http = require('http'); -var agent = new http.Agent({ +const agent = new http.Agent({ keepAlive: true, keepAliveMsecs: 1000, maxSockets: 2, maxFreeSockets: 2 }); -var server = http.createServer(function(req, res) { +const server = http.createServer(function(req, res) { res.end('hello world'); }); @@ -23,12 +23,12 @@ function get(path, callback) { }, callback); } -var count = 0; +let count = 0; function done() { if (++count !== 2) { return; } - var freepool = agent.freeSockets[Object.keys(agent.freeSockets)[0]]; + const freepool = agent.freeSockets[Object.keys(agent.freeSockets)[0]]; assert.equal(freepool.length, 2, 'expect keep 2 free sockets, but got ' + freepool.length); agent.destroy(); diff --git a/test/parallel/test-http-agent-no-protocol.js b/test/parallel/test-http-agent-no-protocol.js index e2c748b011f545..a11489b6c5bc2b 100644 --- a/test/parallel/test-http-agent-no-protocol.js +++ b/test/parallel/test-http-agent-no-protocol.js @@ -3,10 +3,10 @@ const common = require('../common'); const http = require('http'); const url = require('url'); -var server = http.createServer(common.mustCall(function(req, res) { +const server = http.createServer(common.mustCall(function(req, res) { res.end(); })).listen(0, '127.0.0.1', common.mustCall(function() { - var opts = url.parse(`http://127.0.0.1:${this.address().port}/`); + const opts = url.parse(`http://127.0.0.1:${this.address().port}/`); // remove the `protocol` field… the `http` module should fall back // to "http:", as defined by the global, default `http.Agent` instance. diff --git a/test/parallel/test-http-agent-null.js b/test/parallel/test-http-agent-null.js index 426ec3bb762909..9071b88b98997a 100644 --- a/test/parallel/test-http-agent-null.js +++ b/test/parallel/test-http-agent-null.js @@ -2,10 +2,10 @@ const common = require('../common'); const http = require('http'); -var server = http.createServer(common.mustCall(function(req, res) { +const server = http.createServer(common.mustCall(function(req, res) { res.end(); })).listen(0, common.mustCall(function() { - var options = { + const options = { agent: null, port: this.address().port }; diff --git a/test/parallel/test-http-agent.js b/test/parallel/test-http-agent.js index 443af96215fd92..85975979cb3265 100644 --- a/test/parallel/test-http-agent.js +++ b/test/parallel/test-http-agent.js @@ -3,20 +3,20 @@ require('../common'); const assert = require('assert'); const http = require('http'); -var server = http.Server(function(req, res) { +const server = http.Server(function(req, res) { res.writeHead(200); res.end('hello world\n'); }); -var responses = 0; -var N = 4; -var M = 4; +let responses = 0; +const N = 4; +const M = 4; server.listen(0, function() { const port = this.address().port; - for (var i = 0; i < N; i++) { + for (let i = 0; i < N; i++) { setTimeout(function() { - for (var j = 0; j < M; j++) { + for (let j = 0; j < M; j++) { http.get({ port: port, path: '/' }, function(res) { console.log('%d %d', responses, res.statusCode); if (++responses === N * M) { diff --git a/test/parallel/test-http-automatic-headers.js b/test/parallel/test-http-automatic-headers.js index b15330342ce0cb..5fc8d780af9396 100644 --- a/test/parallel/test-http-automatic-headers.js +++ b/test/parallel/test-http-automatic-headers.js @@ -3,7 +3,7 @@ require('../common'); const assert = require('assert'); const http = require('http'); -var server = http.createServer(function(req, res) { +const server = http.createServer(function(req, res) { res.setHeader('X-Date', 'foo'); res.setHeader('X-Connection', 'bar'); res.setHeader('X-Content-Length', 'baz'); @@ -12,7 +12,7 @@ var server = http.createServer(function(req, res) { server.listen(0); server.on('listening', function() { - var agent = new http.Agent({ port: this.address().port, maxSockets: 1 }); + const agent = new http.Agent({ port: this.address().port, maxSockets: 1 }); http.get({ port: this.address().port, path: '/hello', diff --git a/test/parallel/test-http-blank-header.js b/test/parallel/test-http-blank-header.js index 863cbed19d790b..2a6bf482077166 100644 --- a/test/parallel/test-http-blank-header.js +++ b/test/parallel/test-http-blank-header.js @@ -4,7 +4,7 @@ const assert = require('assert'); const http = require('http'); const net = require('net'); -var server = http.createServer(common.mustCall(function(req, res) { +const server = http.createServer(common.mustCall(function(req, res) { assert.equal('GET', req.method); assert.equal('/blah', req.url); assert.deepStrictEqual({ @@ -16,7 +16,7 @@ var server = http.createServer(common.mustCall(function(req, res) { server.listen(0, function() { - var c = net.createConnection(this.address().port); + const c = net.createConnection(this.address().port); c.on('connect', function() { c.write('GET /blah HTTP/1.1\r\n' + diff --git a/test/parallel/test-http-buffer-sanity.js b/test/parallel/test-http-buffer-sanity.js index d71f3bdb783267..c240cd13b1825c 100644 --- a/test/parallel/test-http-buffer-sanity.js +++ b/test/parallel/test-http-buffer-sanity.js @@ -3,26 +3,26 @@ const common = require('../common'); const assert = require('assert'); const http = require('http'); -var bufferSize = 5 * 1024 * 1024; -var measuredSize = 0; +const bufferSize = 5 * 1024 * 1024; +let measuredSize = 0; -var buffer = Buffer.allocUnsafe(bufferSize); -for (var i = 0; i < buffer.length; i++) { +const buffer = Buffer.allocUnsafe(bufferSize); +for (let i = 0; i < buffer.length; i++) { buffer[i] = i % 256; } -var web = http.Server(function(req, res) { +const web = http.Server(function(req, res) { web.close(); console.log(req.headers); - var i = 0; + let i = 0; req.on('data', function(d) { process.stdout.write(','); measuredSize += d.length; - for (var j = 0; j < d.length; j++) { + for (let j = 0; j < d.length; j++) { assert.equal(buffer[i], d[j]); i++; } @@ -45,7 +45,7 @@ var web = http.Server(function(req, res) { web.listen(0, common.mustCall(function() { console.log('Making request'); - var req = http.request({ + const req = http.request({ port: this.address().port, method: 'GET', path: '/', diff --git a/test/parallel/test-http-byteswritten.js b/test/parallel/test-http-byteswritten.js index 1ef5f2398d77ed..3b295ebdcc1c49 100644 --- a/test/parallel/test-http-byteswritten.js +++ b/test/parallel/test-http-byteswritten.js @@ -3,9 +3,9 @@ const common = require('../common'); const assert = require('assert'); const http = require('http'); -var body = 'hello world\n'; +const body = 'hello world\n'; -var httpServer = http.createServer(common.mustCall(function(req, res) { +const httpServer = http.createServer(common.mustCall(function(req, res) { httpServer.close(); res.on('finish', common.mustCall(function() { @@ -16,9 +16,9 @@ var httpServer = http.createServer(common.mustCall(function(req, res) { // Write 1.5mb to cause some requests to buffer // Also, mix up the encodings a bit. - var chunk = new Array(1024 + 1).join('7'); - var bchunk = Buffer.from(chunk); - for (var i = 0; i < 1024; i++) { + const chunk = new Array(1024 + 1).join('7'); + const bchunk = Buffer.from(chunk); + for (let i = 0; i < 1024; i++) { res.write(chunk); res.write(bchunk); res.write(chunk, 'hex'); diff --git a/test/parallel/test-http-chunked.js b/test/parallel/test-http-chunked.js index d8891db6c75aea..516523221133ec 100644 --- a/test/parallel/test-http-chunked.js +++ b/test/parallel/test-http-chunked.js @@ -3,23 +3,23 @@ require('../common'); const assert = require('assert'); const http = require('http'); -var UTF8_STRING = '南越国是前203年至前111年存在于岭南地区的一个国家,' + - '国都位于番禺,疆域包括今天中国的广东、广西两省区的大部份地区,福建省、湖南、' + - '贵州、云南的一小部份地区和越南的北部。南越国是秦朝灭亡后,' + - '由南海郡尉赵佗于前203年起兵兼并桂林郡和象郡后建立。前196年和前179年,' + - '南越国曾先后两次名义上臣属于西汉,成为西汉的“外臣”。前112年,' + - '南越国末代君主赵建德与西汉发生战争,被汉武帝于前111年所灭。' + - '南越国共存在93年,历经五代君主。南越国是岭南地区的第一个有记载的政权国家,' + - '采用封建制和郡县制并存的制度,它的建立保证了秦末乱世岭南地区社会秩序的稳定,' + - '有效的改善了岭南地区落后的政治、经济现状。'; +const UTF8_STRING = '南越国是前203年至前111年存在于岭南地区的一个国家,' + + '国都位于番禺,疆域包括今天中国的广东、广西两省区的大部份地区,福建省、湖南、' + + '贵州、云南的一小部份地区和越南的北部。南越国是秦朝灭亡后,' + + '由南海郡尉赵佗于前203年起兵兼并桂林郡和象郡后建立。前196年和前179年,' + + '南越国曾先后两次名义上臣属于西汉,成为西汉的“外臣”。前112年,' + + '南越国末代君主赵建德与西汉发生战争,被汉武帝于前111年所灭。' + + '南越国共存在93年,历经五代君主。南越国是岭南地区的第一个有记载的政权国家,' + + '采用封建制和郡县制并存的制度,它的建立保证了秦末乱世岭南地区社会秩序的稳定,' + + '有效的改善了岭南地区落后的政治、经济现状。'; -var server = http.createServer(function(req, res) { +const server = http.createServer(function(req, res) { res.writeHead(200, {'Content-Type': 'text/plain; charset=utf8'}); res.end(UTF8_STRING, 'utf8'); }); server.listen(0, function() { - var data = ''; - var get = http.get({ + let data = ''; + const get = http.get({ path: '/', host: 'localhost', port: this.address().port diff --git a/test/parallel/test-http-client-abort-event.js b/test/parallel/test-http-client-abort-event.js index 00c989ca919dc7..b62186e724d919 100644 --- a/test/parallel/test-http-client-abort-event.js +++ b/test/parallel/test-http-client-abort-event.js @@ -1,12 +1,12 @@ 'use strict'; const common = require('../common'); const http = require('http'); -var server = http.createServer(function(req, res) { +const server = http.createServer(function(req, res) { res.end(); }); server.listen(0, common.mustCall(function() { - var req = http.request({ + const req = http.request({ port: this.address().port }, common.fail); diff --git a/test/parallel/test-http-client-abort.js b/test/parallel/test-http-client-abort.js index 4f46128f0e804a..738c620815a21a 100644 --- a/test/parallel/test-http-client-abort.js +++ b/test/parallel/test-http-client-abort.js @@ -3,7 +3,7 @@ require('../common'); const assert = require('assert'); const http = require('http'); -var clientAborts = 0; +let clientAborts = 0; const server = http.Server(function(req, res) { console.log('Got connection'); @@ -23,17 +23,17 @@ const server = http.Server(function(req, res) { }); }); -var responses = 0; +let responses = 0; const N = 8; const requests = []; server.listen(0, function() { console.log('Server listening.'); - for (var i = 0; i < N; i++) { + for (let i = 0; i < N; i++) { console.log('Making client ' + i); - var options = { port: this.address().port, path: '/?id=' + i }; - var req = http.get(options, function(res) { + const options = { port: this.address().port, path: '/?id=' + i }; + const req = http.get(options, function(res) { console.log('Client response code ' + res.statusCode); res.resume(); diff --git a/test/parallel/test-http-client-abort2.js b/test/parallel/test-http-client-abort2.js index 346b781ef08dfd..7c7be9b530e2d2 100644 --- a/test/parallel/test-http-client-abort2.js +++ b/test/parallel/test-http-client-abort2.js @@ -2,12 +2,12 @@ require('../common'); const http = require('http'); -var server = http.createServer(function(req, res) { +const server = http.createServer(function(req, res) { res.end('Hello'); }); server.listen(0, function() { - var req = http.get({port: this.address().port}, function(res) { + const req = http.get({port: this.address().port}, function(res) { res.on('data', function(data) { req.abort(); server.close(); diff --git a/test/parallel/test-http-client-agent.js b/test/parallel/test-http-client-agent.js index 8093100fce2b88..3c2b9c89727467 100644 --- a/test/parallel/test-http-client-agent.js +++ b/test/parallel/test-http-client-agent.js @@ -3,11 +3,11 @@ require('../common'); const assert = require('assert'); const http = require('http'); -var name; -var max = 3; -var count = 0; +let name; +const max = 3; +let count = 0; -var server = http.Server(function(req, res) { +const server = http.Server(function(req, res) { if (req.url === '/0') { setTimeout(function() { res.writeHead(200); @@ -20,17 +20,17 @@ var server = http.Server(function(req, res) { }); server.listen(0, function() { name = http.globalAgent.getName({ port: this.address().port }); - for (var i = 0; i < max; ++i) { + for (let i = 0; i < max; ++i) { request(i); } }); function request(i) { - var req = http.get({ + const req = http.get({ port: server.address().port, path: '/' + i }, function(res) { - var socket = req.socket; + const socket = req.socket; socket.on('close', function() { ++count; if (count < max) { diff --git a/test/parallel/test-http-client-default-headers-exist.js b/test/parallel/test-http-client-default-headers-exist.js index 3a1f52819335b8..2271944773d9db 100644 --- a/test/parallel/test-http-client-default-headers-exist.js +++ b/test/parallel/test-http-client-default-headers-exist.js @@ -3,7 +3,7 @@ require('../common'); const assert = require('assert'); const http = require('http'); -var expectedHeaders = { +const expectedHeaders = { 'DELETE': ['host', 'connection'], 'GET': ['host', 'connection'], 'HEAD': ['host', 'connection'], @@ -12,18 +12,18 @@ var expectedHeaders = { 'PUT': ['host', 'connection', 'content-length'] }; -var expectedMethods = Object.keys(expectedHeaders); +const expectedMethods = Object.keys(expectedHeaders); -var requestCount = 0; +let requestCount = 0; -var server = http.createServer(function(req, res) { +const server = http.createServer(function(req, res) { requestCount++; res.end(); assert(expectedHeaders.hasOwnProperty(req.method), req.method + ' was an unexpected method'); - var requestHeaders = Object.keys(req.headers); + const requestHeaders = Object.keys(req.headers); requestHeaders.forEach(function(header) { assert.notStrictEqual( expectedHeaders[req.method].indexOf(header.toLowerCase()), diff --git a/test/parallel/test-http-client-get-url.js b/test/parallel/test-http-client-get-url.js index d9a5e9325699d2..9311110bdc041c 100644 --- a/test/parallel/test-http-client-get-url.js +++ b/test/parallel/test-http-client-get-url.js @@ -5,7 +5,7 @@ const http = require('http'); const url = require('url'); const URL = url.URL; -var server = http.createServer(common.mustCall(function(req, res) { +const server = http.createServer(common.mustCall(function(req, res) { assert.equal('GET', req.method); assert.equal('/foo?bar', req.url); res.writeHead(200, {'Content-Type': 'text/plain'}); diff --git a/test/parallel/test-http-client-parse-error.js b/test/parallel/test-http-client-parse-error.js index c7469c1562566a..0d8f577a78566c 100644 --- a/test/parallel/test-http-client-parse-error.js +++ b/test/parallel/test-http-client-parse-error.js @@ -5,8 +5,8 @@ const assert = require('assert'); const http = require('http'); const net = require('net'); -var connects = 0; -var parseErrors = 0; +let connects = 0; +let parseErrors = 0; // Create a TCP server net.createServer(function(c) { @@ -18,7 +18,7 @@ net.createServer(function(c) { this.close(); } }).listen(0, '127.0.0.1', function() { - for (var i = 0; i < 2; i++) { + for (let i = 0; i < 2; i++) { http.request({ host: '127.0.0.1', port: this.address().port, diff --git a/test/parallel/test-http-client-pipe-end.js b/test/parallel/test-http-client-pipe-end.js index 04f308e76d8cc5..d4ccba8d55b036 100644 --- a/test/parallel/test-http-client-pipe-end.js +++ b/test/parallel/test-http-client-pipe-end.js @@ -4,7 +4,7 @@ const common = require('../common'); const http = require('http'); -var server = http.createServer(function(req, res) { +const server = http.createServer(function(req, res) { req.resume(); req.once('end', function() { res.writeHead(200); @@ -16,7 +16,7 @@ var server = http.createServer(function(req, res) { common.refreshTmpDir(); server.listen(common.PIPE, function() { - var req = http.request({ + const req = http.request({ socketPath: common.PIPE, headers: {'Content-Length': '1'}, method: 'POST', diff --git a/test/parallel/test-http-client-race-2.js b/test/parallel/test-http-client-race-2.js index 80a8252528fb0b..d9e89b85eca1ed 100644 --- a/test/parallel/test-http-client-race-2.js +++ b/test/parallel/test-http-client-race-2.js @@ -9,14 +9,14 @@ const url = require('url'); // condition involving the parsers FreeList used internally by http.Client. // -var body1_s = '1111111111111111'; -var body2_s = '22222'; -var body3_s = '3333333333333333333'; +const body1_s = '1111111111111111'; +const body2_s = '22222'; +const body3_s = '3333333333333333333'; -var server = http.createServer(function(req, res) { - var pathname = url.parse(req.url).pathname; +const server = http.createServer(function(req, res) { + const pathname = url.parse(req.url).pathname; - var body; + let body; switch (pathname) { case '/1': body = body1_s; break; case '/2': body = body2_s; break; @@ -29,15 +29,15 @@ var server = http.createServer(function(req, res) { }); server.listen(0); -var body1 = ''; -var body2 = ''; -var body3 = ''; +let body1 = ''; +let body2 = ''; +let body3 = ''; server.on('listening', function() { // // Client #1 is assigned Parser #1 // - var req1 = http.get({ port: this.address().port, path: '/1' }); + const req1 = http.get({ port: this.address().port, path: '/1' }); req1.on('response', function(res1) { res1.setEncoding('utf8'); @@ -59,7 +59,7 @@ server.on('listening', function() { // At this point, the bug would manifest itself and crash because the // internal state of the parser was no longer valid for use by Client #1 // - var req2 = http.get({ port: server.address().port, path: '/2' }); + const req2 = http.get({ port: server.address().port, path: '/2' }); req2.on('response', function(res2) { res2.setEncoding('utf8'); res2.on('data', function(chunk) { body2 += chunk; }); @@ -69,7 +69,7 @@ server.on('listening', function() { // Just to be really sure we've covered all our bases, execute a // request using client2. // - var req3 = http.get({ port: server.address().port, path: '/3' }); + const req3 = http.get({ port: server.address().port, path: '/3' }); req3.on('response', function(res3) { res3.setEncoding('utf8'); res3.on('data', function(chunk) { body3 += chunk; }); diff --git a/test/parallel/test-http-client-race.js b/test/parallel/test-http-client-race.js index af8e18686b83d7..14e3300f20a436 100644 --- a/test/parallel/test-http-client-race.js +++ b/test/parallel/test-http-client-race.js @@ -4,22 +4,22 @@ const assert = require('assert'); const http = require('http'); const url = require('url'); -var body1_s = '1111111111111111'; -var body2_s = '22222'; +const body1_s = '1111111111111111'; +const body2_s = '22222'; -var server = http.createServer(function(req, res) { - var body = url.parse(req.url).pathname === '/1' ? body1_s : body2_s; +const server = http.createServer(function(req, res) { + const body = url.parse(req.url).pathname === '/1' ? body1_s : body2_s; res.writeHead(200, {'Content-Type': 'text/plain', 'Content-Length': body.length}); res.end(body); }); server.listen(0); -var body1 = ''; -var body2 = ''; +let body1 = ''; +let body2 = ''; server.on('listening', function() { - var req1 = http.request({ port: this.address().port, path: '/1' }); + const req1 = http.request({ port: this.address().port, path: '/1' }); req1.end(); req1.on('response', function(res1) { res1.setEncoding('utf8'); @@ -29,7 +29,7 @@ server.on('listening', function() { }); res1.on('end', function() { - var req2 = http.request({ port: server.address().port, path: '/2' }); + const req2 = http.request({ port: server.address().port, path: '/2' }); req2.end(); req2.on('response', function(res2) { res2.setEncoding('utf8'); diff --git a/test/parallel/test-http-client-read-in-error.js b/test/parallel/test-http-client-read-in-error.js index 96085ae51f22b6..69b24f73771d41 100644 --- a/test/parallel/test-http-client-read-in-error.js +++ b/test/parallel/test-http-client-read-in-error.js @@ -10,8 +10,8 @@ function Agent() { util.inherits(Agent, http.Agent); Agent.prototype.createConnection = function() { - var self = this; - var socket = new net.Socket(); + const self = this; + const socket = new net.Socket(); socket.on('error', function() { socket.push('HTTP/1.1 200\r\n\r\n'); @@ -35,7 +35,7 @@ Agent.prototype.breakSocket = function breakSocket(socket) { socket.emit('error', new Error('Intentional error')); }; -var agent = new Agent(); +const agent = new Agent(); http.request({ agent: agent diff --git a/test/parallel/test-http-client-readable.js b/test/parallel/test-http-client-readable.js index e49181cedf63d6..bc6421692b305b 100644 --- a/test/parallel/test-http-client-readable.js +++ b/test/parallel/test-http-client-readable.js @@ -13,7 +13,7 @@ util.inherits(FakeAgent, http.Agent); FakeAgent.prototype.createConnection = function() { const s = new Duplex(); - var once = false; + let once = false; s._read = function() { if (once) @@ -38,7 +38,7 @@ FakeAgent.prototype.createConnection = function() { return s; }; -var received = ''; +let received = ''; const req = http.request({ agent: new FakeAgent() diff --git a/test/parallel/test-http-client-response-domain.js b/test/parallel/test-http-client-response-domain.js index 5355a301e8031d..eb8b226acef169 100644 --- a/test/parallel/test-http-client-response-domain.js +++ b/test/parallel/test-http-client-response-domain.js @@ -4,12 +4,12 @@ const assert = require('assert'); const http = require('http'); const domain = require('domain'); -var d; +let d; common.refreshTmpDir(); // first fire up a simple HTTP server -var server = http.createServer(function(req, res) { +const server = http.createServer(function(req, res) { res.writeHead(200); res.end(); server.close(); @@ -26,7 +26,7 @@ function test() { assert.equal('should be caught by domain', err.message); })); - var req = http.get({ + const req = http.get({ socketPath: common.PIPE, headers: {'Content-Length': '1'}, method: 'POST', diff --git a/test/parallel/test-http-client-timeout-agent.js b/test/parallel/test-http-client-timeout-agent.js index 84db25f7b023c3..16a18342468f94 100644 --- a/test/parallel/test-http-client-timeout-agent.js +++ b/test/parallel/test-http-client-timeout-agent.js @@ -3,9 +3,9 @@ require('../common'); const assert = require('assert'); const http = require('http'); -var requests_sent = 0; -var requests_done = 0; -var options = { +let requests_sent = 0; +let requests_done = 0; +const options = { method: 'GET', port: undefined, host: '127.0.0.1', @@ -13,7 +13,7 @@ var options = { //http.globalAgent.maxSockets = 15; -var server = http.createServer(function(req, res) { +const server = http.createServer(function(req, res) { const m = /\/(.*)/.exec(req.url); const reqid = parseInt(m[1], 10); if (reqid % 2) { @@ -27,7 +27,7 @@ var server = http.createServer(function(req, res) { server.listen(0, options.host, function() { options.port = this.address().port; - var req; + let req; for (requests_sent = 0; requests_sent < 30; requests_sent += 1) { options.path = '/' + requests_sent; diff --git a/test/parallel/test-http-client-timeout-option.js b/test/parallel/test-http-client-timeout-option.js index 79aa6ba46b6579..6741fbe0bd1e35 100644 --- a/test/parallel/test-http-client-timeout-option.js +++ b/test/parallel/test-http-client-timeout-option.js @@ -3,7 +3,7 @@ const common = require('../common'); const assert = require('assert'); const http = require('http'); -var options = { +const options = { method: 'GET', port: undefined, host: '127.0.0.1', @@ -11,17 +11,17 @@ var options = { timeout: 1 }; -var server = http.createServer(); +const server = http.createServer(); server.listen(0, options.host, function() { options.port = this.address().port; - var req = http.request(options); + const req = http.request(options); req.on('error', function() { // this space is intentionally left blank }); req.on('close', common.mustCall(() => server.close())); - var timeout_events = 0; + let timeout_events = 0; req.on('timeout', common.mustCall(() => timeout_events += 1)); setTimeout(function() { req.destroy(); diff --git a/test/parallel/test-http-client-timeout-with-data.js b/test/parallel/test-http-client-timeout-with-data.js index c82327beb295da..a21a2181752701 100644 --- a/test/parallel/test-http-client-timeout-with-data.js +++ b/test/parallel/test-http-client-timeout-with-data.js @@ -3,7 +3,7 @@ const common = require('../common'); const assert = require('assert'); const http = require('http'); -var nchunks = 0; +let nchunks = 0; const options = { method: 'GET', diff --git a/test/parallel/test-http-client-timeout.js b/test/parallel/test-http-client-timeout.js index e26c93fe0026a8..0caae0d04c333c 100644 --- a/test/parallel/test-http-client-timeout.js +++ b/test/parallel/test-http-client-timeout.js @@ -3,20 +3,20 @@ require('../common'); const assert = require('assert'); const http = require('http'); -var options = { +const options = { method: 'GET', port: undefined, host: '127.0.0.1', path: '/' }; -var server = http.createServer(function(req, res) { +const server = http.createServer(function(req, res) { // this space intentionally left blank }); server.listen(0, options.host, function() { options.port = this.address().port; - var req = http.request(options, function(res) { + const req = http.request(options, function(res) { // this space intentionally left blank }); req.on('close', function() { @@ -25,7 +25,7 @@ server.listen(0, options.host, function() { function destroy() { req.destroy(); } - var s = req.setTimeout(1, destroy); + const s = req.setTimeout(1, destroy); assert.ok(s instanceof http.ClientRequest); req.on('error', destroy); req.end(); diff --git a/test/parallel/test-http-client-upload-buf.js b/test/parallel/test-http-client-upload-buf.js index e17a2c5ee5698b..338aab9cc59ba0 100644 --- a/test/parallel/test-http-client-upload-buf.js +++ b/test/parallel/test-http-client-upload-buf.js @@ -3,12 +3,12 @@ const common = require('../common'); const assert = require('assert'); const http = require('http'); -var N = 1024; +const N = 1024; -var server = http.createServer(common.mustCall(function(req, res) { +const server = http.createServer(common.mustCall(function(req, res) { assert.equal('POST', req.method); - var bytesReceived = 0; + let bytesReceived = 0; req.on('data', function(chunk) { bytesReceived += chunk.length; @@ -25,7 +25,7 @@ var server = http.createServer(common.mustCall(function(req, res) { server.listen(0); server.on('listening', common.mustCall(function() { - var req = http.request({ + const req = http.request({ port: this.address().port, method: 'POST', path: '/' diff --git a/test/parallel/test-http-client-upload.js b/test/parallel/test-http-client-upload.js index ce2608fcfde0f3..ba60681776ba49 100644 --- a/test/parallel/test-http-client-upload.js +++ b/test/parallel/test-http-client-upload.js @@ -3,11 +3,11 @@ const common = require('../common'); const assert = require('assert'); const http = require('http'); -var server = http.createServer(common.mustCall(function(req, res) { +const server = http.createServer(common.mustCall(function(req, res) { assert.equal('POST', req.method); req.setEncoding('utf8'); - var sent_body = ''; + let sent_body = ''; req.on('data', function(chunk) { console.log('server got: ' + JSON.stringify(chunk)); @@ -25,7 +25,7 @@ var server = http.createServer(common.mustCall(function(req, res) { server.listen(0); server.on('listening', common.mustCall(function() { - var req = http.request({ + const req = http.request({ port: this.address().port, method: 'POST', path: '/' diff --git a/test/parallel/test-http-conn-reset.js b/test/parallel/test-http-conn-reset.js index f244838bc47013..f7f08a6bf42c81 100644 --- a/test/parallel/test-http-conn-reset.js +++ b/test/parallel/test-http-conn-reset.js @@ -4,13 +4,13 @@ const assert = require('assert'); const http = require('http'); const net = require('net'); -var options = { +const options = { host: '127.0.0.1', port: undefined }; // start a tcp server that closes incoming connections immediately -var server = net.createServer(function(client) { +const server = net.createServer(function(client) { client.destroy(); server.close(); }); @@ -19,7 +19,7 @@ server.listen(0, options.host, common.mustCall(onListen)); // do a GET request, expect it to fail function onListen() { options.port = this.address().port; - var req = http.request(options, function(res) { + const req = http.request(options, function(res) { assert.ok(false, 'this should never run'); }); req.on('error', common.mustCall(function(err) { diff --git a/test/parallel/test-http-connect-req-res.js b/test/parallel/test-http-connect-req-res.js index 1cee61e4c2fb37..0b1ca4630a562e 100644 --- a/test/parallel/test-http-connect-req-res.js +++ b/test/parallel/test-http-connect-req-res.js @@ -18,7 +18,7 @@ server.on('connect', common.mustCall(function(req, socket, firstBodyChunk) { 'Head' ); - var data = firstBodyChunk.toString(); + let data = firstBodyChunk.toString(); socket.on('data', function(buf) { data += buf.toString(); }); @@ -49,7 +49,7 @@ server.listen(0, common.mustCall(function() { assert.equal(socket.listeners('connect').length, 0); assert.equal(socket.listeners('data').length, 0); - var data = firstBodyChunk.toString(); + let data = firstBodyChunk.toString(); // test that the firstBodyChunk was not parsed as HTTP assert.equal(data, 'Head'); diff --git a/test/parallel/test-http-content-length.js b/test/parallel/test-http-content-length.js index fd1c8004ffef2d..3d6882d92f04b3 100644 --- a/test/parallel/test-http-content-length.js +++ b/test/parallel/test-http-content-length.js @@ -3,25 +3,25 @@ require('../common'); const assert = require('assert'); const http = require('http'); -var expectedHeadersMultipleWrites = { +const expectedHeadersMultipleWrites = { 'connection': 'close', 'transfer-encoding': 'chunked', }; -var expectedHeadersEndWithData = { +const expectedHeadersEndWithData = { 'connection': 'close', 'content-length': String('hello world'.length) }; -var expectedHeadersEndNoData = { +const expectedHeadersEndNoData = { 'connection': 'close', 'content-length': '0', }; -var receivedRequests = 0; -var totalRequests = 3; +let receivedRequests = 0; +const totalRequests = 3; -var server = http.createServer(function(req, res) { +const server = http.createServer(function(req, res) { res.removeHeader('Date'); switch (req.url.substr(1)) { @@ -47,7 +47,7 @@ var server = http.createServer(function(req, res) { }); server.listen(0, function() { - var req; + let req; req = http.request({ port: this.address().port, diff --git a/test/parallel/test-http-contentLength0.js b/test/parallel/test-http-contentLength0.js index c4c8699df7fc47..46eec45ed2757f 100644 --- a/test/parallel/test-http-contentLength0.js +++ b/test/parallel/test-http-contentLength0.js @@ -7,13 +7,13 @@ const http = require('http'); // I.E. a space character after the 'Content-Length' throws an `error` event. -var s = http.createServer(function(req, res) { +const s = http.createServer(function(req, res) { res.writeHead(200, {'Content-Length': '0 '}); res.end(); }); s.listen(0, function() { - var request = http.request({ port: this.address().port }, function(response) { + const request = http.request({ port: this.address().port }, (response) => { console.log('STATUS: ' + response.statusCode); s.close(); response.resume(); diff --git a/test/parallel/test-http-date-header.js b/test/parallel/test-http-date-header.js index 5b9df4c1747bb0..e14a92b310f2d1 100644 --- a/test/parallel/test-http-date-header.js +++ b/test/parallel/test-http-date-header.js @@ -3,9 +3,9 @@ require('../common'); const assert = require('assert'); const http = require('http'); -var testResBody = 'other stuff!\n'; +const testResBody = 'other stuff!\n'; -var server = http.createServer(function(req, res) { +const server = http.createServer(function(req, res) { assert.ok(!('date' in req.headers), 'Request headers contained a Date.'); res.writeHead(200, { @@ -17,12 +17,12 @@ server.listen(0); server.addListener('listening', function() { - var options = { + const options = { port: this.address().port, path: '/', method: 'GET' }; - var req = http.request(options, function(res) { + const req = http.request(options, function(res) { assert.ok('date' in res.headers, 'Response headers didn\'t contain a Date.'); res.addListener('end', function() { diff --git a/test/parallel/test-http-default-encoding.js b/test/parallel/test-http-default-encoding.js index 0026540373c0aa..46327085184069 100644 --- a/test/parallel/test-http-default-encoding.js +++ b/test/parallel/test-http-default-encoding.js @@ -3,10 +3,10 @@ require('../common'); const assert = require('assert'); const http = require('http'); -var expected = 'This is a unicode text: سلام'; -var result = ''; +const expected = 'This is a unicode text: سلام'; +let result = ''; -var server = http.Server(function(req, res) { +const server = http.Server(function(req, res) { req.setEncoding('utf8'); req.on('data', function(chunk) { result += chunk; diff --git a/test/parallel/test-http-destroyed-socket-write2.js b/test/parallel/test-http-destroyed-socket-write2.js index bb3f5d64cbca8b..01023a088576ef 100644 --- a/test/parallel/test-http-destroyed-socket-write2.js +++ b/test/parallel/test-http-destroyed-socket-write2.js @@ -6,14 +6,14 @@ const assert = require('assert'); // where the server has ended the socket. const http = require('http'); -var server = http.createServer(function(req, res) { +const server = http.createServer(function(req, res) { setImmediate(function() { res.destroy(); }); }); server.listen(0, function() { - var req = http.request({ + const req = http.request({ port: this.address().port, path: '/', method: 'POST' diff --git a/test/parallel/test-http-eof-on-connect.js b/test/parallel/test-http-eof-on-connect.js index 765d8b35e7cfd3..f67e45ed403225 100644 --- a/test/parallel/test-http-eof-on-connect.js +++ b/test/parallel/test-http-eof-on-connect.js @@ -7,7 +7,7 @@ const http = require('http'); // It is separate from test-http-malformed-request.js because it is only // reproduceable on the first packet on the first connection to a server. -var server = http.createServer(function(req, res) {}); +const server = http.createServer(function(req, res) {}); server.listen(0); server.on('listening', function() { diff --git a/test/parallel/test-http-exceptions.js b/test/parallel/test-http-exceptions.js index 8ee46316e98b23..c003db131065a3 100644 --- a/test/parallel/test-http-exceptions.js +++ b/test/parallel/test-http-exceptions.js @@ -2,7 +2,7 @@ require('../common'); const http = require('http'); -var server = http.createServer(function(req, res) { +const server = http.createServer(function(req, res) { intentionally_not_defined(); // eslint-disable-line no-undef res.writeHead(200, {'Content-Type': 'text/plain'}); res.write('Thank you, come again.'); @@ -10,12 +10,12 @@ var server = http.createServer(function(req, res) { }); server.listen(0, function() { - for (var i = 0; i < 4; i += 1) { + for (let i = 0; i < 4; i += 1) { http.get({ port: this.address().port, path: '/busy/' + i }); } }); -var exception_count = 0; +let exception_count = 0; process.on('uncaughtException', function(err) { console.log('Caught an exception: ' + err); diff --git a/test/parallel/test-http-expect-continue.js b/test/parallel/test-http-expect-continue.js index 954d6b6211c27e..0cf90e3b115e60 100644 --- a/test/parallel/test-http-expect-continue.js +++ b/test/parallel/test-http-expect-continue.js @@ -3,11 +3,11 @@ require('../common'); const assert = require('assert'); const http = require('http'); -var outstanding_reqs = 0; -var test_req_body = 'some stuff...\n'; -var test_res_body = 'other stuff!\n'; -var sent_continue = false; -var got_continue = false; +let outstanding_reqs = 0; +const test_req_body = 'some stuff...\n'; +const test_res_body = 'other stuff!\n'; +let sent_continue = false; +let got_continue = false; function handler(req, res) { assert.equal(sent_continue, true, 'Full response sent before 100 Continue'); @@ -19,7 +19,7 @@ function handler(req, res) { res.end(test_res_body); } -var server = http.createServer(handler); +const server = http.createServer(handler); server.on('checkContinue', function(req, res) { console.error('Server got Expect: 100-continue...'); res.writeContinue(); @@ -32,7 +32,7 @@ server.listen(0); server.on('listening', function() { - var req = http.request({ + const req = http.request({ port: this.address().port, method: 'POST', path: '/world', @@ -40,7 +40,7 @@ server.on('listening', function() { }); console.error('Client sending request...'); outstanding_reqs++; - var body = ''; + let body = ''; req.on('continue', function() { console.error('Client got 100 Continue...'); got_continue = true; diff --git a/test/parallel/test-http-extra-response.js b/test/parallel/test-http-extra-response.js index 1866d88a33cbd5..6ebecaad1300de 100644 --- a/test/parallel/test-http-extra-response.js +++ b/test/parallel/test-http-extra-response.js @@ -8,8 +8,8 @@ const net = require('net'); // node should ignore it and drop the connection. // Demos this bug: https://github.com/joyent/node/issues/680 -var body = 'hello world\r\n'; -var fullResponse = +const body = 'hello world\r\n'; +const fullResponse = 'HTTP/1.1 500 Internal Server Error\r\n' + 'Content-Length: ' + body.length + '\r\n' + 'Content-Type: text/plain\r\n' + @@ -20,8 +20,8 @@ var fullResponse = '\r\n' + body; -var server = net.createServer(function(socket) { - var postBody = ''; +const server = net.createServer(function(socket) { + let postBody = ''; socket.setEncoding('utf8'); @@ -43,7 +43,7 @@ var server = net.createServer(function(socket) { server.listen(0, common.mustCall(function() { http.get({ port: this.address().port }, common.mustCall(function(res) { - var buffer = ''; + let buffer = ''; console.log('Got res code: ' + res.statusCode); res.setEncoding('utf8'); diff --git a/test/parallel/test-http-flush-response-headers.js b/test/parallel/test-http-flush-response-headers.js index 1cd8402df361b0..ea7d2d97b4dc7a 100644 --- a/test/parallel/test-http-flush-response-headers.js +++ b/test/parallel/test-http-flush-response-headers.js @@ -11,7 +11,7 @@ server.on('request', function(req, res) { res.flushHeaders(); // Should be idempotent. }); server.listen(0, common.localhostIPv4, function() { - var req = http.request({ + const req = http.request({ method: 'GET', host: common.localhostIPv4, port: this.address().port, diff --git a/test/parallel/test-http-flush.js b/test/parallel/test-http-flush.js index 524965d2d7af5f..e8f5782c2f7857 100644 --- a/test/parallel/test-http-flush.js +++ b/test/parallel/test-http-flush.js @@ -6,7 +6,7 @@ http.createServer(function(req, res) { res.end('ok'); this.close(); }).listen(0, '127.0.0.1', function() { - var req = http.request({ + const req = http.request({ method: 'POST', host: '127.0.0.1', port: this.address().port, diff --git a/test/parallel/test-http-full-response.js b/test/parallel/test-http-full-response.js index be6749cc042f0d..c834c6e6545320 100644 --- a/test/parallel/test-http-full-response.js +++ b/test/parallel/test-http-full-response.js @@ -5,11 +5,11 @@ const assert = require('assert'); const http = require('http'); const exec = require('child_process').exec; -var bodyLength = 12345; +const bodyLength = 12345; -var body = 'c'.repeat(bodyLength); +const body = 'c'.repeat(bodyLength); -var server = http.createServer(function(req, res) { +const server = http.createServer(function(req, res) { res.writeHead(200, { 'Content-Length': bodyLength, 'Content-Type': 'text/plain' @@ -18,7 +18,7 @@ var server = http.createServer(function(req, res) { }); function runAb(opts, callback) { - var command = `ab ${opts} http://127.0.0.1:${server.address().port}/`; + const command = `ab ${opts} http://127.0.0.1:${server.address().port}/`; exec(command, function(err, stdout, stderr) { if (err) { if (/ab|apr/mi.test(stderr)) { @@ -29,14 +29,14 @@ function runAb(opts, callback) { return; } - var m = /Document Length:\s*(\d+) bytes/mi.exec(stdout); - var documentLength = parseInt(m[1]); + let m = /Document Length:\s*(\d+) bytes/mi.exec(stdout); + const documentLength = parseInt(m[1]); m = /Complete requests:\s*(\d+)/mi.exec(stdout); - var completeRequests = parseInt(m[1]); + const completeRequests = parseInt(m[1]); m = /HTML transferred:\s*(\d+) bytes/mi.exec(stdout); - var htmlTransfered = parseInt(m[1]); + const htmlTransfered = parseInt(m[1]); assert.equal(bodyLength, documentLength); assert.equal(completeRequests * documentLength, htmlTransfered); diff --git a/test/parallel/test-http-get-pipeline-problem.js b/test/parallel/test-http-get-pipeline-problem.js index d4e075d229184f..15c96a9a4e12ea 100644 --- a/test/parallel/test-http-get-pipeline-problem.js +++ b/test/parallel/test-http-get-pipeline-problem.js @@ -11,14 +11,14 @@ http.globalAgent.maxSockets = 1; common.refreshTmpDir(); -var image = fs.readFileSync(common.fixturesDir + '/person.jpg'); +const image = fs.readFileSync(common.fixturesDir + '/person.jpg'); console.log('image.length = ' + image.length); -var total = 10; -var requests = 0, responses = 0; +const total = 10; +let requests = 0, responses = 0; -var server = http.Server(function(req, res) { +const server = http.Server(function(req, res) { if (++requests === total) { server.close(); } @@ -35,18 +35,18 @@ var server = http.Server(function(req, res) { server.listen(0, function() { - for (var i = 0; i < total; i++) { + for (let i = 0; i < total; i++) { (function() { - var x = i; + const x = i; - var opts = { + const opts = { port: server.address().port, headers: { connection: 'close' } }; http.get(opts, function(res) { console.error('recv ' + x); - var s = fs.createWriteStream(common.tmpDir + '/' + x + '.jpg'); + const s = fs.createWriteStream(common.tmpDir + '/' + x + '.jpg'); res.pipe(s); s.on('finish', function() { @@ -64,16 +64,16 @@ server.listen(0, function() { }); -var checkedFiles = false; +let checkedFiles = false; function checkFiles() { // Should see 1.jpg, 2.jpg, ..., 100.jpg in tmpDir - var files = fs.readdirSync(common.tmpDir); + const files = fs.readdirSync(common.tmpDir); assert(total <= files.length); - for (var i = 0; i < total; i++) { - var fn = i + '.jpg'; + for (let i = 0; i < total; i++) { + const fn = i + '.jpg'; assert.ok(files.indexOf(fn) >= 0, "couldn't find '" + fn + "'"); - var stat = fs.statSync(common.tmpDir + '/' + fn); + const stat = fs.statSync(common.tmpDir + '/' + fn); assert.equal(image.length, stat.size, "size doesn't match on '" + fn + "'. Got " + stat.size + ' bytes'); diff --git a/test/parallel/test-http-head-request.js b/test/parallel/test-http-head-request.js index eb31930a343c4d..de94dfb8b7d6e7 100644 --- a/test/parallel/test-http-head-request.js +++ b/test/parallel/test-http-head-request.js @@ -2,10 +2,10 @@ const common = require('../common'); const http = require('http'); -var body = 'hello world\n'; +const body = 'hello world\n'; function test(headers) { - var server = http.createServer(function(req, res) { + const server = http.createServer(function(req, res) { console.error('req: %s headers: %j', req.method, headers); res.writeHead(200, headers); res.end(); @@ -13,7 +13,7 @@ function test(headers) { }); server.listen(0, common.mustCall(function() { - var request = http.request({ + const request = http.request({ port: this.address().port, method: 'HEAD', path: '/' diff --git a/test/parallel/test-http-head-response-has-no-body-end.js b/test/parallel/test-http-head-response-has-no-body-end.js index cd2c22c8fa1926..de5ca976fc47b0 100644 --- a/test/parallel/test-http-head-response-has-no-body-end.js +++ b/test/parallel/test-http-head-response-has-no-body-end.js @@ -6,14 +6,14 @@ const http = require('http'); // responds to a HEAD request with data to res.end, // it does not send any body. -var server = http.createServer(function(req, res) { +const server = http.createServer(function(req, res) { res.writeHead(200); res.end('FAIL'); // broken: sends FAIL from hot path. }); server.listen(0); server.on('listening', common.mustCall(function() { - var req = http.request({ + const req = http.request({ port: this.address().port, method: 'HEAD', path: '/' diff --git a/test/parallel/test-http-head-response-has-no-body.js b/test/parallel/test-http-head-response-has-no-body.js index 17107d3b6743a5..b2eb98b1eea06c 100644 --- a/test/parallel/test-http-head-response-has-no-body.js +++ b/test/parallel/test-http-head-response-has-no-body.js @@ -6,14 +6,14 @@ const http = require('http'); // responds to a HEAD request, it does not send any body. // In this case it was sending '0\r\n\r\n' -var server = http.createServer(function(req, res) { +const server = http.createServer(function(req, res) { res.writeHead(200); // broken: defaults to TE chunked res.end(); }); server.listen(0); server.on('listening', common.mustCall(function() { - var req = http.request({ + const req = http.request({ port: this.address().port, method: 'HEAD', path: '/' diff --git a/test/parallel/test-http-header-read.js b/test/parallel/test-http-header-read.js index 42d7e9af5f8566..3d9e756d505238 100644 --- a/test/parallel/test-http-header-read.js +++ b/test/parallel/test-http-header-read.js @@ -6,9 +6,9 @@ const http = require('http'); // Verify that ServerResponse.getHeader() works correctly even after // the response header has been sent. Issue 752 on github. -var s = http.createServer(function(req, res) { - var contentType = 'Content-Type'; - var plain = 'text/plain'; +const s = http.createServer(function(req, res) { + const contentType = 'Content-Type'; + const plain = 'text/plain'; res.setHeader(contentType, plain); assert.ok(!res.headersSent); res.writeHead(200); diff --git a/test/parallel/test-http-hex-write.js b/test/parallel/test-http-hex-write.js index 2fcabb0691ec22..211f818e566699 100644 --- a/test/parallel/test-http-hex-write.js +++ b/test/parallel/test-http-hex-write.js @@ -4,7 +4,7 @@ const assert = require('assert'); const http = require('http'); -var expect = 'hex\nutf8\n'; +const expect = 'hex\nutf8\n'; http.createServer(function(q, s) { s.setHeader('content-length', expect.length); @@ -15,7 +15,7 @@ http.createServer(function(q, s) { }).listen(0, common.mustCall(function() { http.request({ port: this.address().port }) .on('response', common.mustCall(function(res) { - var data = ''; + let data = ''; res.setEncoding('ascii'); res.on('data', function(c) { diff --git a/test/parallel/test-http-host-header-ipv6-fail.js b/test/parallel/test-http-host-header-ipv6-fail.js index 5f81234edba352..94351bc5c167e4 100644 --- a/test/parallel/test-http-host-header-ipv6-fail.js +++ b/test/parallel/test-http-host-header-ipv6-fail.js @@ -16,7 +16,7 @@ const http = require('http'); const hostname = '::1'; function httpreq() { - var req = http.request({ + const req = http.request({ host: hostname, port: server.address().port, path: '/', diff --git a/test/parallel/test-http-host-headers.js b/test/parallel/test-http-host-headers.js index 0adf5716b7e776..0f6233190ce875 100644 --- a/test/parallel/test-http-host-headers.js +++ b/test/parallel/test-http-host-headers.js @@ -26,7 +26,7 @@ testHttp(); function testHttp() { - var counter = 0; + let counter = 0; function cb(res) { counter--; diff --git a/test/parallel/test-http-invalidheaderfield.js b/test/parallel/test-http-invalidheaderfield.js index 9d4a12a952a838..aaed46c69cd592 100644 --- a/test/parallel/test-http-invalidheaderfield.js +++ b/test/parallel/test-http-invalidheaderfield.js @@ -5,7 +5,7 @@ const EventEmitter = require('events'); const http = require('http'); const ee = new EventEmitter(); -var count = 3; +let count = 3; const server = http.createServer(function(req, res) { assert.doesNotThrow(function() { @@ -24,7 +24,7 @@ server.listen(0, function() { assert.throws( function() { - var options = { + const options = { port: server.address().port, headers: {'testing 123': 123} }; @@ -38,7 +38,7 @@ server.listen(0, function() { assert.doesNotThrow( function() { - var options = { + const options = { port: server.address().port, headers: {'testing_123': 123} }; diff --git a/test/parallel/test-http-keep-alive-close-on-header.js b/test/parallel/test-http-keep-alive-close-on-header.js index b69e90c03809f2..15d5d62d429658 100644 --- a/test/parallel/test-http-keep-alive-close-on-header.js +++ b/test/parallel/test-http-keep-alive-close-on-header.js @@ -3,22 +3,22 @@ require('../common'); const assert = require('assert'); const http = require('http'); -var body = 'hello world\n'; -var headers = {'connection': 'keep-alive'}; +const body = 'hello world\n'; +const headers = {'connection': 'keep-alive'}; -var server = http.createServer(function(req, res) { +const server = http.createServer(function(req, res) { res.writeHead(200, {'Content-Length': body.length, 'Connection': 'close'}); res.write(body); res.end(); }); -var connectCount = 0; +let connectCount = 0; server.listen(0, function() { - var agent = new http.Agent({ maxSockets: 1 }); - var name = agent.getName({ port: this.address().port }); - var request = http.request({ + const agent = new http.Agent({ maxSockets: 1 }); + const name = agent.getName({ port: this.address().port }); + let request = http.request({ method: 'GET', path: '/', headers: headers, diff --git a/test/parallel/test-http-keepalive-client.js b/test/parallel/test-http-keepalive-client.js index 55c3342a115f90..c9cf7bba96a7db 100644 --- a/test/parallel/test-http-keepalive-client.js +++ b/test/parallel/test-http-keepalive-client.js @@ -5,8 +5,8 @@ const assert = require('assert'); const http = require('http'); -var serverSocket = null; -var server = http.createServer(function(req, res) { +let serverSocket = null; +const server = http.createServer(function(req, res) { // They should all come in on the same server socket. if (serverSocket) { assert.equal(req.socket, serverSocket); @@ -20,12 +20,12 @@ server.listen(0, function() { makeRequest(expectRequests); }); -var agent = http.Agent({ keepAlive: true }); +const agent = http.Agent({ keepAlive: true }); -var clientSocket = null; -var expectRequests = 10; -var actualRequests = 0; +let clientSocket = null; +const expectRequests = 10; +let actualRequests = 0; function makeRequest(n) { @@ -35,7 +35,7 @@ function makeRequest(n) { return; } - var req = http.request({ + const req = http.request({ port: server.address().port, agent: agent, path: '/' + n @@ -52,7 +52,7 @@ function makeRequest(n) { }); req.on('response', function(res) { - var data = ''; + let data = ''; res.setEncoding('utf8'); res.on('data', function(c) { data += c; diff --git a/test/parallel/test-http-keepalive-maxsockets.js b/test/parallel/test-http-keepalive-maxsockets.js index ffe1472a3cba85..14e9e88ef7fd09 100644 --- a/test/parallel/test-http-keepalive-maxsockets.js +++ b/test/parallel/test-http-keepalive-maxsockets.js @@ -5,21 +5,21 @@ const assert = require('assert'); const http = require('http'); -var serverSockets = []; -var server = http.createServer(function(req, res) { +const serverSockets = []; +const server = http.createServer(function(req, res) { if (serverSockets.indexOf(req.socket) === -1) { serverSockets.push(req.socket); } res.end(req.url); }); server.listen(0, function() { - var agent = http.Agent({ + const agent = http.Agent({ keepAlive: true, maxSockets: 5, maxFreeSockets: 2 }); - var closed = false; + let closed = false; makeReqs(10, function(er) { assert.ifError(er); assert.equal(count(agent.freeSockets), 2); @@ -49,7 +49,7 @@ server.listen(0, function() { // make 10 requests in parallel, // then 10 more when they all finish. function makeReqs(n, cb) { - for (var i = 0; i < n; i++) + for (let i = 0; i < n; i++) makeReq(i, then); function then(er) { @@ -66,7 +66,7 @@ server.listen(0, function() { path: '/' + i, agent: agent }, function(res) { - var data = ''; + let data = ''; res.setEncoding('ascii'); res.on('data', function(c) { data += c; diff --git a/test/parallel/test-http-keepalive-request.js b/test/parallel/test-http-keepalive-request.js index 102f65bb08526f..dc9bdefb333d13 100644 --- a/test/parallel/test-http-keepalive-request.js +++ b/test/parallel/test-http-keepalive-request.js @@ -5,8 +5,8 @@ const assert = require('assert'); const http = require('http'); -var serverSocket = null; -var server = http.createServer(function(req, res) { +let serverSocket = null; +const server = http.createServer(function(req, res) { // They should all come in on the same server socket. if (serverSocket) { assert.equal(req.socket, serverSocket); @@ -20,12 +20,12 @@ server.listen(0, function() { makeRequest(expectRequests); }); -var agent = http.Agent({ keepAlive: true }); +const agent = http.Agent({ keepAlive: true }); -var clientSocket = null; -var expectRequests = 10; -var actualRequests = 0; +let clientSocket = null; +const expectRequests = 10; +let actualRequests = 0; function makeRequest(n) { @@ -35,7 +35,7 @@ function makeRequest(n) { return; } - var req = http.request({ + const req = http.request({ port: server.address().port, path: '/' + n, agent: agent @@ -52,7 +52,7 @@ function makeRequest(n) { }); req.on('response', function(res) { - var data = ''; + let data = ''; res.setEncoding('utf8'); res.on('data', function(c) { data += c; diff --git a/test/parallel/test-http-localaddress-bind-error.js b/test/parallel/test-http-localaddress-bind-error.js index 0290c6a584c959..a23c6f2a4452a6 100644 --- a/test/parallel/test-http-localaddress-bind-error.js +++ b/test/parallel/test-http-localaddress-bind-error.js @@ -2,9 +2,9 @@ const common = require('../common'); const http = require('http'); -var invalidLocalAddress = '1.2.3.4'; +const invalidLocalAddress = '1.2.3.4'; -var server = http.createServer(function(req, res) { +const server = http.createServer(function(req, res) { console.log('Connect from: ' + req.connection.remoteAddress); req.on('end', function() { diff --git a/test/parallel/test-http-localaddress.js b/test/parallel/test-http-localaddress.js index d507d12ec89e25..e8df6888866f9c 100644 --- a/test/parallel/test-http-localaddress.js +++ b/test/parallel/test-http-localaddress.js @@ -8,7 +8,7 @@ if (!common.hasMultiLocalhost()) { return; } -var server = http.createServer(function(req, res) { +const server = http.createServer(function(req, res) { console.log('Connect from: ' + req.connection.remoteAddress); assert.equal('127.0.0.2', req.connection.remoteAddress); @@ -20,13 +20,13 @@ var server = http.createServer(function(req, res) { }); server.listen(0, '127.0.0.1', function() { - var options = { host: 'localhost', - port: this.address().port, - path: '/', - method: 'GET', - localAddress: '127.0.0.2' }; + const options = { host: 'localhost', + port: this.address().port, + path: '/', + method: 'GET', + localAddress: '127.0.0.2' }; - var req = http.request(options, function(res) { + const req = http.request(options, function(res) { res.on('end', function() { server.close(); process.exit(); diff --git a/test/parallel/test-http-malformed-request.js b/test/parallel/test-http-malformed-request.js index 6739a44b6c82f9..a36c9fdbe29451 100644 --- a/test/parallel/test-http-malformed-request.js +++ b/test/parallel/test-http-malformed-request.js @@ -8,10 +8,10 @@ const url = require('url'); // Make sure no exceptions are thrown when receiving malformed HTTP // requests. -var nrequests_completed = 0; -var nrequests_expected = 1; +let nrequests_completed = 0; +const nrequests_expected = 1; -var server = http.createServer(function(req, res) { +const server = http.createServer(function(req, res) { console.log('req: ' + JSON.stringify(url.parse(req.url))); res.writeHead(200, {'Content-Type': 'text/plain'}); @@ -23,7 +23,7 @@ var server = http.createServer(function(req, res) { server.listen(0); server.on('listening', function() { - var c = net.createConnection(this.address().port); + const c = net.createConnection(this.address().port); c.on('connect', function() { c.write('GET /hello?foo=%99bar HTTP/1.1\r\n\r\n'); c.end(); diff --git a/test/parallel/test-http-many-ended-pipelines.js b/test/parallel/test-http-many-ended-pipelines.js index 5fa8e53e01d1d0..b4af99ef00a9d4 100644 --- a/test/parallel/test-http-many-ended-pipelines.js +++ b/test/parallel/test-http-many-ended-pipelines.js @@ -2,7 +2,7 @@ require('../common'); // no warnings should happen! -var trace = console.trace; +const trace = console.trace; console.trace = function() { trace.apply(console, arguments); throw new Error('no tracing should happen here'); @@ -11,10 +11,10 @@ console.trace = function() { const http = require('http'); const net = require('net'); -var numRequests = 20; -var first = false; +const numRequests = 20; +let first = false; -var server = http.createServer(function(req, res) { +const server = http.createServer(function(req, res) { if (!first) { first = true; req.socket.on('close', function() { @@ -28,8 +28,9 @@ var server = http.createServer(function(req, res) { }); server.listen(0, function() { - var client = net.connect({ port: this.address().port, allowHalfOpen: true }); - for (var i = 0; i < numRequests; i++) { + const client = net.connect({ port: this.address().port, + allowHalfOpen: true }); + for (let i = 0; i < numRequests; i++) { client.write('GET / HTTP/1.1\r\n' + 'Host: some.host.name\r\n' + '\r\n\r\n'); diff --git a/test/parallel/test-http-max-headers-count.js b/test/parallel/test-http-max-headers-count.js index 0abddbd2cbf5c4..018ed33c1b9e49 100644 --- a/test/parallel/test-http-max-headers-count.js +++ b/test/parallel/test-http-max-headers-count.js @@ -3,24 +3,24 @@ require('../common'); const assert = require('assert'); const http = require('http'); -var requests = 0; -var responses = 0; +let requests = 0; +let responses = 0; -var headers = {}; -var N = 2000; -for (var i = 0; i < N; ++i) { +const headers = {}; +const N = 2000; +for (let i = 0; i < N; ++i) { headers['key' + i] = i; } -var maxAndExpected = [ // for server +const maxAndExpected = [ // for server [50, 50], [1500, 1500], [0, N + 2] // Host and Connection ]; -var max = maxAndExpected[requests][0]; -var expected = maxAndExpected[requests][1]; +let max = maxAndExpected[requests][0]; +let expected = maxAndExpected[requests][1]; -var server = http.createServer(function(req, res) { +const server = http.createServer(function(req, res) { assert.equal(Object.keys(req.headers).length, expected); if (++requests < maxAndExpected.length) { max = maxAndExpected[requests][0]; @@ -33,7 +33,7 @@ var server = http.createServer(function(req, res) { server.maxHeadersCount = max; server.listen(0, function() { - var maxAndExpected = [ // for client + const maxAndExpected = [ // for client [20, 20], [1200, 1200], [0, N + 3] // Connection, Date and Transfer-Encoding @@ -41,9 +41,9 @@ server.listen(0, function() { doRequest(); function doRequest() { - var max = maxAndExpected[responses][0]; - var expected = maxAndExpected[responses][1]; - var req = http.request({ + const max = maxAndExpected[responses][0]; + const expected = maxAndExpected[responses][1]; + const req = http.request({ port: server.address().port, headers: headers }, function(res) { diff --git a/test/parallel/test-http-multi-line-headers.js b/test/parallel/test-http-multi-line-headers.js index 9c0d758ed571ad..2096f533a196d1 100644 --- a/test/parallel/test-http-multi-line-headers.js +++ b/test/parallel/test-http-multi-line-headers.js @@ -5,10 +5,10 @@ const assert = require('assert'); const http = require('http'); const net = require('net'); -var server = net.createServer(function(conn) { - var body = 'Yet another node.js server.'; +const server = net.createServer(function(conn) { + const body = 'Yet another node.js server.'; - var response = + const response = 'HTTP/1.1 200 OK\r\n' + 'Connection: close\r\n' + 'Content-Length: ' + body.length + '\r\n' + diff --git a/test/parallel/test-http-no-content-length.js b/test/parallel/test-http-no-content-length.js index a393d58d57413f..a6cfad13aa2b44 100644 --- a/test/parallel/test-http-no-content-length.js +++ b/test/parallel/test-http-no-content-length.js @@ -4,12 +4,12 @@ const assert = require('assert'); const net = require('net'); const http = require('http'); -var server = net.createServer(function(socket) { +const server = net.createServer(function(socket) { // Neither Content-Length nor Connection socket.end('HTTP/1.1 200 ok\r\n\r\nHello'); }).listen(0, common.mustCall(function() { http.get({port: this.address().port}, common.mustCall(function(res) { - var body = ''; + let body = ''; res.setEncoding('utf8'); res.on('data', function(chunk) { diff --git a/test/parallel/test-http-outgoing-finish.js b/test/parallel/test-http-outgoing-finish.js index 06630e61787e01..73654909d88e1b 100644 --- a/test/parallel/test-http-outgoing-finish.js +++ b/test/parallel/test-http-outgoing-finish.js @@ -11,7 +11,7 @@ http.createServer(function(req, res) { }); this.close(); }).listen(0, function() { - var req = http.request({ + const req = http.request({ port: this.address().port, method: 'PUT' }); @@ -21,11 +21,11 @@ http.createServer(function(req, res) { }); }); -var buf = Buffer.alloc(1024 * 16, 'x'); +const buf = Buffer.alloc(1024 * 16, 'x'); function write(out) { - var name = out.constructor.name; - var finishEvent = false; - var endCb = false; + const name = out.constructor.name; + let finishEvent = false; + let endCb = false; // first, write until it gets some backpressure while (out.write(buf)) {} diff --git a/test/parallel/test-http-parser-bad-ref.js b/test/parallel/test-http-parser-bad-ref.js index 9eddb2bb3bcd77..69682128fadbdf 100644 --- a/test/parallel/test-http-parser-bad-ref.js +++ b/test/parallel/test-http-parser-bad-ref.js @@ -6,15 +6,15 @@ require('../common'); const assert = require('assert'); -var HTTPParser = process.binding('http_parser').HTTPParser; +const HTTPParser = process.binding('http_parser').HTTPParser; -var kOnHeaders = HTTPParser.kOnHeaders | 0; -var kOnHeadersComplete = HTTPParser.kOnHeadersComplete | 0; -var kOnBody = HTTPParser.kOnBody | 0; -var kOnMessageComplete = HTTPParser.kOnMessageComplete | 0; +const kOnHeaders = HTTPParser.kOnHeaders | 0; +const kOnHeadersComplete = HTTPParser.kOnHeadersComplete | 0; +const kOnBody = HTTPParser.kOnBody | 0; +const kOnMessageComplete = HTTPParser.kOnMessageComplete | 0; -var headersComplete = 0; -var messagesComplete = 0; +let headersComplete = 0; +let messagesComplete = 0; function flushPool() { Buffer.allocUnsafe(Buffer.poolSize - 1); @@ -24,7 +24,7 @@ function flushPool() { function demoBug(part1, part2) { flushPool(); - var parser = new HTTPParser('REQUEST'); + const parser = new HTTPParser('REQUEST'); parser.headers = []; parser.url = ''; @@ -49,7 +49,7 @@ function demoBug(part1, part2) { // We use a function to eliminate references to the Buffer b // We want b to be GCed. The parser will hold a bad reference to it. (function() { - var b = Buffer.from(part1); + const b = Buffer.from(part1); flushPool(); console.log('parse the first part of the message'); @@ -59,7 +59,7 @@ function demoBug(part1, part2) { flushPool(); (function() { - var b = Buffer.from(part2); + const b = Buffer.from(part2); console.log('parse the second part of the message'); parser.execute(b, 0, b.length); diff --git a/test/parallel/test-http-parser-free.js b/test/parallel/test-http-parser-free.js index e9ddfa27e5a5c5..80cc3cc64ee5b3 100644 --- a/test/parallel/test-http-parser-free.js +++ b/test/parallel/test-http-parser-free.js @@ -2,19 +2,19 @@ require('../common'); const assert = require('assert'); const http = require('http'); -var N = 100; -var responses = 0; +const N = 100; +let responses = 0; -var server = http.createServer(function(req, res) { +const server = http.createServer(function(req, res) { res.end('Hello'); }); server.listen(0, function() { http.globalAgent.maxSockets = 1; - var parser; - for (var i = 0; i < N; ++i) { + let parser; + for (let i = 0; i < N; ++i) { (function makeRequest(i) { - var req = http.get({port: server.address().port}, function(res) { + const req = http.get({port: server.address().port}, function(res) { if (!parser) { parser = req.parser; } else { diff --git a/test/parallel/test-http-parser.js b/test/parallel/test-http-parser.js index 8617a093fbd311..e1215fbd13ae40 100644 --- a/test/parallel/test-http-parser.js +++ b/test/parallel/test-http-parser.js @@ -6,14 +6,14 @@ const binding = process.binding('http_parser'); const methods = binding.methods; const HTTPParser = binding.HTTPParser; -var CRLF = '\r\n'; -var REQUEST = HTTPParser.REQUEST; -var RESPONSE = HTTPParser.RESPONSE; +const CRLF = '\r\n'; +const REQUEST = HTTPParser.REQUEST; +const RESPONSE = HTTPParser.RESPONSE; -var kOnHeaders = HTTPParser.kOnHeaders | 0; -var kOnHeadersComplete = HTTPParser.kOnHeadersComplete | 0; -var kOnBody = HTTPParser.kOnBody | 0; -var kOnMessageComplete = HTTPParser.kOnMessageComplete | 0; +const kOnHeaders = HTTPParser.kOnHeaders | 0; +const kOnHeadersComplete = HTTPParser.kOnHeadersComplete | 0; +const kOnBody = HTTPParser.kOnBody | 0; +const kOnMessageComplete = HTTPParser.kOnMessageComplete | 0; // The purpose of this test is not to check HTTP compliance but to test the // binding. Tests for pathological http messages should be submitted @@ -22,7 +22,7 @@ var kOnMessageComplete = HTTPParser.kOnMessageComplete | 0; function newParser(type) { - var parser = new HTTPParser(type); + const parser = new HTTPParser(type); parser.headers = []; parser.url = ''; @@ -47,7 +47,7 @@ function newParser(type) { function mustCall(f, times) { - var actual = 0; + let actual = 0; process.setMaxListeners(256); process.on('exit', function() { @@ -63,7 +63,7 @@ function mustCall(f, times) { function expectBody(expected) { return mustCall(function(buf, start, len) { - var body = '' + buf.slice(start, start + len); + const body = '' + buf.slice(start, start + len); assert.equal(body, expected); }); } @@ -447,11 +447,11 @@ function expectBody(expected) { assert.strictEqual(expected_body, ''); } - for (var i = 1; i < request.length - 1; ++i) { - var a = request.slice(0, i); + for (let i = 1; i < request.length - 1; ++i) { + const a = request.slice(0, i); console.error('request.slice(0, ' + i + ') = ', JSON.stringify(a.toString())); - var b = request.slice(i); + const b = request.slice(i); console.error('request.slice(' + i + ') = ', JSON.stringify(b.toString())); test(a, b); @@ -571,11 +571,11 @@ function expectBody(expected) { // Test parser 'this' safety // https://github.com/joyent/node/issues/6690 assert.throws(function() { - var request = Buffer.from( + const request = Buffer.from( 'GET /hello HTTP/1.1' + CRLF + CRLF); - var parser = newParser(REQUEST); - var notparser = { execute: parser.execute }; + const parser = newParser(REQUEST); + const notparser = { execute: parser.execute }; notparser.execute(request, 0, request.length); }, TypeError); diff --git a/test/parallel/test-http-pause.js b/test/parallel/test-http-pause.js index 3c96dc6792fdad..8bb8dd4b5da25c 100644 --- a/test/parallel/test-http-pause.js +++ b/test/parallel/test-http-pause.js @@ -3,12 +3,12 @@ require('../common'); const assert = require('assert'); const http = require('http'); -var expectedServer = 'Request Body from Client'; -var resultServer = ''; -var expectedClient = 'Response Body from Server'; -var resultClient = ''; +const expectedServer = 'Request Body from Client'; +let resultServer = ''; +const expectedClient = 'Response Body from Server'; +let resultClient = ''; -var server = http.createServer(function(req, res) { +const server = http.createServer(function(req, res) { console.error('pause server request'); req.pause(); setTimeout(function() { @@ -27,7 +27,7 @@ var server = http.createServer(function(req, res) { }); server.listen(0, function() { - var req = http.request({ + const req = http.request({ port: this.address().port, path: '/', method: 'POST' diff --git a/test/parallel/test-http-pipe-fs.js b/test/parallel/test-http-pipe-fs.js index 5b3eb87a145a0f..5348637bd07145 100644 --- a/test/parallel/test-http-pipe-fs.js +++ b/test/parallel/test-http-pipe-fs.js @@ -6,10 +6,10 @@ const path = require('path'); common.refreshTmpDir(); -var file = path.join(common.tmpDir, 'http-pipe-fs-test.txt'); +const file = path.join(common.tmpDir, 'http-pipe-fs-test.txt'); -var server = http.createServer(common.mustCall(function(req, res) { - var stream = fs.createWriteStream(file); +const server = http.createServer(common.mustCall(function(req, res) { + const stream = fs.createWriteStream(file); req.pipe(stream); stream.on('close', function() { res.writeHead(200); @@ -18,9 +18,9 @@ var server = http.createServer(common.mustCall(function(req, res) { }, 2)).listen(0, function() { http.globalAgent.maxSockets = 1; - for (var i = 0; i < 2; ++i) { + for (let i = 0; i < 2; ++i) { (function(i) { - var req = http.request({ + const req = http.request({ port: server.address().port, method: 'POST', headers: { diff --git a/test/parallel/test-http-pipeline-flood.js b/test/parallel/test-http-pipeline-flood.js index 4f6775656e4e49..99e4c3e7b5b9fe 100644 --- a/test/parallel/test-http-pipeline-flood.js +++ b/test/parallel/test-http-pipeline-flood.js @@ -26,7 +26,7 @@ switch (process.argv[2]) { function parent() { const http = require('http'); const bigResponse = Buffer.alloc(10240, 'x'); - var backloggedReqs = 0; + let backloggedReqs = 0; const server = http.createServer(function(req, res) { res.setHeader('content-length', bigResponse.length); @@ -68,7 +68,7 @@ function child() { const port = +process.argv[3]; const conn = net.connect({ port: port }); - var req = `GET / HTTP/1.1\r\nHost: localhost:${port}\r\nAccept: */*\r\n\r\n`; + let req = `GET / HTTP/1.1\r\nHost: localhost:${port}\r\nAccept: */*\r\n\r\n`; req = new Array(10241).join(req); diff --git a/test/parallel/test-http-pipeline-regr-2639.js b/test/parallel/test-http-pipeline-regr-2639.js index f67803ba159c74..7933e419d324f7 100644 --- a/test/parallel/test-http-pipeline-regr-2639.js +++ b/test/parallel/test-http-pipeline-regr-2639.js @@ -6,9 +6,9 @@ const net = require('net'); const COUNT = 10; -var received = 0; +let received = 0; -var server = http.createServer(function(req, res) { +const server = http.createServer(function(req, res) { // Close the server, we have only one TCP connection anyway if (received++ === 0) server.close(); @@ -22,7 +22,7 @@ var server = http.createServer(function(req, res) { }).listen(0, function() { const s = net.connect(this.address().port); - var big = 'GET / HTTP/1.0\r\n\r\n'.repeat(COUNT); + const big = 'GET / HTTP/1.0\r\n\r\n'.repeat(COUNT); s.write(big); s.resume(); diff --git a/test/parallel/test-http-pipeline-regr-3332.js b/test/parallel/test-http-pipeline-regr-3332.js index fdbb76bf8d643d..3ab9e6104c9848 100644 --- a/test/parallel/test-http-pipeline-regr-3332.js +++ b/test/parallel/test-http-pipeline-regr-3332.js @@ -8,9 +8,9 @@ const big = Buffer.alloc(16 * 1024, 'A'); const COUNT = 1e4; -var received = 0; +let received = 0; -var client; +let client; const server = http.createServer(function(req, res) { res.end(big, function() { if (++received === COUNT) { @@ -19,7 +19,7 @@ const server = http.createServer(function(req, res) { } }); }).listen(0, function() { - var req = new Array(COUNT + 1).join('GET / HTTP/1.1\r\n\r\n'); + const req = new Array(COUNT + 1).join('GET / HTTP/1.1\r\n\r\n'); client = net.connect(this.address().port, function() { client.write(req); }); diff --git a/test/parallel/test-http-pipeline-regr-3508.js b/test/parallel/test-http-pipeline-regr-3508.js index b368bae0d7790e..ff735818f68121 100644 --- a/test/parallel/test-http-pipeline-regr-3508.js +++ b/test/parallel/test-http-pipeline-regr-3508.js @@ -3,18 +3,18 @@ require('../common'); const http = require('http'); const net = require('net'); -var once = false; -var first = null; -var second = null; +let once = false; +let first = null; +let second = null; const chunk = Buffer.alloc(1024, 'X'); -var size = 0; +let size = 0; -var more; -var done; +let more; +let done; -var server = http.createServer(function(req, res) { +const server = http.createServer(function(req, res) { if (!once) server.close(); once = true; @@ -41,7 +41,7 @@ var server = http.createServer(function(req, res) { }); first.end('hello'); }).listen(0, function() { - var s = net.connect(this.address().port); + const s = net.connect(this.address().port); more = function() { s.write('GET / HTTP/1.1\r\n\r\n'); }; diff --git a/test/parallel/test-http-proxy.js b/test/parallel/test-http-proxy.js index bfa928afb3de8b..8e7fd55a0ed6ea 100644 --- a/test/parallel/test-http-proxy.js +++ b/test/parallel/test-http-proxy.js @@ -4,23 +4,23 @@ const assert = require('assert'); const http = require('http'); const url = require('url'); -var cookies = [ +const cookies = [ 'session_token=; path=/; expires=Sun, 15-Sep-2030 13:48:52 GMT', 'prefers_open_id=; path=/; expires=Thu, 01-Jan-1970 00:00:00 GMT' ]; -var headers = {'content-type': 'text/plain', - 'set-cookie': cookies, - 'hello': 'world' }; +const headers = {'content-type': 'text/plain', + 'set-cookie': cookies, + 'hello': 'world' }; -var backend = http.createServer(function(req, res) { +const backend = http.createServer(function(req, res) { console.error('backend request'); res.writeHead(200, headers); res.write('hello world\n'); res.end(); }); -var proxy = http.createServer(function(req, res) { +const proxy = http.createServer(function(req, res) { console.error('proxy req headers: ' + JSON.stringify(req.headers)); http.get({ port: backend.address().port, @@ -46,9 +46,9 @@ var proxy = http.createServer(function(req, res) { }); }); -var body = ''; +let body = ''; -var nlistening = 0; +let nlistening = 0; function startReq() { nlistening++; if (nlistening < 2) return; diff --git a/test/parallel/test-http-raw-headers.js b/test/parallel/test-http-raw-headers.js index 0c7cc18415e914..7ae0c35e3d8d11 100644 --- a/test/parallel/test-http-raw-headers.js +++ b/test/parallel/test-http-raw-headers.js @@ -5,7 +5,7 @@ const assert = require('assert'); const http = require('http'); http.createServer(function(req, res) { - var expectRawHeaders = [ + const expectRawHeaders = [ 'Host', `localhost:${this.address().port}`, 'transfer-ENCODING', @@ -15,13 +15,13 @@ http.createServer(function(req, res) { 'Connection', 'close' ]; - var expectHeaders = { + const expectHeaders = { host: `localhost:${this.address().port}`, 'transfer-encoding': 'CHUNKED', 'x-bar': 'yoyoyo', connection: 'close' }; - var expectRawTrailers = [ + const expectRawTrailers = [ 'x-bAr', 'yOyOyOy', 'x-baR', @@ -31,7 +31,7 @@ http.createServer(function(req, res) { 'X-baR', 'OyOyOyO' ]; - var expectTrailers = { 'x-bar': 'yOyOyOy, OyOyOyO, yOyOyOy, OyOyOyO' }; + const expectTrailers = { 'x-bar': 'yOyOyOy, OyOyOyO, yOyOyOy, OyOyOyO' }; this.close(); @@ -53,7 +53,7 @@ http.createServer(function(req, res) { ]); res.end('x f o o'); }).listen(0, function() { - var req = http.request({ port: this.address().port, path: '/' }); + const req = http.request({ port: this.address().port, path: '/' }); req.addTrailers([ ['x-bAr', 'yOyOyOy'], ['x-baR', 'OyOyOyO'], @@ -64,7 +64,7 @@ http.createServer(function(req, res) { req.setHeader('x-BaR', 'yoyoyo'); req.end('y b a r'); req.on('response', function(res) { - var expectRawHeaders = [ + const expectRawHeaders = [ 'Trailer', 'x-foo', 'Date', @@ -74,7 +74,7 @@ http.createServer(function(req, res) { 'Transfer-Encoding', 'chunked' ]; - var expectHeaders = { + const expectHeaders = { trailer: 'x-foo', date: null, connection: 'close', @@ -85,7 +85,7 @@ http.createServer(function(req, res) { assert.deepStrictEqual(res.rawHeaders, expectRawHeaders); assert.deepStrictEqual(res.headers, expectHeaders); res.on('end', function() { - var expectRawTrailers = [ + const expectRawTrailers = [ 'x-fOo', 'xOxOxOx', 'x-foO', @@ -95,7 +95,7 @@ http.createServer(function(req, res) { 'X-foO', 'OxOxOxO' ]; - var expectTrailers = { 'x-foo': 'xOxOxOx, OxOxOxO, xOxOxOx, OxOxOxO' }; + const expectTrailers = { 'x-foo': 'xOxOxOx, OxOxOxO, xOxOxOx, OxOxOxO' }; assert.deepStrictEqual(res.rawTrailers, expectRawTrailers); assert.deepStrictEqual(res.trailers, expectTrailers); diff --git a/test/parallel/test-http-remove-header-stays-removed.js b/test/parallel/test-http-remove-header-stays-removed.js index bf417597b18244..077ff0f5b33f40 100644 --- a/test/parallel/test-http-remove-header-stays-removed.js +++ b/test/parallel/test-http-remove-header-stays-removed.js @@ -4,7 +4,7 @@ const assert = require('assert'); const http = require('http'); -var server = http.createServer(function(request, response) { +const server = http.createServer(function(request, response) { // removed headers should stay removed, even if node automatically adds them // to the output: response.removeHeader('connection'); @@ -20,7 +20,7 @@ var server = http.createServer(function(request, response) { this.close(); }); -var response = ''; +let response = ''; process.on('exit', function() { assert.equal('beep boop\n', response); diff --git a/test/parallel/test-http-request-dont-override-options.js b/test/parallel/test-http-request-dont-override-options.js index 5570dd49a2fc1b..04235fd0e42b4e 100644 --- a/test/parallel/test-http-request-dont-override-options.js +++ b/test/parallel/test-http-request-dont-override-options.js @@ -4,7 +4,7 @@ const common = require('../common'); const assert = require('assert'); const http = require('http'); -var requests = 0; +let requests = 0; http.createServer(function(req, res) { res.writeHead(200); @@ -12,13 +12,13 @@ http.createServer(function(req, res) { requests++; }).listen(0, function() { - var agent = new http.Agent(); + const agent = new http.Agent(); agent.defaultPort = this.address().port; // options marked as explicitly undefined for readability // in this test, they should STAY undefined as options should not // be mutable / modified - var options = { + const options = { host: undefined, hostname: common.localhostIPv4, port: undefined, diff --git a/test/parallel/test-http-request-end-twice.js b/test/parallel/test-http-request-end-twice.js index 5dd21d06dee6a6..ab30c0a1eef8a1 100644 --- a/test/parallel/test-http-request-end-twice.js +++ b/test/parallel/test-http-request-end-twice.js @@ -3,12 +3,12 @@ require('../common'); const assert = require('assert'); const http = require('http'); -var server = http.Server(function(req, res) { +const server = http.Server(function(req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('hello world\n'); }); server.listen(0, function() { - var req = http.get({port: this.address().port}, function(res) { + const req = http.get({port: this.address().port}, function(res) { res.on('end', function() { assert.ok(!req.end()); server.close(); diff --git a/test/parallel/test-http-request-end.js b/test/parallel/test-http-request-end.js index 207c3564fb5519..dd4a8caf105329 100644 --- a/test/parallel/test-http-request-end.js +++ b/test/parallel/test-http-request-end.js @@ -3,10 +3,10 @@ require('../common'); const assert = require('assert'); const http = require('http'); -var expected = 'Post Body For Test'; +const expected = 'Post Body For Test'; -var server = http.Server(function(req, res) { - var result = ''; +const server = http.Server(function(req, res) { + let result = ''; req.setEncoding('utf8'); req.on('data', function(chunk) { diff --git a/test/parallel/test-http-request-methods.js b/test/parallel/test-http-request-methods.js index b24779adf8f1ab..e4579791ef301a 100644 --- a/test/parallel/test-http-request-methods.js +++ b/test/parallel/test-http-request-methods.js @@ -7,7 +7,7 @@ const http = require('http'); // Test that the DELETE, PATCH and PURGE verbs get passed through correctly ['DELETE', 'PATCH', 'PURGE'].forEach(function(method, index) { - var server = http.createServer(common.mustCall(function(req, res) { + const server = http.createServer(common.mustCall(function(req, res) { assert.strictEqual(req.method, method); res.writeHead(200, {'Content-Type': 'text/plain'}); res.write('hello '); @@ -17,8 +17,8 @@ const http = require('http'); server.listen(0); server.on('listening', common.mustCall(function() { - var c = net.createConnection(this.address().port); - var server_response = ''; + const c = net.createConnection(this.address().port); + let server_response = ''; c.setEncoding('utf8'); diff --git a/test/parallel/test-http-res-write-after-end.js b/test/parallel/test-http-res-write-after-end.js index d01753b88a5da2..2ee0e4e29d95e4 100644 --- a/test/parallel/test-http-res-write-after-end.js +++ b/test/parallel/test-http-res-write-after-end.js @@ -3,7 +3,7 @@ const common = require('../common'); const assert = require('assert'); const http = require('http'); -var server = http.Server(common.mustCall(function(req, res) { +const server = http.Server(common.mustCall(function(req, res) { res.on('error', common.mustCall(function onResError(err) { assert.strictEqual(err.message, 'write after end'); })); @@ -11,7 +11,7 @@ var server = http.Server(common.mustCall(function(req, res) { res.write('This should write.'); res.end(); - var r = res.write('This should raise an error.'); + const r = res.write('This should raise an error.'); assert.equal(r, true, 'write after end should return true'); })); diff --git a/test/parallel/test-http-res-write-end-dont-take-array.js b/test/parallel/test-http-res-write-end-dont-take-array.js index cbae755b4fbc7f..6964ec15965a96 100644 --- a/test/parallel/test-http-res-write-end-dont-take-array.js +++ b/test/parallel/test-http-res-write-end-dont-take-array.js @@ -3,9 +3,9 @@ require('../common'); const assert = require('assert'); const http = require('http'); -var test = 1; +let test = 1; -var server = http.createServer(function(req, res) { +const server = http.createServer(function(req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); if (test === 1) { // write should accept string diff --git a/test/parallel/test-http-response-close.js b/test/parallel/test-http-response-close.js index 6b5966735a156e..de179c113e1db1 100644 --- a/test/parallel/test-http-response-close.js +++ b/test/parallel/test-http-response-close.js @@ -2,7 +2,7 @@ const common = require('../common'); const http = require('http'); -var server = http.createServer(common.mustCall(function(req, res) { +const server = http.createServer(common.mustCall(function(req, res) { res.writeHead(200); res.write('a'); diff --git a/test/parallel/test-http-response-multi-content-length.js b/test/parallel/test-http-response-multi-content-length.js index 3290f74c16e250..7cd802a74aa80c 100644 --- a/test/parallel/test-http-response-multi-content-length.js +++ b/test/parallel/test-http-response-multi-content-length.js @@ -24,7 +24,7 @@ const server = http.createServer((req, res) => { res.end('ok'); }); -var count = 0; +let count = 0; server.listen(0, common.mustCall(() => { for (let n = 1; n <= MAX_COUNT; n++) { diff --git a/test/parallel/test-http-response-multiheaders.js b/test/parallel/test-http-response-multiheaders.js index f4c1fd4116b735..8f48dc2377f3c3 100644 --- a/test/parallel/test-http-response-multiheaders.js +++ b/test/parallel/test-http-response-multiheaders.js @@ -29,7 +29,7 @@ const norepeat = [ ]; const server = http.createServer(function(req, res) { - var num = req.headers['x-num']; + const num = req.headers['x-num']; if (num === '1') { for (const name of norepeat) { res.setHeader(name, ['A', 'B']); @@ -47,7 +47,7 @@ const server = http.createServer(function(req, res) { }); server.listen(0, common.mustCall(function() { - var count = 0; + let count = 0; for (let n = 1; n <= 2; n++) { // this runs twice, the first time, the server will use // setHeader, the second time it uses writeHead. The diff --git a/test/parallel/test-http-response-no-headers.js b/test/parallel/test-http-response-no-headers.js index 4c261fc2adc7d4..3f44b4ef5fde0b 100644 --- a/test/parallel/test-http-response-no-headers.js +++ b/test/parallel/test-http-response-no-headers.js @@ -4,28 +4,28 @@ const assert = require('assert'); const http = require('http'); const net = require('net'); -var expected = { +const expected = { '0.9': 'I AM THE WALRUS', '1.0': 'I AM THE WALRUS', '1.1': '' }; function test(httpVersion, callback) { - var server = net.createServer(function(conn) { - var reply = 'HTTP/' + httpVersion + ' 200 OK\r\n\r\n' + - expected[httpVersion]; + const server = net.createServer(function(conn) { + const reply = 'HTTP/' + httpVersion + ' 200 OK\r\n\r\n' + + expected[httpVersion]; conn.end(reply); }); server.listen(0, '127.0.0.1', common.mustCall(function() { - var options = { + const options = { host: '127.0.0.1', port: this.address().port }; - var req = http.get(options, common.mustCall(function(res) { - var body = ''; + const req = http.get(options, common.mustCall(function(res) { + let body = ''; res.on('data', function(data) { body += data; diff --git a/test/parallel/test-http-response-readable.js b/test/parallel/test-http-response-readable.js index f8ecd5bab58e6c..07c0a40e4bf1a8 100644 --- a/test/parallel/test-http-response-readable.js +++ b/test/parallel/test-http-response-readable.js @@ -3,7 +3,7 @@ require('../common'); const assert = require('assert'); const http = require('http'); -var testServer = new http.Server(function(req, res) { +const testServer = new http.Server(function(req, res) { res.writeHead(200); res.end('Hello world'); }); diff --git a/test/parallel/test-http-response-splitting.js b/test/parallel/test-http-response-splitting.js index e4021e78317759..f6c3a04064ec1c 100644 --- a/test/parallel/test-http-response-splitting.js +++ b/test/parallel/test-http-response-splitting.js @@ -17,7 +17,7 @@ const str = '/welcome?lang=bar%c4%8d%c4%8aContent­Length:%200%c4%8d%c4%8a%c' + const x = 'fooഊSet-Cookie: foo=barഊഊ'; const y = 'foo⠊Set-Cookie: foo=bar'; -var count = 0; +let count = 0; const server = http.createServer((req, res) => { switch (count++) { diff --git a/test/parallel/test-http-response-status-message.js b/test/parallel/test-http-response-status-message.js index cfc9e6420905ad..d17dfb24c6b4c8 100644 --- a/test/parallel/test-http-response-status-message.js +++ b/test/parallel/test-http-response-status-message.js @@ -4,9 +4,9 @@ const assert = require('assert'); const http = require('http'); const net = require('net'); -var testsComplete = 0; +let testsComplete = 0; -var testCases = [ +const testCases = [ { path: '/200', statusMessage: 'OK', response: 'HTTP/1.1 200 OK\r\n\r\n' }, { path: '/500', statusMessage: 'Internal Server Error', @@ -19,7 +19,7 @@ var testCases = [ response: 'HTTP/1.1 200\r\n\r\n' } ]; testCases.findByPath = function(path) { - var matching = this.filter(function(testCase) { + const matching = this.filter(function(testCase) { return testCase.path === path; }); if (matching.length === 0) { @@ -28,18 +28,18 @@ testCases.findByPath = function(path) { return matching[0]; }; -var server = net.createServer(function(connection) { +const server = net.createServer(function(connection) { connection.on('data', function(data) { - var path = data.toString().match(/GET (.*) HTTP.1.1/)[1]; - var testCase = testCases.findByPath(path); + const path = data.toString().match(/GET (.*) HTTP.1.1/)[1]; + const testCase = testCases.findByPath(path); connection.write(testCase.response); connection.end(); }); }); -var runTest = function(testCaseIndex) { - var testCase = testCases[testCaseIndex]; +const runTest = function(testCaseIndex) { + const testCase = testCases[testCaseIndex]; http.get({ port: server.address().port, diff --git a/test/parallel/test-http-response-statuscode.js b/test/parallel/test-http-response-statuscode.js index 57256db6032324..4bd75647aebea7 100644 --- a/test/parallel/test-http-response-statuscode.js +++ b/test/parallel/test-http-response-statuscode.js @@ -4,7 +4,7 @@ const assert = require('assert'); const http = require('http'); const MAX_REQUESTS = 12; -var reqNum = 0; +let reqNum = 0; const server = http.Server(common.mustCall(function(req, res) { switch (reqNum) { diff --git a/test/parallel/test-http-server-client-error.js b/test/parallel/test-http-server-client-error.js index cd20b7321a63f7..260963dc24daaa 100644 --- a/test/parallel/test-http-server-client-error.js +++ b/test/parallel/test-http-server-client-error.js @@ -21,7 +21,7 @@ server.listen(0, function() { const client = net.connect(server.address().port); client.end('Oopsie-doopsie\r\n'); - var chunks = ''; + let chunks = ''; client.on('data', function(chunk) { chunks += chunk; }); diff --git a/test/parallel/test-http-server-multiheaders.js b/test/parallel/test-http-server-multiheaders.js index b978cb3ad4aad9..189ab0657bacb0 100644 --- a/test/parallel/test-http-server-multiheaders.js +++ b/test/parallel/test-http-server-multiheaders.js @@ -7,7 +7,7 @@ require('../common'); const assert = require('assert'); const http = require('http'); -var srv = http.createServer(function(req, res) { +const srv = http.createServer(function(req, res) { assert.equal(req.headers.accept, 'abc, def, ghijklmnopqrst'); assert.equal(req.headers.host, 'foo'); assert.equal(req.headers['www-authenticate'], 'foo, bar, baz'); diff --git a/test/parallel/test-http-server-multiheaders2.js b/test/parallel/test-http-server-multiheaders2.js index ba0710f70c839a..82cc9960329a11 100644 --- a/test/parallel/test-http-server-multiheaders2.js +++ b/test/parallel/test-http-server-multiheaders2.js @@ -7,7 +7,7 @@ require('../common'); const assert = require('assert'); const http = require('http'); -var multipleAllowed = [ +const multipleAllowed = [ 'Accept', 'Accept-Charset', 'Accept-Encoding', @@ -31,7 +31,7 @@ var multipleAllowed = [ 'X-Some-Random-Header', ]; -var multipleForbidden = [ +const multipleForbidden = [ 'Content-Type', 'User-Agent', 'Referer', @@ -48,7 +48,7 @@ var multipleForbidden = [ //'Content-Length', ]; -var srv = http.createServer(function(req, res) { +const srv = http.createServer(function(req, res) { multipleForbidden.forEach(function(header) { assert.equal(req.headers[header.toLowerCase()], 'foo', 'header parsed incorrectly: ' + header); @@ -70,7 +70,7 @@ function makeHeader(value) { }; } -var headers = [] +const headers = [] .concat(multipleAllowed.map(makeHeader('foo'))) .concat(multipleForbidden.map(makeHeader('foo'))) .concat(multipleAllowed.map(makeHeader('bar'))) diff --git a/test/parallel/test-http-server-stale-close.js b/test/parallel/test-http-server-stale-close.js index 04e9635403614c..3728453c039447 100644 --- a/test/parallel/test-http-server-stale-close.js +++ b/test/parallel/test-http-server-stale-close.js @@ -5,7 +5,7 @@ const util = require('util'); const fork = require('child_process').fork; if (process.env.NODE_TEST_FORK_PORT) { - var req = http.request({ + const req = http.request({ headers: {'Content-Length': '42'}, method: 'POST', host: '127.0.0.1', @@ -14,7 +14,7 @@ if (process.env.NODE_TEST_FORK_PORT) { req.write('BAM'); req.end(); } else { - var server = http.createServer(function(req, res) { + const server = http.createServer(function(req, res) { res.writeHead(200, {'Content-Length': '42'}); req.pipe(res); req.on('close', function() { diff --git a/test/parallel/test-http-server-unconsume.js b/test/parallel/test-http-server-unconsume.js index fd5486a289e590..fca2691aacc25d 100644 --- a/test/parallel/test-http-server-unconsume.js +++ b/test/parallel/test-http-server-unconsume.js @@ -4,9 +4,9 @@ const assert = require('assert'); const http = require('http'); const net = require('net'); -var received = ''; +let received = ''; -var server = http.createServer(function(req, res) { +const server = http.createServer(function(req, res) { res.writeHead(200); res.end(); @@ -16,7 +16,7 @@ var server = http.createServer(function(req, res) { server.close(); }).listen(0, function() { - var socket = net.connect(this.address().port, function() { + const socket = net.connect(this.address().port, function() { socket.write('PUT / HTTP/1.1\r\n\r\n'); socket.once('data', function() { diff --git a/test/parallel/test-http-server.js b/test/parallel/test-http-server.js index c915272af2b9bf..90c2709ebdbc5c 100644 --- a/test/parallel/test-http-server.js +++ b/test/parallel/test-http-server.js @@ -6,12 +6,12 @@ const http = require('http'); const url = require('url'); const qs = require('querystring'); -var request_number = 0; -var requests_sent = 0; -var server_response = ''; -var client_got_eof = false; +let request_number = 0; +let requests_sent = 0; +let server_response = ''; +let client_got_eof = false; -var server = http.createServer(function(req, res) { +const server = http.createServer(function(req, res) { res.id = request_number; req.id = request_number++; @@ -48,7 +48,7 @@ server.listen(0); server.httpAllowHalfOpen = true; server.on('listening', function() { - var c = net.createConnection(this.address().port); + const c = net.createConnection(this.address().port); c.setEncoding('utf8'); @@ -94,10 +94,10 @@ process.on('exit', function() { assert.strictEqual(4, request_number); assert.strictEqual(4, requests_sent); - var hello = new RegExp('/hello'); + const hello = new RegExp('/hello'); assert.notStrictEqual(null, hello.exec(server_response)); - var quit = new RegExp('/quit'); + const quit = new RegExp('/quit'); assert.notStrictEqual(null, quit.exec(server_response)); assert.strictEqual(true, client_got_eof); diff --git a/test/parallel/test-http-set-cookies.js b/test/parallel/test-http-set-cookies.js index 3fa01655b4acdb..cb06352b3ca85d 100644 --- a/test/parallel/test-http-set-cookies.js +++ b/test/parallel/test-http-set-cookies.js @@ -3,9 +3,9 @@ require('../common'); const assert = require('assert'); const http = require('http'); -var nresponses = 0; +let nresponses = 0; -var server = http.createServer(function(req, res) { +const server = http.createServer(function(req, res) { if (req.url === '/one') { res.writeHead(200, [['set-cookie', 'A'], ['content-type', 'text/plain']]); diff --git a/test/parallel/test-http-set-timeout-server.js b/test/parallel/test-http-set-timeout-server.js index 03fca8f219300b..7a2447763e4cf9 100644 --- a/test/parallel/test-http-set-timeout-server.js +++ b/test/parallel/test-http-set-timeout-server.js @@ -4,7 +4,7 @@ const assert = require('assert'); const http = require('http'); const net = require('net'); -var tests = []; +const tests = []; function test(fn) { if (!tests.length) @@ -13,7 +13,7 @@ function test(fn) { } function run() { - var fn = tests.shift(); + const fn = tests.shift(); if (fn) { console.log('# %s', fn.name); fn(run); @@ -23,17 +23,17 @@ function run() { } test(function serverTimeout(cb) { - var caughtTimeout = false; + let caughtTimeout = false; process.on('exit', function() { assert(caughtTimeout); }); - var server = http.createServer(function(req, res) { + const server = http.createServer(function(req, res) { // just do nothing, we should get a timeout event. }); server.listen(common.mustCall(function() { http.get({ port: server.address().port }).on('error', function() {}); })); - var s = server.setTimeout(50, function(socket) { + const s = server.setTimeout(50, function(socket) { caughtTimeout = true; socket.destroy(); server.close(); @@ -43,13 +43,13 @@ test(function serverTimeout(cb) { }); test(function serverRequestTimeout(cb) { - var caughtTimeout = false; + let caughtTimeout = false; process.on('exit', function() { assert(caughtTimeout); }); - var server = http.createServer(function(req, res) { + const server = http.createServer(function(req, res) { // just do nothing, we should get a timeout event. - var s = req.setTimeout(50, function() { + const s = req.setTimeout(50, function() { caughtTimeout = true; req.socket.destroy(); server.close(); @@ -58,8 +58,8 @@ test(function serverRequestTimeout(cb) { assert.ok(s instanceof http.IncomingMessage); }); server.listen(common.mustCall(function() { - var port = server.address().port; - var req = http.request({ port: port, method: 'POST' }); + const port = server.address().port; + const req = http.request({ port: port, method: 'POST' }); req.on('error', function() {}); req.write('Hello'); // req is in progress @@ -67,13 +67,13 @@ test(function serverRequestTimeout(cb) { }); test(function serverResponseTimeout(cb) { - var caughtTimeout = false; + let caughtTimeout = false; process.on('exit', function() { assert(caughtTimeout); }); - var server = http.createServer(function(req, res) { + const server = http.createServer(function(req, res) { // just do nothing, we should get a timeout event. - var s = res.setTimeout(50, function() { + const s = res.setTimeout(50, function() { caughtTimeout = true; res.socket.destroy(); server.close(); @@ -82,21 +82,21 @@ test(function serverResponseTimeout(cb) { assert.ok(s instanceof http.OutgoingMessage); }); server.listen(common.mustCall(function() { - var port = server.address().port; + const port = server.address().port; http.get({ port: port }).on('error', function() {}); })); }); test(function serverRequestNotTimeoutAfterEnd(cb) { - var caughtTimeoutOnRequest = false; - var caughtTimeoutOnResponse = false; + let caughtTimeoutOnRequest = false; + let caughtTimeoutOnResponse = false; process.on('exit', function() { assert(!caughtTimeoutOnRequest); assert(caughtTimeoutOnResponse); }); - var server = http.createServer(function(req, res) { + const server = http.createServer(function(req, res) { // just do nothing, we should get a timeout event. - var s = req.setTimeout(50, function(socket) { + const s = req.setTimeout(50, function(socket) { caughtTimeoutOnRequest = true; }); assert.ok(s instanceof http.IncomingMessage); @@ -110,18 +110,18 @@ test(function serverRequestNotTimeoutAfterEnd(cb) { cb(); }); server.listen(common.mustCall(function() { - var port = server.address().port; + const port = server.address().port; http.get({ port: port }).on('error', function() {}); })); }); test(function serverResponseTimeoutWithPipeline(cb) { - var caughtTimeout = ''; + let caughtTimeout = ''; process.on('exit', function() { assert.equal(caughtTimeout, '/2'); }); - var server = http.createServer(function(req, res) { - var s = res.setTimeout(50, function() { + const server = http.createServer(function(req, res) { + const s = res.setTimeout(50, function() { caughtTimeout += req.url; }); assert.ok(s instanceof http.OutgoingMessage); @@ -133,8 +133,8 @@ test(function serverResponseTimeoutWithPipeline(cb) { cb(); }); server.listen(common.mustCall(function() { - var port = server.address().port; - var c = net.connect({ port: port, allowHalfOpen: true }, function() { + const port = server.address().port; + const c = net.connect({ port: port, allowHalfOpen: true }, function() { c.write('GET /1 HTTP/1.1\r\nHost: localhost\r\n\r\n'); c.write('GET /2 HTTP/1.1\r\nHost: localhost\r\n\r\n'); c.write('GET /3 HTTP/1.1\r\nHost: localhost\r\n\r\n'); @@ -143,15 +143,15 @@ test(function serverResponseTimeoutWithPipeline(cb) { }); test(function idleTimeout(cb) { - var caughtTimeoutOnRequest = false; - var caughtTimeoutOnResponse = false; - var caughtTimeoutOnServer = false; + let caughtTimeoutOnRequest = false; + let caughtTimeoutOnResponse = false; + let caughtTimeoutOnServer = false; process.on('exit', function() { assert(!caughtTimeoutOnRequest); assert(!caughtTimeoutOnResponse); assert(caughtTimeoutOnServer); }); - var server = http.createServer(function(req, res) { + const server = http.createServer(function(req, res) { req.on('timeout', function(socket) { caughtTimeoutOnRequest = true; }); @@ -160,7 +160,7 @@ test(function idleTimeout(cb) { }); res.end(); }); - var s = server.setTimeout(50, function(socket) { + const s = server.setTimeout(50, function(socket) { caughtTimeoutOnServer = true; socket.destroy(); server.close(); @@ -168,8 +168,8 @@ test(function idleTimeout(cb) { }); assert.ok(s instanceof http.Server); server.listen(common.mustCall(function() { - var port = server.address().port; - var c = net.connect({ port: port, allowHalfOpen: true }, function() { + const port = server.address().port; + const c = net.connect({ port: port, allowHalfOpen: true }, function() { c.write('GET /1 HTTP/1.1\r\nHost: localhost\r\n\r\n'); // Keep-Alive }); diff --git a/test/parallel/test-http-set-timeout.js b/test/parallel/test-http-set-timeout.js index e8df29e0ccdc67..965b3486faee95 100644 --- a/test/parallel/test-http-set-timeout.js +++ b/test/parallel/test-http-set-timeout.js @@ -4,9 +4,9 @@ const assert = require('assert'); const http = require('http'); const net = require('net'); -var server = http.createServer(function(req, res) { +const server = http.createServer(function(req, res) { console.log('got request. setting 500ms timeout'); - var socket = req.connection.setTimeout(500); + const socket = req.connection.setTimeout(500); assert.ok(socket instanceof net.Socket); req.connection.on('timeout', common.mustCall(function() { req.connection.destroy(); @@ -18,7 +18,7 @@ var server = http.createServer(function(req, res) { server.listen(0, function() { console.log(`Server running at http://127.0.0.1:${this.address().port}/`); - var request = http.get({port: this.address().port, path: '/'}); + const request = http.get({port: this.address().port, path: '/'}); request.on('error', common.mustCall(function() { console.log('HTTP REQUEST COMPLETE (this is good)'); })); diff --git a/test/parallel/test-http-set-trailers.js b/test/parallel/test-http-set-trailers.js index e34ea889b0bed4..7b66933ecd12cd 100644 --- a/test/parallel/test-http-set-trailers.js +++ b/test/parallel/test-http-set-trailers.js @@ -4,9 +4,9 @@ const assert = require('assert'); const http = require('http'); const net = require('net'); -var outstanding_reqs = 0; +let outstanding_reqs = 0; -var server = http.createServer(function(req, res) { +const server = http.createServer(function(req, res) { res.writeHead(200, [['content-type', 'text/plain']]); res.addTrailers({'x-foo': 'bar'}); res.end('stuff' + '\n'); @@ -16,8 +16,8 @@ server.listen(0); // first, we test an HTTP/1.0 request. server.on('listening', function() { - var c = net.createConnection(this.address().port); - var res_buffer = ''; + const c = net.createConnection(this.address().port); + let res_buffer = ''; c.setEncoding('utf8'); @@ -44,9 +44,9 @@ server.on('listening', function() { // now, we test an HTTP/1.1 request. server.on('listening', function() { - var c = net.createConnection(this.address().port); - var res_buffer = ''; - var tid; + const c = net.createConnection(this.address().port); + let res_buffer = ''; + let tid; c.setEncoding('utf8'); diff --git a/test/parallel/test-http-should-keep-alive.js b/test/parallel/test-http-should-keep-alive.js index 5cfbd51e76ac9e..77a3c3922a20f0 100644 --- a/test/parallel/test-http-should-keep-alive.js +++ b/test/parallel/test-http-should-keep-alive.js @@ -4,7 +4,7 @@ const assert = require('assert'); const http = require('http'); const net = require('net'); -var SERVER_RESPONSES = [ +const SERVER_RESPONSES = [ 'HTTP/1.0 200 ok\r\nContent-Length: 0\r\n\r\n', 'HTTP/1.0 200 ok\r\nContent-Length: 0\r\nConnection: keep-alive\r\n\r\n', 'HTTP/1.0 200 ok\r\nContent-Length: 0\r\nConnection: close\r\n\r\n', @@ -12,7 +12,7 @@ var SERVER_RESPONSES = [ 'HTTP/1.1 200 ok\r\nContent-Length: 0\r\nConnection: keep-alive\r\n\r\n', 'HTTP/1.1 200 ok\r\nContent-Length: 0\r\nConnection: close\r\n\r\n' ]; -var SHOULD_KEEP_ALIVE = [ +const SHOULD_KEEP_ALIVE = [ false, // HTTP/1.0, default true, // HTTP/1.0, Connection: keep-alive false, // HTTP/1.0, Connection: close @@ -20,16 +20,16 @@ var SHOULD_KEEP_ALIVE = [ true, // HTTP/1.1, Connection: keep-alive false // HTTP/1.1, Connection: close ]; -var requests = 0; -var responses = 0; +let requests = 0; +let responses = 0; http.globalAgent.maxSockets = 5; -var server = net.createServer(function(socket) { +const server = net.createServer(function(socket) { socket.write(SERVER_RESPONSES[requests]); ++requests; }).listen(0, function() { function makeRequest() { - var req = http.get({port: server.address().port}, function(res) { + const req = http.get({port: server.address().port}, function(res) { assert.equal(req.shouldKeepAlive, SHOULD_KEEP_ALIVE[responses], SERVER_RESPONSES[responses] + ' should ' + (SHOULD_KEEP_ALIVE[responses] ? '' : 'not ') + diff --git a/test/parallel/test-http-status-code.js b/test/parallel/test-http-status-code.js index 0b3d204c435a2b..b5060109bf4985 100644 --- a/test/parallel/test-http-status-code.js +++ b/test/parallel/test-http-status-code.js @@ -6,12 +6,12 @@ const http = require('http'); // Simple test of Node's HTTP ServerResponse.statusCode // ServerResponse.prototype.statusCode -var testsComplete = 0; -var tests = [200, 202, 300, 404, 451, 500]; -var testIdx = 0; +let testsComplete = 0; +const tests = [200, 202, 300, 404, 451, 500]; +let testIdx = 0; -var s = http.createServer(function(req, res) { - var t = tests[testIdx]; +const s = http.createServer(function(req, res) { + const t = tests[testIdx]; res.writeHead(t, {'Content-Type': 'text/plain'}); console.log('--\nserver: statusCode after writeHead: ' + res.statusCode); assert.equal(res.statusCode, t); @@ -25,7 +25,7 @@ function nextTest() { if (testIdx + 1 === tests.length) { return s.close(); } - var test = tests[testIdx]; + const test = tests[testIdx]; http.get({ port: s.address().port }, function(response) { console.log('client: expected status: ' + test); diff --git a/test/parallel/test-http-status-message.js b/test/parallel/test-http-status-message.js index 9a086dcd4673fd..668b02ee0780b4 100644 --- a/test/parallel/test-http-status-message.js +++ b/test/parallel/test-http-status-message.js @@ -4,7 +4,7 @@ const assert = require('assert'); const http = require('http'); const net = require('net'); -var s = http.createServer(function(req, res) { +const s = http.createServer(function(req, res) { res.statusCode = 200; res.statusMessage = 'Custom Message'; res.end(''); @@ -14,15 +14,15 @@ s.listen(0, test); function test() { - var bufs = []; - var client = net.connect(this.address().port, function() { + const bufs = []; + const client = net.connect(this.address().port, function() { client.write('GET / HTTP/1.1\r\nConnection: close\r\n\r\n'); }); client.on('data', function(chunk) { bufs.push(chunk); }); client.on('end', function() { - var head = Buffer.concat(bufs).toString('latin1').split('\r\n')[0]; + const head = Buffer.concat(bufs).toString('latin1').split('\r\n')[0]; assert.equal('HTTP/1.1 200 Custom Message', head); console.log('ok'); s.close(); diff --git a/test/parallel/test-http-timeout-overflow.js b/test/parallel/test-http-timeout-overflow.js index c045a28ce75df1..39b4550d57e529 100644 --- a/test/parallel/test-http-timeout-overflow.js +++ b/test/parallel/test-http-timeout-overflow.js @@ -4,10 +4,10 @@ const assert = require('assert'); const http = require('http'); -var serverRequests = 0; -var clientRequests = 0; +let serverRequests = 0; +let clientRequests = 0; -var server = http.createServer(function(req, res) { +const server = http.createServer(function(req, res) { serverRequests++; res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('OK'); @@ -16,7 +16,7 @@ var server = http.createServer(function(req, res) { server.listen(0, function() { function callback() {} - var req = http.request({ + const req = http.request({ port: this.address().port, path: '/', agent: false diff --git a/test/parallel/test-http-timeout.js b/test/parallel/test-http-timeout.js index 128ca148839b6b..63f87ed63089ee 100644 --- a/test/parallel/test-http-timeout.js +++ b/test/parallel/test-http-timeout.js @@ -3,22 +3,22 @@ require('../common'); const http = require('http'); -var server = http.createServer(function(req, res) { +const server = http.createServer(function(req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('OK'); }); -var agent = new http.Agent({maxSockets: 1}); +const agent = new http.Agent({maxSockets: 1}); server.listen(0, function() { - for (var i = 0; i < 11; ++i) { + for (let i = 0; i < 11; ++i) { createRequest().end(); } function callback() {} - var count = 0; + let count = 0; function createRequest() { const req = http.request( diff --git a/test/parallel/test-http-unix-socket.js b/test/parallel/test-http-unix-socket.js index d2b99bde95a234..f9308d86325cd1 100644 --- a/test/parallel/test-http-unix-socket.js +++ b/test/parallel/test-http-unix-socket.js @@ -17,12 +17,12 @@ common.refreshTmpDir(); server.listen(common.PIPE, common.mustCall(function() { - var options = { + const options = { socketPath: common.PIPE, path: '/' }; - var req = http.get(options, common.mustCall(function(res) { + const req = http.get(options, common.mustCall(function(res) { assert.strictEqual(res.statusCode, 200); assert.strictEqual(res.headers['content-type'], 'text/plain'); diff --git a/test/parallel/test-http-upgrade-agent.js b/test/parallel/test-http-upgrade-agent.js index 27f21649a7d508..a196ba904905a3 100644 --- a/test/parallel/test-http-upgrade-agent.js +++ b/test/parallel/test-http-upgrade-agent.js @@ -10,7 +10,7 @@ const http = require('http'); const net = require('net'); // Create a TCP server -var srv = net.createServer(function(c) { +const srv = net.createServer(function(c) { c.on('data', function(d) { c.write('HTTP/1.1 101\r\n'); c.write('hello: world\r\n'); @@ -27,7 +27,7 @@ var srv = net.createServer(function(c) { srv.listen(0, '127.0.0.1', common.mustCall(function() { - var options = { + const options = { port: this.address().port, host: '127.0.0.1', headers: { @@ -35,13 +35,13 @@ srv.listen(0, '127.0.0.1', common.mustCall(function() { 'upgrade': 'websocket' } }; - var name = options.host + ':' + options.port; + const name = options.host + ':' + options.port; - var req = http.request(options); + const req = http.request(options); req.end(); req.on('upgrade', common.mustCall(function(res, socket, upgradeHead) { - var recvData = upgradeHead; + let recvData = upgradeHead; socket.on('data', function(d) { recvData += d; }); @@ -51,9 +51,9 @@ srv.listen(0, '127.0.0.1', common.mustCall(function() { })); console.log(res.headers); - var expectedHeaders = { 'hello': 'world', - 'connection': 'upgrade', - 'upgrade': 'websocket' }; + const expectedHeaders = { 'hello': 'world', + 'connection': 'upgrade', + 'upgrade': 'websocket' }; assert.deepStrictEqual(expectedHeaders, res.headers); // Make sure this request got removed from the pool. diff --git a/test/parallel/test-http-upgrade-client.js b/test/parallel/test-http-upgrade-client.js index f5c25f15d4136c..34e3e8f24158e7 100644 --- a/test/parallel/test-http-upgrade-client.js +++ b/test/parallel/test-http-upgrade-client.js @@ -10,7 +10,7 @@ const http = require('http'); const net = require('net'); // Create a TCP server -var srv = net.createServer(function(c) { +const srv = net.createServer(function(c) { c.on('data', function(d) { c.write('HTTP/1.1 101\r\n'); c.write('hello: world\r\n'); @@ -39,16 +39,16 @@ srv.listen(0, '127.0.0.1', common.mustCall(function() { ['Origin', 'http://www.websocket.org'] ] ]; - var left = headers.length; + let left = headers.length; headers.forEach(function(h) { - var req = http.get({ + const req = http.get({ port: port, headers: h }); - var sawUpgrade = false; + let sawUpgrade = false; req.on('upgrade', common.mustCall(function(res, socket, upgradeHead) { sawUpgrade = true; - var recvData = upgradeHead; + let recvData = upgradeHead; socket.on('data', function(d) { recvData += d; }); diff --git a/test/parallel/test-http-upgrade-client2.js b/test/parallel/test-http-upgrade-client2.js index 03cb36981ad6d7..fa14f8ca51f030 100644 --- a/test/parallel/test-http-upgrade-client2.js +++ b/test/parallel/test-http-upgrade-client2.js @@ -2,9 +2,9 @@ const common = require('../common'); const http = require('http'); -var CRLF = '\r\n'; +const CRLF = '\r\n'; -var server = http.createServer(); +const server = http.createServer(); server.on('upgrade', function(req, socket, head) { socket.write('HTTP/1.1 101 Ok' + CRLF + 'Connection: Upgrade' + CRLF + @@ -18,12 +18,12 @@ server.listen(0, common.mustCall(function() { function upgradeRequest(fn) { console.log('req'); - var header = { 'Connection': 'Upgrade', 'Upgrade': 'Test' }; - var request = http.request({ + const header = { 'Connection': 'Upgrade', 'Upgrade': 'Test' }; + const request = http.request({ port: server.address().port, headers: header }); - var wasUpgrade = false; + let wasUpgrade = false; function onUpgrade(res, socket, head) { console.log('client upgraded'); diff --git a/test/parallel/test-http-upgrade-server.js b/test/parallel/test-http-upgrade-server.js index 50183dffe18ae7..221263e98ce9cd 100644 --- a/test/parallel/test-http-upgrade-server.js +++ b/test/parallel/test-http-upgrade-server.js @@ -7,9 +7,9 @@ const net = require('net'); const http = require('http'); -var requests_recv = 0; -var requests_sent = 0; -var request_upgradeHead = null; +let requests_recv = 0; +let requests_sent = 0; +let request_upgradeHead = null; function createTestServer() { return new testServer(); @@ -37,7 +37,7 @@ function testServer() { request_upgradeHead = upgradeHead; socket.on('data', function(d) { - var data = d.toString('utf8'); + const data = d.toString('utf8'); if (data === 'kill') { socket.end(); } else { @@ -60,9 +60,9 @@ function writeReq(socket, data, encoding) { connection: Upgrade with listener -----------------------------------------------*/ function test_upgrade_with_listener() { - var conn = net.createConnection(server.address().port); + const conn = net.createConnection(server.address().port); conn.setEncoding('utf8'); - var state = 0; + let state = 0; conn.on('connect', function() { writeReq(conn, @@ -99,10 +99,10 @@ function test_upgrade_with_listener() { /*----------------------------------------------- connection: Upgrade, no listener -----------------------------------------------*/ -var test_upgrade_no_listener_ended = false; +let test_upgrade_no_listener_ended = false; function test_upgrade_no_listener() { - var conn = net.createConnection(server.address().port); + const conn = net.createConnection(server.address().port); conn.setEncoding('utf8'); conn.on('connect', function() { @@ -127,7 +127,7 @@ function test_upgrade_no_listener() { connection: normal -----------------------------------------------*/ function test_standard_http() { - var conn = net.createConnection(server.address().port); + const conn = net.createConnection(server.address().port); conn.setEncoding('utf8'); conn.on('connect', function() { @@ -146,7 +146,7 @@ function test_standard_http() { } -var server = createTestServer(); +const server = createTestServer(); server.listen(0, function() { // All tests get chained after this: diff --git a/test/parallel/test-http-upgrade-server2.js b/test/parallel/test-http-upgrade-server2.js index e7533b194d0760..c64b2e843637af 100644 --- a/test/parallel/test-http-upgrade-server2.js +++ b/test/parallel/test-http-upgrade-server2.js @@ -4,7 +4,7 @@ const assert = require('assert'); const http = require('http'); const net = require('net'); -var server = http.createServer(function(req, res) { +const server = http.createServer(function(req, res) { throw new Error('This shouldn\'t happen.'); }); @@ -21,7 +21,7 @@ process.on('uncaughtException', common.mustCall(function(e) { server.listen(0, function() { - var c = net.createConnection(this.address().port); + const c = net.createConnection(this.address().port); c.on('connect', function() { c.write('GET /blah HTTP/1.1\r\n' + diff --git a/test/parallel/test-http-url.parse-auth-with-header-in-request.js b/test/parallel/test-http-url.parse-auth-with-header-in-request.js index 9781cefcbdb23a..d91ec75f60d767 100644 --- a/test/parallel/test-http-url.parse-auth-with-header-in-request.js +++ b/test/parallel/test-http-url.parse-auth-with-header-in-request.js @@ -9,7 +9,7 @@ function check(request) { assert.strictEqual(request.headers.authorization, 'NoAuthForYOU'); } -var server = http.createServer(function(request, response) { +const server = http.createServer(function(request, response) { // run the check function check.call(this, request, response); response.writeHead(200, {}); @@ -18,7 +18,8 @@ var server = http.createServer(function(request, response) { }); server.listen(0, function() { - var testURL = url.parse(`http://asdf:qwer@localhost:${this.address().port}`); + const testURL = url.parse('http://asdf:qwer@localhost:' + + `${this.address().port}`); // the test here is if you set a specific authorization header in the // request we should not override that with basic auth testURL.headers = { diff --git a/test/parallel/test-http-url.parse-auth.js b/test/parallel/test-http-url.parse-auth.js index 72e69b14a9a3b8..25913f4e49a12a 100644 --- a/test/parallel/test-http-url.parse-auth.js +++ b/test/parallel/test-http-url.parse-auth.js @@ -9,7 +9,7 @@ function check(request) { assert.strictEqual(request.headers.authorization, 'Basic dXNlcjpwYXNzOg=='); } -var server = http.createServer(function(request, response) { +const server = http.createServer(function(request, response) { // run the check function check.call(this, request, response); response.writeHead(200, {}); @@ -20,7 +20,7 @@ var server = http.createServer(function(request, response) { server.listen(0, function() { const port = this.address().port; // username = "user", password = "pass:" - var testURL = url.parse(`http://user:pass%3A@localhost:${port}`); + const testURL = url.parse(`http://user:pass%3A@localhost:${port}`); // make the request http.request(testURL).end(); diff --git a/test/parallel/test-http-url.parse-basic.js b/test/parallel/test-http-url.parse-basic.js index 0fa8f104653162..ac22b6e38d80e1 100644 --- a/test/parallel/test-http-url.parse-basic.js +++ b/test/parallel/test-http-url.parse-basic.js @@ -4,7 +4,7 @@ const assert = require('assert'); const http = require('http'); const url = require('url'); -var testURL; +let testURL; // make sure the basics work function check(request) { @@ -17,7 +17,7 @@ function check(request) { testURL.hostname + ':' + testURL.port); } -var server = http.createServer(function(request, response) { +const server = http.createServer(function(request, response) { // run the check function check.call(this, request, response); response.writeHead(200, {}); @@ -29,7 +29,7 @@ server.listen(0, function() { testURL = url.parse(`http://localhost:${this.address().port}`); // make the request - var clientRequest = http.request(testURL); + const clientRequest = http.request(testURL); // since there is a little magic with the agent // make sure that an http request uses the http.Agent assert.ok(clientRequest.agent instanceof http.Agent); diff --git a/test/parallel/test-http-url.parse-https.request.js b/test/parallel/test-http-url.parse-https.request.js index ddd1d5147532b1..ad40e76debee90 100644 --- a/test/parallel/test-http-url.parse-https.request.js +++ b/test/parallel/test-http-url.parse-https.request.js @@ -12,7 +12,7 @@ const url = require('url'); const fs = require('fs'); // https options -var httpsOptions = { +const httpsOptions = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }; @@ -22,7 +22,7 @@ function check(request) { assert.ok(request.socket._secureEstablished); } -var server = https.createServer(httpsOptions, function(request, response) { +const server = https.createServer(httpsOptions, function(request, response) { // run the check function check.call(this, request, response); response.writeHead(200, {}); @@ -31,11 +31,11 @@ var server = https.createServer(httpsOptions, function(request, response) { }); server.listen(0, function() { - var testURL = url.parse(`https://localhost:${this.address().port}`); + const testURL = url.parse(`https://localhost:${this.address().port}`); testURL.rejectUnauthorized = false; // make the request - var clientRequest = https.request(testURL); + const clientRequest = https.request(testURL); // since there is a little magic with the agent // make sure that the request uses the https.Agent assert.ok(clientRequest.agent instanceof https.Agent); diff --git a/test/parallel/test-http-url.parse-path.js b/test/parallel/test-http-url.parse-path.js index e5a1306f8ee077..6fab8bb0eb3b6b 100644 --- a/test/parallel/test-http-url.parse-path.js +++ b/test/parallel/test-http-url.parse-path.js @@ -9,7 +9,7 @@ function check(request) { assert.strictEqual(request.url, '/asdf'); } -var server = http.createServer(function(request, response) { +const server = http.createServer(function(request, response) { // run the check function check.call(this, request, response); response.writeHead(200, {}); @@ -18,7 +18,7 @@ var server = http.createServer(function(request, response) { }); server.listen(0, function() { - var testURL = url.parse(`http://localhost:${this.address().port}/asdf`); + const testURL = url.parse(`http://localhost:${this.address().port}/asdf`); // make the request http.request(testURL).end(); diff --git a/test/parallel/test-http-url.parse-post.js b/test/parallel/test-http-url.parse-post.js index 3ea40de6ecca5d..d63f404c5403dd 100644 --- a/test/parallel/test-http-url.parse-post.js +++ b/test/parallel/test-http-url.parse-post.js @@ -4,7 +4,7 @@ const assert = require('assert'); const http = require('http'); const url = require('url'); -var testURL; +let testURL; function check(request) { //url.parse should not mess with the method @@ -16,7 +16,7 @@ function check(request) { testURL.hostname + ':' + testURL.port); } -var server = http.createServer(function(request, response) { +const server = http.createServer(function(request, response) { // run the check function check.call(this, request, response); response.writeHead(200, {}); diff --git a/test/parallel/test-http-url.parse-search.js b/test/parallel/test-http-url.parse-search.js index 47cc0c03a6cfc5..f2a5d1806d89a2 100644 --- a/test/parallel/test-http-url.parse-search.js +++ b/test/parallel/test-http-url.parse-search.js @@ -9,7 +9,7 @@ function check(request) { assert.strictEqual(request.url, '/asdf?qwer=zxcv'); } -var server = http.createServer(function(request, response) { +const server = http.createServer(function(request, response) { // run the check function check.call(this, request, response); response.writeHead(200, {}); @@ -19,7 +19,7 @@ var server = http.createServer(function(request, response) { server.listen(0, function() { const port = this.address().port; - var testURL = url.parse(`http://localhost:${port}/asdf?qwer=zxcv`); + const testURL = url.parse(`http://localhost:${port}/asdf?qwer=zxcv`); // make the request http.request(testURL).end(); diff --git a/test/parallel/test-http-wget.js b/test/parallel/test-http-wget.js index 795f1794777cef..a633873c8bb16f 100644 --- a/test/parallel/test-http-wget.js +++ b/test/parallel/test-http-wget.js @@ -19,7 +19,7 @@ const http = require('http'); // content-length is not provided, that the connection is in fact // closed. -var server = http.createServer(function(req, res) { +const server = http.createServer(function(req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.write('hello '); res.write('world\n'); @@ -28,8 +28,8 @@ var server = http.createServer(function(req, res) { server.listen(0); server.on('listening', common.mustCall(function() { - var c = net.createConnection(this.address().port); - var server_response = ''; + const c = net.createConnection(this.address().port); + let server_response = ''; c.setEncoding('utf8'); diff --git a/test/parallel/test-http-write-callbacks.js b/test/parallel/test-http-write-callbacks.js index 59010256559144..3783dc305e39a7 100644 --- a/test/parallel/test-http-write-callbacks.js +++ b/test/parallel/test-http-write-callbacks.js @@ -4,13 +4,13 @@ const assert = require('assert'); const http = require('http'); -var serverEndCb = false; -var serverIncoming = ''; -var serverIncomingExpect = 'bazquuxblerg'; +let serverEndCb = false; +let serverIncoming = ''; +const serverIncomingExpect = 'bazquuxblerg'; -var clientEndCb = false; -var clientIncoming = ''; -var clientIncomingExpect = 'asdffoobar'; +let clientEndCb = false; +let clientIncoming = ''; +const clientIncomingExpect = 'asdffoobar'; process.on('exit', function() { assert(serverEndCb); @@ -21,7 +21,7 @@ process.on('exit', function() { }); // Verify that we get a callback when we do res.write(..., cb) -var server = http.createServer(function(req, res) { +const server = http.createServer(function(req, res) { res.statusCode = 400; res.end('Bad Request.\nMust send Expect:100-continue\n'); }); @@ -51,7 +51,7 @@ server.on('checkContinue', function(req, res) { }); server.listen(0, function() { - var req = http.request({ + const req = http.request({ port: this.address().port, method: 'PUT', headers: { 'expect': '100-continue' } diff --git a/test/parallel/test-http-write-empty-string.js b/test/parallel/test-http-write-empty-string.js index c659c47fa47bc6..69463fb3a50852 100644 --- a/test/parallel/test-http-write-empty-string.js +++ b/test/parallel/test-http-write-empty-string.js @@ -4,7 +4,7 @@ const assert = require('assert'); const http = require('http'); -var server = http.createServer(function(request, response) { +const server = http.createServer(function(request, response) { console.log('responding to ' + request.url); response.writeHead(200, {'Content-Type': 'text/plain'}); @@ -19,7 +19,7 @@ var server = http.createServer(function(request, response) { server.listen(0, common.mustCall(function() { http.get({ port: this.address().port }, common.mustCall(function(res) { - var response = ''; + let response = ''; assert.equal(200, res.statusCode); res.setEncoding('ascii'); diff --git a/test/parallel/test-http-write-head.js b/test/parallel/test-http-write-head.js index 9807dc6943f13c..12f5e00b0db493 100644 --- a/test/parallel/test-http-write-head.js +++ b/test/parallel/test-http-write-head.js @@ -6,11 +6,11 @@ const http = require('http'); // Verify that ServerResponse.writeHead() works as setHeader. // Issue 5036 on github. -var s = http.createServer(function(req, res) { +const s = http.createServer(function(req, res) { res.setHeader('test', '1'); // toLowerCase() is used on the name argument, so it must be a string. - var threw = false; + let threw = false; try { res.setHeader(0xf00, 'bar'); } catch (e) { diff --git a/test/parallel/test-http-zero-length-write.js b/test/parallel/test-http-zero-length-write.js index b446fd77860e83..63446e460471e4 100644 --- a/test/parallel/test-http-zero-length-write.js +++ b/test/parallel/test-http-zero-length-write.js @@ -9,10 +9,10 @@ const Stream = require('stream'); function getSrc() { // An old-style readable stream. // The Readable class prevents this behavior. - var src = new Stream(); + const src = new Stream(); // start out paused, just so we don't miss anything yet. - var paused = false; + let paused = false; src.pause = function() { paused = true; }; @@ -20,12 +20,12 @@ function getSrc() { paused = false; }; - var chunks = [ '', 'asdf', '', 'foo', '', 'bar', '' ]; - var interval = setInterval(function() { + const chunks = [ '', 'asdf', '', 'foo', '', 'bar', '' ]; + const interval = setInterval(function() { if (paused) return; - var chunk = chunks.shift(); + const chunk = chunks.shift(); if (chunk !== undefined) { src.emit('data', chunk); } else { @@ -38,10 +38,10 @@ function getSrc() { } -var expect = 'asdffoobar'; +const expect = 'asdffoobar'; -var server = http.createServer(function(req, res) { - var actual = ''; +const server = http.createServer(function(req, res) { + let actual = ''; req.setEncoding('utf8'); req.on('data', function(c) { actual += c; @@ -54,8 +54,8 @@ var server = http.createServer(function(req, res) { }); server.listen(0, function() { - var req = http.request({ port: this.address().port, method: 'POST' }); - var actual = ''; + const req = http.request({ port: this.address().port, method: 'POST' }); + let actual = ''; req.on('response', function(res) { res.setEncoding('utf8'); res.on('data', function(c) { diff --git a/test/parallel/test-http.js b/test/parallel/test-http.js index f755bca8bc74ec..a80a2b8856558b 100644 --- a/test/parallel/test-http.js +++ b/test/parallel/test-http.js @@ -4,10 +4,10 @@ const assert = require('assert'); const http = require('http'); const url = require('url'); -var responses_sent = 0; -var responses_recvd = 0; -var body0 = ''; -var body1 = ''; +let responses_sent = 0; +let responses_recvd = 0; +let body0 = ''; +let body1 = ''; const server = http.Server(function(req, res) { if (responses_sent === 0) { diff --git a/test/parallel/test-https-agent-disable-session-reuse.js b/test/parallel/test-https-agent-disable-session-reuse.js index 2f59118e3673ea..8e694a61b72a03 100644 --- a/test/parallel/test-https-agent-disable-session-reuse.js +++ b/test/parallel/test-https-agent-disable-session-reuse.js @@ -19,7 +19,7 @@ const options = { }; const clientSessions = []; -var serverRequests = 0; +let serverRequests = 0; const agent = new https.Agent({ maxCachedSessions: 0 @@ -29,7 +29,7 @@ const server = https.createServer(options, function(req, res) { serverRequests++; res.end('ok'); }).listen(0, function() { - var waiting = TOTAL_REQS; + let waiting = TOTAL_REQS; function request() { const options = { agent: agent, diff --git a/test/parallel/test-https-agent-servername.js b/test/parallel/test-https-agent-servername.js index 09a0f6bdd6b701..a321f7140396a3 100644 --- a/test/parallel/test-https-agent-servername.js +++ b/test/parallel/test-https-agent-servername.js @@ -9,14 +9,14 @@ if (!common.hasCrypto) { const https = require('https'); const fs = require('fs'); -var options = { +const options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem'), ca: fs.readFileSync(common.fixturesDir + '/keys/ca1-cert.pem') }; -var server = https.Server(options, function(req, res) { +const server = https.Server(options, function(req, res) { res.writeHead(200); res.end('hello world\n'); }); diff --git a/test/parallel/test-https-agent-sni.js b/test/parallel/test-https-agent-sni.js index 4174fd0b9c1fed..ca15dc3db3a88d 100644 --- a/test/parallel/test-https-agent-sni.js +++ b/test/parallel/test-https-agent-sni.js @@ -16,7 +16,7 @@ const options = { }; const TOTAL = 4; -var waiting = TOTAL; +let waiting = TOTAL; const server = https.Server(options, function(req, res) { if (--waiting === 0) server.close(); @@ -35,10 +35,10 @@ server.listen(0, function() { }); } - var agent = new https.Agent({ + const agent = new https.Agent({ maxSockets: 1 }); - for (var j = 0; j < TOTAL; j++) { + for (let j = 0; j < TOTAL; j++) { https.get({ agent: agent, diff --git a/test/parallel/test-https-agent.js b/test/parallel/test-https-agent.js index 221ed2bbd2fe49..392bdcbf033000 100644 --- a/test/parallel/test-https-agent.js +++ b/test/parallel/test-https-agent.js @@ -22,15 +22,15 @@ const server = https.Server(options, function(req, res) { }); -var responses = 0; +let responses = 0; const N = 4; const M = 4; server.listen(0, function() { - for (var i = 0; i < N; i++) { + for (let i = 0; i < N; i++) { setTimeout(function() { - for (var j = 0; j < M; j++) { + for (let j = 0; j < M; j++) { https.get({ path: '/', port: server.address().port, diff --git a/test/parallel/test-https-byteswritten.js b/test/parallel/test-https-byteswritten.js index 51f59bc311d0b1..cdea4d1ee930f3 100644 --- a/test/parallel/test-https-byteswritten.js +++ b/test/parallel/test-https-byteswritten.js @@ -9,14 +9,14 @@ if (!common.hasCrypto) { } const https = require('https'); -var options = { +const options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }; -var body = 'hello world\n'; +const body = 'hello world\n'; -var httpsServer = https.createServer(options, function(req, res) { +const httpsServer = https.createServer(options, function(req, res) { res.on('finish', function() { assert.strictEqual(typeof req.connection.bytesWritten, 'number'); assert(req.connection.bytesWritten > 0); diff --git a/test/parallel/test-https-client-checkServerIdentity.js b/test/parallel/test-https-client-checkServerIdentity.js index 82f03320c4fb5c..688c7e22706e0e 100644 --- a/test/parallel/test-https-client-checkServerIdentity.js +++ b/test/parallel/test-https-client-checkServerIdentity.js @@ -11,12 +11,12 @@ const https = require('https'); const fs = require('fs'); const path = require('path'); -var options = { +const options = { key: fs.readFileSync(path.join(common.fixturesDir, 'keys/agent3-key.pem')), cert: fs.readFileSync(path.join(common.fixturesDir, 'keys/agent3-cert.pem')) }; -var server = https.createServer(options, common.mustCall(function(req, res) { +const server = https.createServer(options, common.mustCall(function(req, res) { res.writeHead(200); res.end(); req.resume(); @@ -25,7 +25,7 @@ var server = https.createServer(options, common.mustCall(function(req, res) { }); function authorized() { - var req = https.request({ + const req = https.request({ port: server.address().port, rejectUnauthorized: true, ca: [fs.readFileSync(path.join(common.fixturesDir, 'keys/ca2-cert.pem'))] @@ -37,7 +37,7 @@ function authorized() { } function override() { - var options = { + const options = { port: server.address().port, rejectUnauthorized: true, ca: [fs.readFileSync(path.join(common.fixturesDir, 'keys/ca2-cert.pem'))], @@ -46,7 +46,7 @@ function override() { } }; options.agent = new https.Agent(options); - var req = https.request(options, function(res) { + const req = https.request(options, function(res) { assert(req.socket.authorized); server.close(); }); diff --git a/test/parallel/test-https-client-get-url.js b/test/parallel/test-https-client-get-url.js index 6852967848a16b..1f4f6ff748b410 100644 --- a/test/parallel/test-https-client-get-url.js +++ b/test/parallel/test-https-client-get-url.js @@ -15,12 +15,12 @@ const fs = require('fs'); const url = require('url'); const URL = url.URL; -var options = { +const options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }; -var server = https.createServer(options, common.mustCall(function(req, res) { +const server = https.createServer(options, common.mustCall(function(req, res) { assert.equal('GET', req.method); assert.equal('/foo?bar', req.url); res.writeHead(200, {'Content-Type': 'text/plain'}); diff --git a/test/parallel/test-https-client-reject.js b/test/parallel/test-https-client-reject.js index 32626b0a05f946..92bbabe8b3be90 100644 --- a/test/parallel/test-https-client-reject.js +++ b/test/parallel/test-https-client-reject.js @@ -11,12 +11,12 @@ const https = require('https'); const fs = require('fs'); const path = require('path'); -var options = { +const options = { key: fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')), cert: fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')) }; -var server = https.createServer(options, common.mustCall(function(req, res) { +const server = https.createServer(options, common.mustCall(function(req, res) { res.writeHead(200); res.end(); req.resume(); @@ -25,7 +25,7 @@ var server = https.createServer(options, common.mustCall(function(req, res) { }); function unauthorized() { - var req = https.request({ + const req = https.request({ port: server.address().port, rejectUnauthorized: false }, function(res) { @@ -40,11 +40,11 @@ function unauthorized() { } function rejectUnauthorized() { - var options = { + const options = { port: server.address().port }; options.agent = new https.Agent(options); - var req = https.request(options, common.fail); + const req = https.request(options, common.fail); req.on('error', function(err) { authorized(); }); @@ -52,12 +52,12 @@ function rejectUnauthorized() { } function authorized() { - var options = { + const options = { port: server.address().port, ca: [fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem'))] }; options.agent = new https.Agent(options); - var req = https.request(options, function(res) { + const req = https.request(options, function(res) { res.resume(); assert(req.socket.authorized); server.close(); diff --git a/test/parallel/test-https-client-resume.js b/test/parallel/test-https-client-resume.js index 58a06c70e2a5da..79e1a716bd77cf 100644 --- a/test/parallel/test-https-client-resume.js +++ b/test/parallel/test-https-client-resume.js @@ -14,21 +14,21 @@ const https = require('https'); const tls = require('tls'); const fs = require('fs'); -var options = { +const options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem') }; // create server -var server = https.createServer(options, common.mustCall(function(req, res) { +const server = https.createServer(options, common.mustCall(function(req, res) { res.end('Goodbye'); }, 2)); // start listening server.listen(0, function() { - var session1 = null; - var client1 = tls.connect({ + let session1 = null; + const client1 = tls.connect({ port: this.address().port, rejectUnauthorized: false }, function() { @@ -43,13 +43,13 @@ server.listen(0, function() { client1.on('close', function() { console.log('close1'); - var opts = { + const opts = { port: server.address().port, rejectUnauthorized: false, session: session1 }; - var client2 = tls.connect(opts, function() { + const client2 = tls.connect(opts, function() { console.log('connect2'); assert.ok(client2.isSessionReused(), 'Session *should* be reused.'); client2.write('GET / HTTP/1.0\r\n' + diff --git a/test/parallel/test-https-close.js b/test/parallel/test-https-close.js index f77726ceb68bf9..cf950f29d6f8ad 100644 --- a/test/parallel/test-https-close.js +++ b/test/parallel/test-https-close.js @@ -13,17 +13,17 @@ const options = { cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }; -var connections = {}; +const connections = {}; -var server = https.createServer(options, function(req, res) { - var interval = setInterval(function() { +const server = https.createServer(options, function(req, res) { + const interval = setInterval(function() { res.write('data'); }, 1000); interval.unref(); }); server.on('connection', function(connection) { - var key = connection.remoteAddress + ':' + connection.remotePort; + const key = connection.remoteAddress + ':' + connection.remotePort; connection.on('close', function() { delete connections[key]; }); @@ -33,14 +33,14 @@ server.on('connection', function(connection) { function shutdown() { server.close(common.mustCall(function() {})); - for (var key in connections) { + for (const key in connections) { connections[key].destroy(); delete connections[key]; } } server.listen(0, function() { - var requestOptions = { + const requestOptions = { hostname: '127.0.0.1', port: this.address().port, path: '/', @@ -48,7 +48,7 @@ server.listen(0, function() { rejectUnauthorized: false }; - var req = https.request(requestOptions, function(res) { + const req = https.request(requestOptions, function(res) { res.on('data', function(d) {}); setImmediate(shutdown); }); diff --git a/test/parallel/test-https-connecting-to-http.js b/test/parallel/test-https-connecting-to-http.js index 3bfab5f626efd2..ae8507f99cbc00 100644 --- a/test/parallel/test-https-connecting-to-http.js +++ b/test/parallel/test-https-connecting-to-http.js @@ -10,10 +10,10 @@ if (!common.hasCrypto) { } const https = require('https'); -var server = http.createServer(common.fail); +const server = http.createServer(common.fail); server.listen(0, common.mustCall(function() { - var req = https.get({ port: this.address().port }, common.fail); + const req = https.get({ port: this.address().port }, common.fail); req.on('error', common.mustCall(function(e) { console.log('Got expected error: ', e.message); diff --git a/test/parallel/test-https-drain.js b/test/parallel/test-https-drain.js index 0f6501e8ef5603..0b18795078fd1f 100644 --- a/test/parallel/test-https-drain.js +++ b/test/parallel/test-https-drain.js @@ -11,28 +11,28 @@ const https = require('https'); const fs = require('fs'); const path = require('path'); -var options = { +const options = { key: fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')), cert: fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')) }; -var bufSize = 1024 * 1024; -var sent = 0; -var received = 0; +const bufSize = 1024 * 1024; +let sent = 0; +let received = 0; -var server = https.createServer(options, function(req, res) { +const server = https.createServer(options, function(req, res) { res.writeHead(200); req.pipe(res); }); server.listen(0, function() { - var resumed = false; - var req = https.request({ + let resumed = false; + const req = https.request({ method: 'POST', port: this.address().port, rejectUnauthorized: false }, function(res) { - var timer; + let timer; res.pause(); console.error('paused'); send(); diff --git a/test/parallel/test-https-eof-for-eom.js b/test/parallel/test-https-eof-for-eom.js index 81d4e978a87672..d5e896c7695cfd 100644 --- a/test/parallel/test-https-eof-for-eom.js +++ b/test/parallel/test-https-eof-for-eom.js @@ -19,13 +19,13 @@ const tls = require('tls'); const fs = require('fs'); -var options = { +const options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }; -var server = tls.Server(options, function(socket) { +const server = tls.Server(options, function(socket) { console.log('2) Server got request'); socket.write('HTTP/1.1 200 OK\r\n' + 'Date: Tue, 15 Feb 2011 22:14:54 GMT\r\n' + @@ -52,7 +52,7 @@ server.listen(0, common.mustCall(function() { port: this.address().port, rejectUnauthorized: false }, common.mustCall(function(res) { - var bodyBuffer = ''; + let bodyBuffer = ''; server.close(); console.log('3) Client got response headers.'); diff --git a/test/parallel/test-https-foafssl.js b/test/parallel/test-https-foafssl.js index 6be850a11ed633..f1b8d442e27893 100644 --- a/test/parallel/test-https-foafssl.js +++ b/test/parallel/test-https-foafssl.js @@ -18,7 +18,7 @@ if (!common.hasCrypto) { } const https = require('https'); -var options = { +const options = { key: fs.readFileSync(common.fixturesDir + '/agent.key'), cert: fs.readFileSync(common.fixturesDir + '/agent.crt'), requestCert: true @@ -34,11 +34,11 @@ const modulus = 'A6F44A9C25791431214F5C87AF9E040177A8BB89AC803F7E09BBC3A5519F' + 'EBDAF1191F4A4E26D71879C4C7867B62FCD508E8CE66E82D128A71E91580' + '9FCF44E8DE774067F1DE5D70B9C03687'; -var CRLF = '\r\n'; -var body = 'hello world\n'; -var cert; +const CRLF = '\r\n'; +const body = 'hello world\n'; +let cert; -var server = https.createServer(options, common.mustCall(function(req, res) { +const server = https.createServer(options, common.mustCall(function(req, res) { console.log('got request'); cert = req.connection.getPeerCertificate(); @@ -51,21 +51,21 @@ var server = https.createServer(options, common.mustCall(function(req, res) { })); server.listen(0, function() { - var args = ['s_client', - '-quiet', - '-connect', `127.0.0.1:${this.address().port}`, - '-cert', join(common.fixturesDir, 'foafssl.crt'), - '-key', join(common.fixturesDir, 'foafssl.key')]; + const args = ['s_client', + '-quiet', + '-connect', `127.0.0.1:${this.address().port}`, + '-cert', join(common.fixturesDir, 'foafssl.crt'), + '-key', join(common.fixturesDir, 'foafssl.key')]; // for the performance and stability issue in s_client on Windows if (common.isWindows) args.push('-no_rand_screen'); - var client = spawn(common.opensslCli, args); + const client = spawn(common.opensslCli, args); client.stdout.on('data', function(data) { - var message = data.toString(); - var contents = message.split(CRLF + CRLF).pop(); + const message = data.toString(); + const contents = message.split(CRLF + CRLF).pop(); assert.equal(body, contents); server.close(); }); diff --git a/test/parallel/test-https-host-headers.js b/test/parallel/test-https-host-headers.js index 25de4435ea3b28..190f15f29a8078 100644 --- a/test/parallel/test-https-host-headers.js +++ b/test/parallel/test-https-host-headers.js @@ -37,7 +37,7 @@ testHttps(); function testHttps() { - var counter = 0; + let counter = 0; function cb(res) { counter--; diff --git a/test/parallel/test-https-localaddress-bind-error.js b/test/parallel/test-https-localaddress-bind-error.js index 2382d59a7c36af..662d6f080a0fff 100644 --- a/test/parallel/test-https-localaddress-bind-error.js +++ b/test/parallel/test-https-localaddress-bind-error.js @@ -8,14 +8,14 @@ if (!common.hasCrypto) { } const https = require('https'); -var options = { +const options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }; -var invalidLocalAddress = '1.2.3.4'; +const invalidLocalAddress = '1.2.3.4'; -var server = https.createServer(options, function(req, res) { +const server = https.createServer(options, function(req, res) { console.log('Connect from: ' + req.connection.remoteAddress); req.on('end', function() { diff --git a/test/parallel/test-https-localaddress.js b/test/parallel/test-https-localaddress.js index 22e96eb4675417..78583b38ecf1cf 100644 --- a/test/parallel/test-https-localaddress.js +++ b/test/parallel/test-https-localaddress.js @@ -14,12 +14,12 @@ if (!common.hasMultiLocalhost()) { return; } -var options = { +const options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }; -var server = https.createServer(options, function(req, res) { +const server = https.createServer(options, function(req, res) { console.log('Connect from: ' + req.connection.remoteAddress); assert.equal('127.0.0.2', req.connection.remoteAddress); @@ -31,7 +31,7 @@ var server = https.createServer(options, function(req, res) { }); server.listen(0, '127.0.0.1', function() { - var options = { + const options = { host: 'localhost', port: this.address().port, path: '/', @@ -40,7 +40,7 @@ server.listen(0, '127.0.0.1', function() { rejectUnauthorized: false }; - var req = https.request(options, function(res) { + const req = https.request(options, function(res) { res.on('end', function() { server.close(); process.exit(); diff --git a/test/parallel/test-https-pfx.js b/test/parallel/test-https-pfx.js index 8d0f51b6a51c82..c30bbc0848d137 100644 --- a/test/parallel/test-https-pfx.js +++ b/test/parallel/test-https-pfx.js @@ -9,9 +9,9 @@ if (!common.hasCrypto) { } const https = require('https'); -var pfx = fs.readFileSync(common.fixturesDir + '/test_cert.pfx'); +const pfx = fs.readFileSync(common.fixturesDir + '/test_cert.pfx'); -var options = { +const options = { host: '127.0.0.1', port: undefined, path: '/', @@ -21,7 +21,7 @@ var options = { rejectUnauthorized: false }; -var server = https.createServer(options, function(req, res) { +const server = https.createServer(options, function(req, res) { assert.equal(req.socket.authorized, false); // not a client cert assert.equal(req.socket.authorizationError, 'DEPTH_ZERO_SELF_SIGNED_CERT'); res.writeHead(200); @@ -32,7 +32,7 @@ server.listen(0, options.host, common.mustCall(function() { options.port = this.address().port; https.get(options, common.mustCall(function(res) { - var data = ''; + let data = ''; res.on('data', function(data_) { data += data_; }); res.on('end', common.mustCall(function() { diff --git a/test/parallel/test-https-req-split.js b/test/parallel/test-https-req-split.js index d0d20a73ad16df..4298abe5eff43d 100644 --- a/test/parallel/test-https-req-split.js +++ b/test/parallel/test-https-req-split.js @@ -12,7 +12,7 @@ const https = require('https'); const tls = require('tls'); const fs = require('fs'); -var options = { +const options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }; @@ -20,7 +20,7 @@ var options = { // Force splitting incoming data tls.SLAB_BUFFER_SIZE = 1; -var server = https.createServer(options); +const server = https.createServer(options); server.on('upgrade', common.mustCall(function(req, socket, upgrade) { socket.on('data', function(data) { throw new Error('Unexpected data: ' + data); @@ -29,7 +29,7 @@ server.on('upgrade', common.mustCall(function(req, socket, upgrade) { })); server.listen(0, function() { - var req = https.request({ + const req = https.request({ host: '127.0.0.1', port: this.address().port, agent: false, diff --git a/test/parallel/test-https-resume-after-renew.js b/test/parallel/test-https-resume-after-renew.js index 72d77104255beb..cc712b312485b2 100644 --- a/test/parallel/test-https-resume-after-renew.js +++ b/test/parallel/test-https-resume-after-renew.js @@ -9,24 +9,25 @@ const fs = require('fs'); const https = require('https'); const crypto = require('crypto'); -var options = { +const options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem'), ca: fs.readFileSync(common.fixturesDir + '/keys/ca1-cert.pem') }; -var server = https.createServer(options, function(req, res) { +const server = https.createServer(options, function(req, res) { res.end('hello'); }); -var aes = Buffer.alloc(16, 'S'); -var hmac = Buffer.alloc(16, 'H'); +const aes = Buffer.alloc(16, 'S'); +const hmac = Buffer.alloc(16, 'H'); server._sharedCreds.context.enableTicketKeyCallback(); server._sharedCreds.context.onticketkeycallback = function(name, iv, enc) { + let newName, newIV; if (enc) { - var newName = Buffer.alloc(16, 'A'); - var newIV = crypto.randomBytes(16); + newName = Buffer.alloc(16, 'A'); + newIV = crypto.randomBytes(16); } else { // Renew return [ 2, hmac, aes ]; @@ -36,7 +37,7 @@ server._sharedCreds.context.onticketkeycallback = function(name, iv, enc) { }; server.listen(0, function() { - var addr = this.address(); + const addr = this.address(); function doReq(callback) { https.request({ diff --git a/test/parallel/test-https-set-timeout-server.js b/test/parallel/test-https-set-timeout-server.js index fbf16a0ce32268..4cf999667d7384 100644 --- a/test/parallel/test-https-set-timeout-server.js +++ b/test/parallel/test-https-set-timeout-server.js @@ -11,9 +11,9 @@ const https = require('https'); const tls = require('tls'); const fs = require('fs'); -var tests = []; +const tests = []; -var serverOptions = { +const serverOptions = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }; @@ -25,7 +25,7 @@ function test(fn) { } function run() { - var fn = tests.shift(); + const fn = tests.shift(); if (fn) { console.log('# %s', fn.name); fn(run); @@ -35,11 +35,11 @@ function run() { } test(function serverTimeout(cb) { - var server = https.createServer(serverOptions, function(req, res) { + const server = https.createServer(serverOptions, function(req, res) { // just do nothing, we should get a timeout event. }); server.listen(0, common.mustCall(function() { - var s = server.setTimeout(50, common.mustCall(function(socket) { + const s = server.setTimeout(50, common.mustCall(function(socket) { socket.destroy(); server.close(); cb(); @@ -62,9 +62,9 @@ test(function serverRequestTimeout(cb) { })); } - var server = https.createServer(serverOptions, common.mustCall(handler)); + const server = https.createServer(serverOptions, common.mustCall(handler)); server.listen(0, function() { - var req = https.request({ + const req = https.request({ port: this.address().port, method: 'POST', rejectUnauthorized: false @@ -85,7 +85,7 @@ test(function serverResponseTimeout(cb) { })); } - var server = https.createServer(serverOptions, common.mustCall(handler)); + const server = https.createServer(serverOptions, common.mustCall(handler)); server.listen(0, function() { https.get({ port: this.address().port, @@ -100,7 +100,7 @@ test(function serverRequestNotTimeoutAfterEnd(cb) { req.setTimeout(50, common.fail); res.on('timeout', common.mustCall(function(socket) {})); } - var server = https.createServer(serverOptions, common.mustCall(handler)); + const server = https.createServer(serverOptions, common.mustCall(handler)); server.on('timeout', function(socket) { socket.destroy(); server.close(); @@ -115,11 +115,11 @@ test(function serverRequestNotTimeoutAfterEnd(cb) { }); test(function serverResponseTimeoutWithPipeline(cb) { - var caughtTimeout = ''; + let caughtTimeout = ''; process.on('exit', function() { assert.equal(caughtTimeout, '/2'); }); - var server = https.createServer(serverOptions, function(req, res) { + const server = https.createServer(serverOptions, function(req, res) { res.setTimeout(50, function() { caughtTimeout += req.url; }); @@ -131,12 +131,12 @@ test(function serverResponseTimeoutWithPipeline(cb) { cb(); }); server.listen(0, function() { - var options = { + const options = { port: this.address().port, allowHalfOpen: true, rejectUnauthorized: false }; - var c = tls.connect(options, function() { + const c = tls.connect(options, function() { c.write('GET /1 HTTP/1.1\r\nHost: localhost\r\n\r\n'); c.write('GET /2 HTTP/1.1\r\nHost: localhost\r\n\r\n'); c.write('GET /3 HTTP/1.1\r\nHost: localhost\r\n\r\n'); @@ -145,19 +145,19 @@ test(function serverResponseTimeoutWithPipeline(cb) { }); test(function idleTimeout(cb) { - var server = https.createServer(serverOptions, - common.mustCall(function(req, res) { - req.on('timeout', common.fail); - res.on('timeout', common.fail); - res.end(); - })); + const server = https.createServer(serverOptions, + common.mustCall(function(req, res) { + req.on('timeout', common.fail); + res.on('timeout', common.fail); + res.end(); + })); server.setTimeout(50, common.mustCall(function(socket) { socket.destroy(); server.close(); cb(); })); server.listen(0, function() { - var options = { + const options = { port: this.address().port, allowHalfOpen: true, rejectUnauthorized: false diff --git a/test/parallel/test-https-socket-options.js b/test/parallel/test-https-socket-options.js index 337cc264a2587c..05137b35c437ff 100644 --- a/test/parallel/test-https-socket-options.js +++ b/test/parallel/test-https-socket-options.js @@ -11,16 +11,16 @@ const fs = require('fs'); const http = require('http'); -var options = { +const options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }; -var body = 'hello world\n'; +const body = 'hello world\n'; // Try first with http server -var server_http = http.createServer(function(req, res) { +const server_http = http.createServer(function(req, res) { console.log('got HTTP request'); res.writeHead(200, { 'content-type': 'text/plain' }); res.end(body); @@ -28,7 +28,7 @@ var server_http = http.createServer(function(req, res) { server_http.listen(0, function() { - var req = http.request({ + const req = http.request({ port: this.address().port, rejectUnauthorized: false }, function(res) { @@ -45,14 +45,14 @@ server_http.listen(0, function() { // Then try https server (requires functions to be // mirroed in tls.js's CryptoStream) -var server_https = https.createServer(options, function(req, res) { +const server_https = https.createServer(options, function(req, res) { console.log('got HTTPS request'); res.writeHead(200, { 'content-type': 'text/plain' }); res.end(body); }); server_https.listen(0, function() { - var req = https.request({ + const req = https.request({ port: this.address().port, rejectUnauthorized: false }, function(res) { diff --git a/test/parallel/test-https-timeout-server-2.js b/test/parallel/test-https-timeout-server-2.js index a17abec5398ada..8729af1ae8b4ba 100644 --- a/test/parallel/test-https-timeout-server-2.js +++ b/test/parallel/test-https-timeout-server-2.js @@ -12,15 +12,15 @@ const https = require('https'); const tls = require('tls'); const fs = require('fs'); -var options = { +const options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }; -var server = https.createServer(options, common.fail); +const server = https.createServer(options, common.fail); server.on('secureConnection', function(cleartext) { - var s = cleartext.setTimeout(50, function() { + const s = cleartext.setTimeout(50, function() { cleartext.destroy(); server.close(); }); diff --git a/test/parallel/test-icu-transcode.js b/test/parallel/test-icu-transcode.js index 463b2fca9188ba..0766f8c6d460d8 100644 --- a/test/parallel/test-icu-transcode.js +++ b/test/parallel/test-icu-transcode.js @@ -23,7 +23,7 @@ const tests = { for (const test in tests) { const dest = buffer.transcode(orig, 'utf8', test); assert.strictEqual(dest.length, tests[test].length); - for (var n = 0; n < tests[test].length; n++) + for (let n = 0; n < tests[test].length; n++) assert.strictEqual(dest[n], tests[test][n]); } diff --git a/test/parallel/test-listen-fd-cluster.js b/test/parallel/test-listen-fd-cluster.js index 001eb007f2532c..de1fbed7b56aff 100644 --- a/test/parallel/test-listen-fd-cluster.js +++ b/test/parallel/test-listen-fd-cluster.js @@ -22,7 +22,7 @@ switch (process.argv[2]) { case 'worker': return worker(); } -var ok; +let ok; process.on('exit', function() { assert.ok(ok); @@ -41,7 +41,7 @@ test(function(parent, port) { port: port, path: '/', }).on('response', function(res) { - var s = ''; + let s = ''; res.on('data', function(c) { s += c.toString(); }); @@ -61,7 +61,7 @@ test(function(parent, port) { function test(cb) { console.error('about to listen in parent'); - var server = net.createServer(function(conn) { + const server = net.createServer(function(conn) { console.error('connection on parent'); conn.end('hello from parent\n'); }).listen(0, function() { @@ -69,7 +69,7 @@ function test(cb) { console.error('server listening on %d', port); const spawn = require('child_process').spawn; - var master = spawn(process.execPath, [__filename, 'master'], { + const master = spawn(process.execPath, [__filename, 'master'], { stdio: [ 0, 'pipe', 2, server._handle, 'ipc' ], detached: true }); @@ -100,7 +100,7 @@ function master() { cluster.setupMaster({ args: [ 'worker' ] }); - var worker = cluster.fork(); + const worker = cluster.fork(); worker.on('message', function(msg) { if (msg === 'worker ready') { process.send('started worker'); diff --git a/test/parallel/test-listen-fd-detached-inherit.js b/test/parallel/test-listen-fd-detached-inherit.js index 9699232d2e0088..2ac4d83dba6691 100644 --- a/test/parallel/test-listen-fd-detached-inherit.js +++ b/test/parallel/test-listen-fd-detached-inherit.js @@ -23,24 +23,24 @@ switch (process.argv[2]) { // concurrency in HTTP servers! Use the cluster module, or if you want // a more low-level approach, use child process IPC manually. function test() { - var parent = spawn(process.execPath, [__filename, 'parent'], { + const parent = spawn(process.execPath, [__filename, 'parent'], { stdio: [ 0, 'pipe', 2 ] }); - var json = ''; + let json = ''; parent.stdout.on('data', function(c) { json += c.toString(); if (json.indexOf('\n') !== -1) next(); }); function next() { console.error('output from parent = %s', json); - var child = JSON.parse(json); + const child = JSON.parse(json); // now make sure that we can request to the child, then kill it. http.get({ server: 'localhost', port: child.port, path: '/', }).on('response', function(res) { - var s = ''; + let s = ''; res.on('data', function(c) { s += c.toString(); }); @@ -62,13 +62,13 @@ function test() { // Listen on port, and then pass the handle to the detached child. // Then output the child's pid, and immediately exit. function parent() { - var server = net.createServer(function(conn) { + const server = net.createServer(function(conn) { conn.end('HTTP/1.1 403 Forbidden\r\n\r\nI got problems.\r\n'); throw new Error('Should not see connections on parent'); }).listen(0, function() { console.error('server listening on %d', this.address().port); - var child = spawn(process.execPath, [__filename, 'child'], { + const child = spawn(process.execPath, [__filename, 'child'], { stdio: [ 0, 1, 2, server._handle ], detached: true }); diff --git a/test/parallel/test-listen-fd-detached.js b/test/parallel/test-listen-fd-detached.js index 4ec3654a2166cf..1194d001610fce 100644 --- a/test/parallel/test-listen-fd-detached.js +++ b/test/parallel/test-listen-fd-detached.js @@ -23,24 +23,24 @@ switch (process.argv[2]) { // concurrency in HTTP servers! Use the cluster module, or if you want // a more low-level approach, use child process IPC manually. function test() { - var parent = spawn(process.execPath, [__filename, 'parent'], { + const parent = spawn(process.execPath, [__filename, 'parent'], { stdio: [ 0, 'pipe', 2 ] }); - var json = ''; + let json = ''; parent.stdout.on('data', function(c) { json += c.toString(); if (json.indexOf('\n') !== -1) next(); }); function next() { console.error('output from parent = %s', json); - var child = JSON.parse(json); + const child = JSON.parse(json); // now make sure that we can request to the child, then kill it. http.get({ server: 'localhost', port: child.port, path: '/', }).on('response', function(res) { - var s = ''; + let s = ''; res.on('data', function(c) { s += c.toString(); }); @@ -60,14 +60,14 @@ function test() { } function parent() { - var server = net.createServer(function(conn) { + const server = net.createServer(function(conn) { console.error('connection on parent'); conn.end('hello from parent\n'); }).listen(0, function() { console.error('server listening on %d', this.address().port); const spawn = require('child_process').spawn; - var child = spawn(process.execPath, [__filename, 'child'], { + const child = spawn(process.execPath, [__filename, 'child'], { stdio: [ 'ignore', 'ignore', 'ignore', server._handle ], detached: true }); diff --git a/test/parallel/test-listen-fd-server.js b/test/parallel/test-listen-fd-server.js index 87a624f7137562..60aa8717a8c24e 100644 --- a/test/parallel/test-listen-fd-server.js +++ b/test/parallel/test-listen-fd-server.js @@ -13,7 +13,7 @@ switch (process.argv[2]) { case 'child': return child(); } -var ok; +let ok; process.on('exit', function() { assert.ok(ok); @@ -31,7 +31,7 @@ test(function(child, port) { port: port, path: '/', }).on('response', function(res) { - var s = ''; + let s = ''; res.on('data', function(c) { s += c.toString(); }); @@ -67,7 +67,7 @@ function child() { } function test(cb) { - var server = net.createServer(function(conn) { + const server = net.createServer(function(conn) { console.error('connection on parent'); conn.end('hello from parent\n'); }).listen(0, function() { @@ -75,7 +75,7 @@ function test(cb) { console.error('server listening on %d', port); const spawn = require('child_process').spawn; - var child = spawn(process.execPath, [__filename, 'child'], { + const child = spawn(process.execPath, [__filename, 'child'], { stdio: [ 0, 1, 2, server._handle, 'ipc' ] }); diff --git a/test/parallel/test-memory-usage-emfile.js b/test/parallel/test-memory-usage-emfile.js index ce74dd3be3c4e5..09ab270b70fa21 100644 --- a/test/parallel/test-memory-usage-emfile.js +++ b/test/parallel/test-memory-usage-emfile.js @@ -4,10 +4,10 @@ const assert = require('assert'); const fs = require('fs'); -var files = []; +const files = []; while (files.length < 256) files.push(fs.openSync(__filename, 'r')); -var r = process.memoryUsage(); +const r = process.memoryUsage(); assert.equal(true, r['rss'] > 0); diff --git a/test/parallel/test-memory-usage.js b/test/parallel/test-memory-usage.js index 400e17aa008a90..cba3f9a5172a07 100644 --- a/test/parallel/test-memory-usage.js +++ b/test/parallel/test-memory-usage.js @@ -2,7 +2,7 @@ require('../common'); const assert = require('assert'); -var r = process.memoryUsage(); +const r = process.memoryUsage(); assert.ok(r.rss > 0); assert.ok(r.heapTotal > 0); assert.ok(r.heapUsed > 0); diff --git a/test/parallel/test-microtask-queue-integration-domain.js b/test/parallel/test-microtask-queue-integration-domain.js index 2e865041dfc209..7110af7648ae8a 100644 --- a/test/parallel/test-microtask-queue-integration-domain.js +++ b/test/parallel/test-microtask-queue-integration-domain.js @@ -9,21 +9,21 @@ const assert = require('assert'); // removed. require('domain'); -var implementations = [ +const implementations = [ function(fn) { Promise.resolve().then(fn); } ]; -var expected = 0; -var done = 0; +let expected = 0; +let done = 0; process.on('exit', function() { assert.equal(done, expected); }); function test(scheduleMicrotask) { - var nextTickCalled = false; + let nextTickCalled = false; expected++; scheduleMicrotask(function() { diff --git a/test/parallel/test-microtask-queue-integration.js b/test/parallel/test-microtask-queue-integration.js index f4f518caa30c93..d212bbae96b001 100644 --- a/test/parallel/test-microtask-queue-integration.js +++ b/test/parallel/test-microtask-queue-integration.js @@ -2,21 +2,21 @@ require('../common'); const assert = require('assert'); -var implementations = [ +const implementations = [ function(fn) { Promise.resolve().then(fn); } ]; -var expected = 0; -var done = 0; +let expected = 0; +let done = 0; process.on('exit', function() { assert.equal(done, expected); }); function test(scheduleMicrotask) { - var nextTickCalled = false; + let nextTickCalled = false; expected++; scheduleMicrotask(function() { diff --git a/test/parallel/test-microtask-queue-run-domain.js b/test/parallel/test-microtask-queue-run-domain.js index 57ba4543a3f6cd..7d34ec829a003c 100644 --- a/test/parallel/test-microtask-queue-run-domain.js +++ b/test/parallel/test-microtask-queue-run-domain.js @@ -13,7 +13,7 @@ function enqueueMicrotask(fn) { Promise.resolve().then(fn); } -var done = 0; +let done = 0; process.on('exit', function() { assert.equal(done, 2); @@ -29,7 +29,7 @@ setTimeout(function() { // no nextTick, microtask with nextTick setTimeout(function() { - var called = false; + let called = false; enqueueMicrotask(function() { process.nextTick(function() { diff --git a/test/parallel/test-microtask-queue-run-immediate-domain.js b/test/parallel/test-microtask-queue-run-immediate-domain.js index 5241b6c4a91e9d..e09087f74e32a9 100644 --- a/test/parallel/test-microtask-queue-run-immediate-domain.js +++ b/test/parallel/test-microtask-queue-run-immediate-domain.js @@ -13,7 +13,7 @@ function enqueueMicrotask(fn) { Promise.resolve().then(fn); } -var done = 0; +let done = 0; process.on('exit', function() { assert.equal(done, 2); @@ -29,7 +29,7 @@ setImmediate(function() { // no nextTick, microtask with nextTick setImmediate(function() { - var called = false; + let called = false; enqueueMicrotask(function() { process.nextTick(function() { diff --git a/test/parallel/test-microtask-queue-run-immediate.js b/test/parallel/test-microtask-queue-run-immediate.js index b21af670ffdb9d..c5ed6c6dcbc1ae 100644 --- a/test/parallel/test-microtask-queue-run-immediate.js +++ b/test/parallel/test-microtask-queue-run-immediate.js @@ -6,7 +6,7 @@ function enqueueMicrotask(fn) { Promise.resolve().then(fn); } -var done = 0; +let done = 0; process.on('exit', function() { assert.equal(done, 2); @@ -22,7 +22,7 @@ setImmediate(function() { // no nextTick, microtask with nextTick setImmediate(function() { - var called = false; + let called = false; enqueueMicrotask(function() { process.nextTick(function() { diff --git a/test/parallel/test-microtask-queue-run.js b/test/parallel/test-microtask-queue-run.js index 3150c9ebda514a..71e1fbedbaecbd 100644 --- a/test/parallel/test-microtask-queue-run.js +++ b/test/parallel/test-microtask-queue-run.js @@ -6,7 +6,7 @@ function enqueueMicrotask(fn) { Promise.resolve().then(fn); } -var done = 0; +let done = 0; process.on('exit', function() { assert.equal(done, 2); @@ -22,7 +22,7 @@ setTimeout(function() { // no nextTick, microtask with nextTick setTimeout(function() { - var called = false; + let called = false; enqueueMicrotask(function() { process.nextTick(function() { diff --git a/test/parallel/test-module-globalpaths-nodepath.js b/test/parallel/test-module-globalpaths-nodepath.js index 66511e51eddb11..ec90f1a3e2c868 100644 --- a/test/parallel/test-module-globalpaths-nodepath.js +++ b/test/parallel/test-module-globalpaths-nodepath.js @@ -3,8 +3,8 @@ const common = require('../common'); const assert = require('assert'); const mod = require('module'); -var partA, partB; -var partC = ''; +let partA, partB; +const partC = ''; if (common.isWindows) { partA = 'C:\\Users\\Rocko Artischocko\\AppData\\Roaming\\npm'; diff --git a/test/parallel/test-module-loading-error.js b/test/parallel/test-module-loading-error.js index b8454f2ae9ffb0..d78f61de60fa14 100644 --- a/test/parallel/test-module-loading-error.js +++ b/test/parallel/test-module-loading-error.js @@ -4,13 +4,13 @@ const assert = require('assert'); console.error('load test-module-loading-error.js'); -var error_desc = { +const error_desc = { win32: ['%1 is not a valid Win32 application'], linux: ['file too short', 'Exec format error'], sunos: ['unknown file type', 'not an ELF file'], darwin: ['file too short'] }; -var dlerror_msg = error_desc[process.platform]; +const dlerror_msg = error_desc[process.platform]; if (!dlerror_msg) { common.skip('platform not supported.'); diff --git a/test/parallel/test-net-after-close.js b/test/parallel/test-net-after-close.js index db658bcb03de06..d46f096116d02e 100644 --- a/test/parallel/test-net-after-close.js +++ b/test/parallel/test-net-after-close.js @@ -3,13 +3,13 @@ const common = require('../common'); const assert = require('assert'); const net = require('net'); -var server = net.createServer(function(s) { +const server = net.createServer(function(s) { console.error('SERVER: got connection'); s.end(); }); server.listen(0, common.mustCall(function() { - var c = net.createConnection(this.address().port); + const c = net.createConnection(this.address().port); c.on('close', common.mustCall(function() { console.error('connection closed'); assert.strictEqual(c._handle, null); diff --git a/test/parallel/test-net-better-error-messages-path.js b/test/parallel/test-net-better-error-messages-path.js index bf18e14898fbf0..2f821ef5d703be 100644 --- a/test/parallel/test-net-better-error-messages-path.js +++ b/test/parallel/test-net-better-error-messages-path.js @@ -2,8 +2,8 @@ const common = require('../common'); const net = require('net'); const assert = require('assert'); -var fp = '/tmp/fadagagsdfgsdf'; -var c = net.connect(fp); +const fp = '/tmp/fadagagsdfgsdf'; +const c = net.connect(fp); c.on('connect', common.fail); diff --git a/test/parallel/test-net-binary.js b/test/parallel/test-net-binary.js index 47e0be8d04dcf6..bcc554ac4024f6 100644 --- a/test/parallel/test-net-binary.js +++ b/test/parallel/test-net-binary.js @@ -3,8 +3,8 @@ require('../common'); const assert = require('assert'); const net = require('net'); -var binaryString = ''; -for (var i = 255; i >= 0; i--) { +let binaryString = ''; +for (let i = 255; i >= 0; i--) { const s = `'\\${i.toString(8)}'`; const S = eval(s); assert.strictEqual(S.charCodeAt(0), i); @@ -13,7 +13,7 @@ for (var i = 255; i >= 0; i--) { } // safe constructor -var echoServer = net.Server(function(connection) { +const echoServer = net.Server(function(connection) { connection.setEncoding('latin1'); connection.on('data', function(chunk) { connection.write(chunk, 'latin1'); @@ -24,10 +24,10 @@ var echoServer = net.Server(function(connection) { }); echoServer.listen(0); -var recv = ''; +let recv = ''; echoServer.on('listening', function() { - var j = 0; + let j = 0; const c = net.createConnection({ port: this.address().port }); diff --git a/test/parallel/test-net-bind-twice.js b/test/parallel/test-net-bind-twice.js index 68e93a75f0154a..17fdc90cb3742b 100644 --- a/test/parallel/test-net-bind-twice.js +++ b/test/parallel/test-net-bind-twice.js @@ -3,9 +3,9 @@ const common = require('../common'); const assert = require('assert'); const net = require('net'); -var server1 = net.createServer(common.fail); +const server1 = net.createServer(common.fail); server1.listen(0, '127.0.0.1', common.mustCall(function() { - var server2 = net.createServer(common.fail); + const server2 = net.createServer(common.fail); server2.listen(this.address().port, '127.0.0.1', common.fail); server2.on('error', common.mustCall(function(e) { diff --git a/test/parallel/test-net-buffersize.js b/test/parallel/test-net-buffersize.js index dfaf5dd50d6614..e8ba17a76e6c69 100644 --- a/test/parallel/test-net-buffersize.js +++ b/test/parallel/test-net-buffersize.js @@ -3,9 +3,9 @@ require('../common'); const assert = require('assert'); const net = require('net'); -var iter = 10; +const iter = 10; -var server = net.createServer(function(socket) { +const server = net.createServer(function(socket) { socket.on('readable', function() { socket.read(); }); @@ -16,13 +16,13 @@ var server = net.createServer(function(socket) { }); server.listen(0, function() { - var client = net.connect(this.address().port); + const client = net.connect(this.address().port); client.on('finish', function() { assert.strictEqual(client.bufferSize, 0); }); - for (var i = 1; i < iter; i++) { + for (let i = 1; i < iter; i++) { client.write('a'); assert.strictEqual(client.bufferSize, i); } diff --git a/test/parallel/test-net-bytes-stats.js b/test/parallel/test-net-bytes-stats.js index 518b2f10ba37d4..4cc6eee8373e86 100644 --- a/test/parallel/test-net-bytes-stats.js +++ b/test/parallel/test-net-bytes-stats.js @@ -3,11 +3,11 @@ require('../common'); const assert = require('assert'); const net = require('net'); -var bytesRead = 0; -var bytesWritten = 0; -var count = 0; +let bytesRead = 0; +let bytesWritten = 0; +let count = 0; -var tcp = net.Server(function(s) { +const tcp = net.Server(function(s) { console.log('tcp server connection'); // trigger old mode. @@ -21,7 +21,7 @@ var tcp = net.Server(function(s) { tcp.listen(0, function doTest() { console.error('listening'); - var socket = net.createConnection(this.address().port); + const socket = net.createConnection(this.address().port); socket.on('connect', function() { count++; diff --git a/test/parallel/test-net-can-reset-timeout.js b/test/parallel/test-net-can-reset-timeout.js index c5333e2522711e..faa460e847aa08 100644 --- a/test/parallel/test-net-can-reset-timeout.js +++ b/test/parallel/test-net-can-reset-timeout.js @@ -2,7 +2,7 @@ const common = require('../common'); const net = require('net'); -var server = net.createServer(common.mustCall(function(stream) { +const server = net.createServer(common.mustCall(function(stream) { stream.setTimeout(100); stream.resume(); @@ -20,7 +20,7 @@ var server = net.createServer(common.mustCall(function(stream) { })); server.listen(0, function() { - var c = net.createConnection(this.address().port); + const c = net.createConnection(this.address().port); c.on('data', function() { c.end(); diff --git a/test/parallel/test-net-connect-buffer.js b/test/parallel/test-net-connect-buffer.js index 187cbf19426653..c43ee1abd0e305 100644 --- a/test/parallel/test-net-connect-buffer.js +++ b/test/parallel/test-net-connect-buffer.js @@ -3,15 +3,15 @@ require('../common'); const assert = require('assert'); const net = require('net'); -var dataWritten = false; -var connectHappened = false; +let dataWritten = false; +let connectHappened = false; -var tcp = net.Server(function(s) { +const tcp = net.Server(function(s) { tcp.close(); console.log('tcp server connection'); - var buf = ''; + let buf = ''; s.on('data', function(d) { buf += d; }); @@ -30,7 +30,7 @@ var tcp = net.Server(function(s) { }); tcp.listen(0, function() { - var socket = net.Stream({ highWaterMark: 0 }); + const socket = net.Stream({ highWaterMark: 0 }); console.log('Connecting to socket '); @@ -65,13 +65,13 @@ tcp.listen(0, function() { // Write a string that contains a multi-byte character sequence to test that // `bytesWritten` is incremented with the # of bytes, not # of characters. - var a = "L'État, c'est "; - var b = 'moi'; + const a = "L'État, c'est "; + const b = 'moi'; // We're still connecting at this point so the datagram is first pushed onto // the connect queue. Make sure that it's not added to `bytesWritten` again // when the actual write happens. - var r = socket.write(a, function(er) { + const r = socket.write(a, function(er) { console.error('write cb'); dataWritten = true; assert.ok(connectHappened); diff --git a/test/parallel/test-net-connect-local-error.js b/test/parallel/test-net-connect-local-error.js index 197b283bdf3621..8f1784565d38ee 100644 --- a/test/parallel/test-net-connect-local-error.js +++ b/test/parallel/test-net-connect-local-error.js @@ -3,7 +3,7 @@ const common = require('../common'); const assert = require('assert'); const net = require('net'); -var client = net.connect({ +const client = net.connect({ port: common.PORT + 1, localPort: common.PORT, localAddress: common.localhostIPv4 diff --git a/test/parallel/test-net-connect-options-ipv6.js b/test/parallel/test-net-connect-options-ipv6.js index 7f638d66f59508..e9d8a78cbbefef 100644 --- a/test/parallel/test-net-connect-options-ipv6.js +++ b/test/parallel/test-net-connect-options-ipv6.js @@ -9,9 +9,9 @@ if (!common.hasIPv6) { } const hosts = common.localIPv6Hosts; -var hostIdx = 0; -var host = hosts[hostIdx]; -var localhostTries = 10; +let hostIdx = 0; +let host = hosts[hostIdx]; +let localhostTries = 10; const server = net.createServer({allowHalfOpen: true}, function(socket) { socket.resume(); diff --git a/test/parallel/test-net-connect-options.js b/test/parallel/test-net-connect-options.js index 727504b06fc7e2..e794c40859856a 100644 --- a/test/parallel/test-net-connect-options.js +++ b/test/parallel/test-net-connect-options.js @@ -3,7 +3,7 @@ const common = require('../common'); const assert = require('assert'); const net = require('net'); -var server = net.createServer({ +const server = net.createServer({ allowHalfOpen: true }, common.mustCall(function(socket) { socket.resume(); @@ -12,7 +12,7 @@ var server = net.createServer({ })); server.listen(0, function() { - var client = net.connect({ + const client = net.connect({ host: '127.0.0.1', port: this.address().port, allowHalfOpen: true diff --git a/test/parallel/test-net-create-connection.js b/test/parallel/test-net-create-connection.js index a21f92a3a5674c..a5d8cd101d974d 100644 --- a/test/parallel/test-net-create-connection.js +++ b/test/parallel/test-net-create-connection.js @@ -5,8 +5,8 @@ const dns = require('dns'); const net = require('net'); const expectedConnections = 7; -var clientConnected = 0; -var serverConnected = 0; +let clientConnected = 0; +let serverConnected = 0; const server = net.createServer(function(socket) { socket.end(); diff --git a/test/parallel/test-net-dns-custom-lookup.js b/test/parallel/test-net-dns-custom-lookup.js index d643910d62e0d4..c7a01f5fa6faec 100644 --- a/test/parallel/test-net-dns-custom-lookup.js +++ b/test/parallel/test-net-dns-custom-lookup.js @@ -4,13 +4,13 @@ const assert = require('assert'); const net = require('net'); function check(addressType, cb) { - var server = net.createServer(function(client) { + const server = net.createServer(function(client) { client.end(); server.close(); cb && cb(); }); - var address = addressType === 4 ? common.localhostIPv4 : '::1'; + const address = addressType === 4 ? common.localhostIPv4 : '::1'; server.listen(0, address, common.mustCall(function() { net.connect({ port: this.address().port, diff --git a/test/parallel/test-net-dns-error.js b/test/parallel/test-net-dns-error.js index f5a1dcc6b1c2c5..aa288c5fde1ffa 100644 --- a/test/parallel/test-net-dns-error.js +++ b/test/parallel/test-net-dns-error.js @@ -4,13 +4,13 @@ const assert = require('assert'); const net = require('net'); -var host = '*'.repeat(256); +const host = '*'.repeat(256); function do_not_call() { throw new Error('This function should not have been called.'); } -var socket = net.connect(42, host, do_not_call); +const socket = net.connect(42, host, do_not_call); socket.on('error', common.mustCall(function(err) { assert.equal(err.code, 'ENOTFOUND'); })); diff --git a/test/parallel/test-net-dns-lookup-skip.js b/test/parallel/test-net-dns-lookup-skip.js index 60674053f7a53c..0997e6cc6c1c5d 100644 --- a/test/parallel/test-net-dns-lookup-skip.js +++ b/test/parallel/test-net-dns-lookup-skip.js @@ -3,12 +3,12 @@ const common = require('../common'); const net = require('net'); function check(addressType) { - var server = net.createServer(function(client) { + const server = net.createServer(function(client) { client.end(); server.close(); }); - var address = addressType === 4 ? '127.0.0.1' : '::1'; + const address = addressType === 4 ? '127.0.0.1' : '::1'; server.listen(0, address, function() { net.connect(this.address().port, address).on('lookup', common.fail); }); diff --git a/test/parallel/test-net-dns-lookup.js b/test/parallel/test-net-dns-lookup.js index c0aebf0ee919c3..8d9930f4b7a366 100644 --- a/test/parallel/test-net-dns-lookup.js +++ b/test/parallel/test-net-dns-lookup.js @@ -3,7 +3,7 @@ const common = require('../common'); const assert = require('assert'); const net = require('net'); -var server = net.createServer(function(client) { +const server = net.createServer(function(client) { client.end(); server.close(); }); diff --git a/test/parallel/test-net-during-close.js b/test/parallel/test-net-during-close.js index f6a5455ee7b0f1..e8723fb1a692a8 100644 --- a/test/parallel/test-net-during-close.js +++ b/test/parallel/test-net-during-close.js @@ -3,12 +3,12 @@ const common = require('../common'); const assert = require('assert'); const net = require('net'); -var server = net.createServer(function(socket) { +const server = net.createServer(function(socket) { socket.end(); }); server.listen(0, common.mustCall(function() { - var client = net.createConnection(this.address().port); + const client = net.createConnection(this.address().port); server.close(); // server connection event has not yet fired // client is still attempting to connect diff --git a/test/parallel/test-net-eaddrinuse.js b/test/parallel/test-net-eaddrinuse.js index 53ae1a0589262b..3d7ceb8d5e38f7 100644 --- a/test/parallel/test-net-eaddrinuse.js +++ b/test/parallel/test-net-eaddrinuse.js @@ -3,9 +3,9 @@ require('../common'); const assert = require('assert'); const net = require('net'); -var server1 = net.createServer(function(socket) { +const server1 = net.createServer(function(socket) { }); -var server2 = net.createServer(function(socket) { +const server2 = net.createServer(function(socket) { }); server1.listen(0, function() { server2.on('error', function(error) { diff --git a/test/parallel/test-net-end-without-connect.js b/test/parallel/test-net-end-without-connect.js index 0bbd2833626df7..99324b071d27d6 100644 --- a/test/parallel/test-net-end-without-connect.js +++ b/test/parallel/test-net-end-without-connect.js @@ -2,5 +2,5 @@ require('../common'); const net = require('net'); -var sock = new net.Socket(); +const sock = new net.Socket(); sock.end(); // Should not throw. diff --git a/test/parallel/test-net-error-twice.js b/test/parallel/test-net-error-twice.js index 36c33b4b1cc012..98a2c337559b06 100644 --- a/test/parallel/test-net-error-twice.js +++ b/test/parallel/test-net-error-twice.js @@ -6,8 +6,8 @@ const net = require('net'); const buf = Buffer.alloc(10 * 1024 * 1024, 0x62); const errs = []; -var clientSocket; -var serverSocket; +let clientSocket; +let serverSocket; function ready() { if (clientSocket && serverSocket) { @@ -16,7 +16,7 @@ function ready() { } } -var srv = net.createServer(function onConnection(conn) { +const srv = net.createServer(function onConnection(conn) { conn.on('error', function(err) { errs.push(err); if (errs.length > 1 && errs[0] === errs[1]) @@ -28,7 +28,7 @@ var srv = net.createServer(function onConnection(conn) { serverSocket = conn; ready(); }).listen(0, function() { - var client = net.connect({ port: this.address().port }); + const client = net.connect({ port: this.address().port }); client.on('connect', function() { clientSocket = client; diff --git a/test/parallel/test-net-internal.js b/test/parallel/test-net-internal.js index 0c8d1cf9e17a0e..a79d022a5d7eaa 100644 --- a/test/parallel/test-net-internal.js +++ b/test/parallel/test-net-internal.js @@ -6,7 +6,7 @@ require('../common'); const assert = require('assert'); const isLegalPort = require('internal/net').isLegalPort; -for (var n = 0; n <= 0xFFFF; n++) { +for (let n = 0; n <= 0xFFFF; n++) { assert(isLegalPort(n)); assert(isLegalPort('' + n)); assert(`0x${n.toString(16)}`); diff --git a/test/parallel/test-net-keepalive.js b/test/parallel/test-net-keepalive.js index 8b6998fa831a78..68ed5f842ff13b 100644 --- a/test/parallel/test-net-keepalive.js +++ b/test/parallel/test-net-keepalive.js @@ -3,9 +3,9 @@ const common = require('../common'); const assert = require('assert'); const net = require('net'); -var serverConnection; -var clientConnection; -var echoServer = net.createServer(function(connection) { +let serverConnection; +let clientConnection; +const echoServer = net.createServer(function(connection) { serverConnection = connection; setTimeout(common.mustCall(function() { // make sure both connections are still open diff --git a/test/parallel/test-net-large-string.js b/test/parallel/test-net-large-string.js index ba70275eb03e6f..83612111e2a0aa 100644 --- a/test/parallel/test-net-large-string.js +++ b/test/parallel/test-net-large-string.js @@ -3,12 +3,12 @@ const common = require('../common'); const assert = require('assert'); const net = require('net'); -var kPoolSize = 40 * 1024; -var data = 'あ'.repeat(kPoolSize); -var encoding = 'UTF-8'; +const kPoolSize = 40 * 1024; +const data = 'あ'.repeat(kPoolSize); +const encoding = 'UTF-8'; -var server = net.createServer(common.mustCall(function(socket) { - var receivedSize = 0; +const server = net.createServer(common.mustCall(function(socket) { + let receivedSize = 0; socket.setEncoding(encoding); socket.on('data', function(data) { @@ -21,7 +21,7 @@ var server = net.createServer(common.mustCall(function(socket) { })); server.listen(0, function() { - var client = net.createConnection(this.address().port); + const client = net.createConnection(this.address().port); client.on('end', function() { server.close(); }); diff --git a/test/parallel/test-net-listen-close-server-callback-is-not-function.js b/test/parallel/test-net-listen-close-server-callback-is-not-function.js index 18234a816e1b0d..472ea37e7146b9 100644 --- a/test/parallel/test-net-listen-close-server-callback-is-not-function.js +++ b/test/parallel/test-net-listen-close-server-callback-is-not-function.js @@ -2,7 +2,7 @@ const common = require('../common'); const net = require('net'); -var server = net.createServer(common.fail); +const server = net.createServer(common.fail); server.on('close', common.mustCall(function() {})); diff --git a/test/parallel/test-net-listen-close-server.js b/test/parallel/test-net-listen-close-server.js index b6ab99c60e2d51..0a45adecbe83e7 100644 --- a/test/parallel/test-net-listen-close-server.js +++ b/test/parallel/test-net-listen-close-server.js @@ -2,7 +2,7 @@ const common = require('../common'); const net = require('net'); -var server = net.createServer(function(socket) { +const server = net.createServer(function(socket) { }); server.listen(0, common.fail); server.on('error', common.fail); diff --git a/test/parallel/test-net-listen-error.js b/test/parallel/test-net-listen-error.js index 009d12b09e7aca..7b721d1004f37f 100644 --- a/test/parallel/test-net-listen-error.js +++ b/test/parallel/test-net-listen-error.js @@ -2,7 +2,7 @@ const common = require('../common'); const net = require('net'); -var server = net.createServer(function(socket) { +const server = net.createServer(function(socket) { }); server.listen(1, '1.1.1.1', common.fail); // EACCESS or EADDRNOTAVAIL server.on('error', common.mustCall(function(error) {})); diff --git a/test/parallel/test-net-listen-exclusive-random-ports.js b/test/parallel/test-net-listen-exclusive-random-ports.js index 974af6aaa60438..cc1ab4d805994f 100644 --- a/test/parallel/test-net-listen-exclusive-random-ports.js +++ b/test/parallel/test-net-listen-exclusive-random-ports.js @@ -7,11 +7,11 @@ const net = require('net'); function noop() {} if (cluster.isMaster) { - var worker1 = cluster.fork(); + const worker1 = cluster.fork(); worker1.on('message', function(port1) { assert.equal(port1, port1 | 0, 'first worker could not listen'); - var worker2 = cluster.fork(); + const worker2 = cluster.fork(); worker2.on('message', function(port2) { assert.equal(port2, port2 | 0, 'second worker could not listen'); @@ -21,7 +21,7 @@ if (cluster.isMaster) { }); }); } else { - var server = net.createServer(noop); + const server = net.createServer(noop); server.on('error', function(err) { process.send(err.code); diff --git a/test/parallel/test-net-listen-shared-ports.js b/test/parallel/test-net-listen-shared-ports.js index 4cd26ac330a67c..ce344be4a6f492 100644 --- a/test/parallel/test-net-listen-shared-ports.js +++ b/test/parallel/test-net-listen-shared-ports.js @@ -7,11 +7,11 @@ const net = require('net'); function noop() {} if (cluster.isMaster) { - var worker1 = cluster.fork(); + const worker1 = cluster.fork(); worker1.on('message', function(msg) { assert.equal(msg, 'success'); - var worker2 = cluster.fork(); + const worker2 = cluster.fork(); worker2.on('message', function(msg) { assert.equal(msg, 'server2:EADDRINUSE'); @@ -20,8 +20,8 @@ if (cluster.isMaster) { }); }); } else { - var server1 = net.createServer(noop); - var server2 = net.createServer(noop); + const server1 = net.createServer(noop); + const server2 = net.createServer(noop); server1.on('error', function(err) { // no errors expected diff --git a/test/parallel/test-net-local-address-port.js b/test/parallel/test-net-local-address-port.js index 56f8eab5855c46..b256d93b5f8400 100644 --- a/test/parallel/test-net-local-address-port.js +++ b/test/parallel/test-net-local-address-port.js @@ -3,7 +3,7 @@ const common = require('../common'); const assert = require('assert'); const net = require('net'); -var server = net.createServer(common.mustCall(function(socket) { +const server = net.createServer(common.mustCall(function(socket) { assert.strictEqual(socket.localAddress, common.localhostIPv4); assert.strictEqual(socket.localPort, this.address().port); socket.on('end', function() { @@ -13,7 +13,8 @@ var server = net.createServer(common.mustCall(function(socket) { })); server.listen(0, common.localhostIPv4, function() { - var client = net.createConnection(this.address().port, common.localhostIPv4); + const client = net.createConnection(this.address() + .port, common.localhostIPv4); client.on('connect', function() { client.end(); }); diff --git a/test/parallel/test-net-localport.js b/test/parallel/test-net-localport.js index 3c105ff2877544..b100e4ae768c29 100644 --- a/test/parallel/test-net-localport.js +++ b/test/parallel/test-net-localport.js @@ -3,7 +3,7 @@ const common = require('../common'); const assert = require('assert'); const net = require('net'); -var server = net.createServer(function(socket) { +const server = net.createServer(function(socket) { console.log(socket.remotePort); assert.strictEqual(socket.remotePort, common.PORT); socket.end(); @@ -11,7 +11,7 @@ var server = net.createServer(function(socket) { server.close(); }); }).listen(0).on('listening', function() { - var client = net.connect({ + const client = net.connect({ host: '127.0.0.1', port: this.address().port, localPort: common.PORT, diff --git a/test/parallel/test-net-pause-resume-connecting.js b/test/parallel/test-net-pause-resume-connecting.js index 6f3e78a94a56df..f441252fed6e70 100644 --- a/test/parallel/test-net-pause-resume-connecting.js +++ b/test/parallel/test-net-pause-resume-connecting.js @@ -9,7 +9,7 @@ let conn; // Server -var server = net.createServer(function(conn) { +const server = net.createServer(function(conn) { connections++; conn.end('This was the year he fell to pieces.'); diff --git a/test/parallel/test-net-persistent-keepalive.js b/test/parallel/test-net-persistent-keepalive.js index febdc688519ca8..6338b5932de1fa 100644 --- a/test/parallel/test-net-persistent-keepalive.js +++ b/test/parallel/test-net-persistent-keepalive.js @@ -3,9 +3,9 @@ require('../common'); const assert = require('assert'); const net = require('net'); -var serverConnection; -var clientConnection; -var echoServer = net.createServer(function(connection) { +let serverConnection; +let clientConnection; +const echoServer = net.createServer(function(connection) { serverConnection = connection; setTimeout(function() { // make sure both connections are still open @@ -27,7 +27,7 @@ echoServer.on('listening', function() { clientConnection = new net.Socket(); // send a keepalive packet after 1000 ms // and make sure it persists - var s = clientConnection.setKeepAlive(true, 400); + const s = clientConnection.setKeepAlive(true, 400); assert.ok(s instanceof net.Socket); clientConnection.connect(this.address().port); clientConnection.setTimeout(0); diff --git a/test/parallel/test-net-persistent-nodelay.js b/test/parallel/test-net-persistent-nodelay.js index bd34d303264a64..3f94424b0e1197 100644 --- a/test/parallel/test-net-persistent-nodelay.js +++ b/test/parallel/test-net-persistent-nodelay.js @@ -2,17 +2,17 @@ require('../common'); const assert = require('assert'); const net = require('net'); -var TCPWrap = process.binding('tcp_wrap').TCP; +const TCPWrap = process.binding('tcp_wrap').TCP; -var echoServer = net.createServer(function(connection) { +const echoServer = net.createServer(function(connection) { connection.end(); }); echoServer.listen(0); -var callCount = 0; +let callCount = 0; -var Socket = net.Socket; -var setNoDelay = TCPWrap.prototype.setNoDelay; +const Socket = net.Socket; +const setNoDelay = TCPWrap.prototype.setNoDelay; TCPWrap.prototype.setNoDelay = function(enable) { setNoDelay.call(this, enable); @@ -20,11 +20,11 @@ TCPWrap.prototype.setNoDelay = function(enable) { }; echoServer.on('listening', function() { - var sock1 = new Socket(); + const sock1 = new Socket(); // setNoDelay before the handle is created // there is probably a better way to test this - var s = sock1.setNoDelay(); + const s = sock1.setNoDelay(); assert.ok(s instanceof net.Socket); sock1.connect(this.address().port); sock1.on('end', function() { diff --git a/test/parallel/test-net-persistent-ref-unref.js b/test/parallel/test-net-persistent-ref-unref.js index 9034a16f9a2793..1d3cbc6ffaef18 100644 --- a/test/parallel/test-net-persistent-ref-unref.js +++ b/test/parallel/test-net-persistent-ref-unref.js @@ -2,16 +2,16 @@ require('../common'); const assert = require('assert'); const net = require('net'); -var TCPWrap = process.binding('tcp_wrap').TCP; +const TCPWrap = process.binding('tcp_wrap').TCP; -var echoServer = net.createServer(function(conn) { +const echoServer = net.createServer(function(conn) { conn.end(); }); -var ref = TCPWrap.prototype.ref; -var unref = TCPWrap.prototype.unref; +const ref = TCPWrap.prototype.ref; +const unref = TCPWrap.prototype.unref; -var refCount = 0; +let refCount = 0; TCPWrap.prototype.ref = function() { ref.call(this); @@ -28,7 +28,7 @@ TCPWrap.prototype.unref = function() { echoServer.listen(0); echoServer.on('listening', function() { - var sock = new net.Socket(); + const sock = new net.Socket(); sock.unref(); sock.ref(); sock.connect(this.address().port); diff --git a/test/parallel/test-net-pingpong.js b/test/parallel/test-net-pingpong.js index b49b3a78778719..9280991f39e5d9 100644 --- a/test/parallel/test-net-pingpong.js +++ b/test/parallel/test-net-pingpong.js @@ -5,9 +5,9 @@ const net = require('net'); function pingPongTest(port, host) { const N = 1000; - var count = 0; - var sentPongs = 0; - var sent_final_ping = false; + let count = 0; + let sentPongs = 0; + let sent_final_ping = false; const server = net.createServer( { allowHalfOpen: true }, diff --git a/test/parallel/test-net-pipe-connect-errors.js b/test/parallel/test-net-pipe-connect-errors.js index 3e00befc341682..2c1332efa11429 100644 --- a/test/parallel/test-net-pipe-connect-errors.js +++ b/test/parallel/test-net-pipe-connect-errors.js @@ -8,7 +8,7 @@ const assert = require('assert'); // Test if ENOTSOCK is fired when trying to connect to a file which is not // a socket. -var emptyTxt; +let emptyTxt; if (common.isWindows) { // on Win, common.PIPE will be a named pipe, so we use an existing empty @@ -34,7 +34,7 @@ if (common.isWindows) { fs.writeFileSync(emptyTxt, ''); } -var notSocketClient = net.createConnection(emptyTxt, function() { +const notSocketClient = net.createConnection(emptyTxt, function() { common.fail('connection callback should not run'); }); @@ -45,7 +45,7 @@ notSocketClient.on('error', common.mustCall(function(err) { // Trying to connect to not-existing socket should result in ENOENT error -var noEntSocketClient = net.createConnection('no-ent-file', function() { +const noEntSocketClient = net.createConnection('no-ent-file', function() { common.fail('connection to non-existent socket, callback should not run'); }); @@ -63,7 +63,7 @@ if (!common.isWindows && process.getuid() !== 0) { accessServer.listen(common.PIPE, common.mustCall(function() { fs.chmodSync(common.PIPE, 0); - var accessClient = net.createConnection(common.PIPE, function() { + const accessClient = net.createConnection(common.PIPE, function() { common.fail('connection should get EACCES, callback should not run'); }); diff --git a/test/parallel/test-net-reconnect.js b/test/parallel/test-net-reconnect.js index c0c5589b396ee4..47171093ca13f9 100644 --- a/test/parallel/test-net-reconnect.js +++ b/test/parallel/test-net-reconnect.js @@ -4,12 +4,12 @@ const assert = require('assert'); const net = require('net'); -var N = 50; -var client_recv_count = 0; -var client_end_count = 0; -var disconnect_count = 0; +const N = 50; +let client_recv_count = 0; +let client_end_count = 0; +let disconnect_count = 0; -var server = net.createServer(function(socket) { +const server = net.createServer(function(socket) { console.error('SERVER: got socket connection'); socket.resume(); @@ -29,7 +29,7 @@ var server = net.createServer(function(socket) { server.listen(0, function() { console.log('SERVER listening'); - var client = net.createConnection(this.address().port); + const client = net.createConnection(this.address().port); client.setEncoding('UTF8'); diff --git a/test/parallel/test-net-remote-address-port.js b/test/parallel/test-net-remote-address-port.js index 9cdf4ff7f876b8..a9d02631be5194 100644 --- a/test/parallel/test-net-remote-address-port.js +++ b/test/parallel/test-net-remote-address-port.js @@ -4,15 +4,15 @@ const assert = require('assert'); const net = require('net'); -var conns_closed = 0; +let conns_closed = 0; -var remoteAddrCandidates = [ common.localhostIPv4 ]; +const remoteAddrCandidates = [ common.localhostIPv4 ]; if (common.hasIPv6) remoteAddrCandidates.push('::ffff:127.0.0.1'); -var remoteFamilyCandidates = ['IPv4']; +const remoteFamilyCandidates = ['IPv4']; if (common.hasIPv6) remoteFamilyCandidates.push('IPv6'); -var server = net.createServer(common.mustCall(function(socket) { +const server = net.createServer(common.mustCall(function(socket) { assert.ok(remoteAddrCandidates.includes(socket.remoteAddress)); assert.ok(remoteFamilyCandidates.includes(socket.remoteFamily)); assert.ok(socket.remotePort); @@ -28,8 +28,8 @@ var server = net.createServer(common.mustCall(function(socket) { }, 2)); server.listen(0, 'localhost', function() { - var client = net.createConnection(this.address().port, 'localhost'); - var client2 = net.createConnection(this.address().port); + const client = net.createConnection(this.address().port, 'localhost'); + const client2 = net.createConnection(this.address().port); client.on('connect', function() { assert.ok(remoteAddrCandidates.includes(client.remoteAddress)); assert.ok(remoteFamilyCandidates.includes(client.remoteFamily)); diff --git a/test/parallel/test-net-server-bind.js b/test/parallel/test-net-server-bind.js index 623962e3abddca..e4dc64216441cf 100644 --- a/test/parallel/test-net-server-bind.js +++ b/test/parallel/test-net-server-bind.js @@ -6,8 +6,8 @@ const net = require('net'); // With only a callback, server should get a port assigned by the OS -var address0; -var server0 = net.createServer(function(socket) { }); +let address0; +const server0 = net.createServer(function(socket) { }); server0.listen(function() { address0 = server0.address(); @@ -18,9 +18,9 @@ server0.listen(function() { // No callback to listen(), assume we can bind in 100 ms -var address1; -var connectionKey1; -var server1 = net.createServer(function(socket) { }); +let address1; +let connectionKey1; +const server1 = net.createServer(function(socket) { }); server1.listen(common.PORT); @@ -34,8 +34,8 @@ setTimeout(function() { // Callback to listen() -var address2; -var server2 = net.createServer(function(socket) { }); +let address2; +const server2 = net.createServer(function(socket) { }); server2.listen(common.PORT + 1, function() { address2 = server2.address(); @@ -46,8 +46,8 @@ server2.listen(common.PORT + 1, function() { // Backlog argument -var address3; -var server3 = net.createServer(function(socket) { }); +let address3; +const server3 = net.createServer(function(socket) { }); server3.listen(common.PORT + 2, '0.0.0.0', 127, function() { address3 = server3.address(); @@ -58,8 +58,8 @@ server3.listen(common.PORT + 2, '0.0.0.0', 127, function() { // Backlog argument without host argument -var address4; -var server4 = net.createServer(function(socket) { }); +let address4; +const server4 = net.createServer(function(socket) { }); server4.listen(common.PORT + 3, 127, function() { address4 = server4.address(); @@ -72,7 +72,7 @@ process.on('exit', function() { assert.ok(address0.port > 100); assert.equal(common.PORT, address1.port); - var expectedConnectionKey1; + let expectedConnectionKey1; if (address1.family === 'IPv6') expectedConnectionKey1 = '6::::' + address1.port; diff --git a/test/parallel/test-net-server-close.js b/test/parallel/test-net-server-close.js index 9f920a6a69b194..d52cccaacfd8e6 100644 --- a/test/parallel/test-net-server-close.js +++ b/test/parallel/test-net-server-close.js @@ -3,8 +3,8 @@ require('../common'); const assert = require('assert'); const net = require('net'); -var events = []; -var sockets = []; +const events = []; +const sockets = []; process.on('exit', function() { assert.equal(server.connections, 0); @@ -15,7 +15,7 @@ process.on('exit', function() { assert.equal(events.join(' ').match(/client/g).length, 2); }); -var server = net.createServer(function(c) { +const server = net.createServer(function(c) { c.on('close', function() { events.push('client'); }); diff --git a/test/parallel/test-net-server-connections.js b/test/parallel/test-net-server-connections.js index ce3087713c3ad7..4e41d29a505199 100644 --- a/test/parallel/test-net-server-connections.js +++ b/test/parallel/test-net-server-connections.js @@ -7,6 +7,6 @@ const net = require('net'); // test that server.connections property is no longer enumerable now that it // has been marked as deprecated -var server = new net.Server(); +const server = new net.Server(); assert.equal(Object.keys(server).indexOf('connections'), -1); diff --git a/test/parallel/test-net-server-listen-remove-callback.js b/test/parallel/test-net-server-listen-remove-callback.js index 4d2c12102c4448..a678922683eeb1 100644 --- a/test/parallel/test-net-server-listen-remove-callback.js +++ b/test/parallel/test-net-server-listen-remove-callback.js @@ -4,10 +4,10 @@ const assert = require('assert'); const net = require('net'); // Server should only fire listen callback once -var server = net.createServer(); +const server = net.createServer(); server.on('close', function() { - var listeners = server.listeners('listening'); + const listeners = server.listeners('listening'); console.log('Closed, listeners:', listeners.length); assert.equal(0, listeners.length); }); diff --git a/test/parallel/test-net-server-max-connections-close-makes-more-available.js b/test/parallel/test-net-server-max-connections-close-makes-more-available.js index 14a27da8f8cc3d..c7fe7c74a77d37 100644 --- a/test/parallel/test-net-server-max-connections-close-makes-more-available.js +++ b/test/parallel/test-net-server-max-connections-close-makes-more-available.js @@ -13,16 +13,16 @@ const net = require('net'); // Connection 2 should be accepted. // Connection 3 should be rejected. -var connections = []; -var received = []; -var sent = []; +const connections = []; +const received = []; +const sent = []; -var createConnection = function(index) { +const createConnection = function(index) { console.error('creating connection ' + index); return new Promise(function(resolve, reject) { - var connection = net.createConnection(server.address().port, function() { - var msg = '' + index; + const connection = net.createConnection(server.address().port, function() { + const msg = '' + index; console.error('sending message: ' + msg); this.write(msg); sent.push(msg); @@ -47,7 +47,7 @@ var createConnection = function(index) { }); }; -var closeConnection = function(index) { +const closeConnection = function(index) { console.error('closing connection ' + index); return new Promise(function(resolve, reject) { connections[index].on('end', function() { @@ -57,7 +57,7 @@ var closeConnection = function(index) { }); }; -var server = net.createServer(function(socket) { +const server = net.createServer(function(socket) { socket.on('data', function(data) { console.error('received message: ' + data); received.push('' + data); diff --git a/test/parallel/test-net-server-max-connections.js b/test/parallel/test-net-server-max-connections.js index 99d3b345f40974..f560a7dafc4446 100644 --- a/test/parallel/test-net-server-max-connections.js +++ b/test/parallel/test-net-server-max-connections.js @@ -9,7 +9,7 @@ const net = require('net'); // and the last 10 connections are rejected. const N = 20; -var closes = 0; +let closes = 0; const waits = []; const server = net.createServer(common.mustCall(function(connection) { @@ -26,7 +26,7 @@ server.maxConnections = N / 2; function makeConnection(index) { const c = net.createConnection(server.address().port); - var gotData = false; + let gotData = false; c.on('connect', function() { if (index + 1 < N) { @@ -45,7 +45,7 @@ function makeConnection(index) { } if (closes === N / 2) { - var cb; + let cb; console.error('calling wait callback.'); while (cb = waits.shift()) { cb(); diff --git a/test/parallel/test-net-server-pause-on-connect.js b/test/parallel/test-net-server-pause-on-connect.js index 798175737b80b3..ee5ac4e2807b0a 100644 --- a/test/parallel/test-net-server-pause-on-connect.js +++ b/test/parallel/test-net-server-pause-on-connect.js @@ -3,8 +3,8 @@ const common = require('../common'); const assert = require('assert'); const net = require('net'); const msg = 'test'; -var stopped = true; -var server1Sock; +let stopped = true; +let server1Sock; const server1ConnHandler = function(socket) { diff --git a/test/parallel/test-net-server-unref-persistent.js b/test/parallel/test-net-server-unref-persistent.js index e75a4d83052aab..beb91832ea9448 100644 --- a/test/parallel/test-net-server-unref-persistent.js +++ b/test/parallel/test-net-server-unref-persistent.js @@ -1,7 +1,7 @@ 'use strict'; const common = require('../common'); const net = require('net'); -var server = net.createServer(); +const server = net.createServer(); // unref before listening server.unref(); diff --git a/test/parallel/test-net-server-unref.js b/test/parallel/test-net-server-unref.js index bf8a9ef43ab12c..60df9fc700ec64 100644 --- a/test/parallel/test-net-server-unref.js +++ b/test/parallel/test-net-server-unref.js @@ -2,7 +2,7 @@ const common = require('../common'); const net = require('net'); -var s = net.createServer(); +const s = net.createServer(); s.listen(0); s.unref(); diff --git a/test/parallel/test-net-socket-destroy-twice.js b/test/parallel/test-net-socket-destroy-twice.js index be82d9f2a678b4..998ad05a1d6487 100644 --- a/test/parallel/test-net-socket-destroy-twice.js +++ b/test/parallel/test-net-socket-destroy-twice.js @@ -2,7 +2,7 @@ const common = require('../common'); const net = require('net'); -var conn = net.createConnection(common.PORT); +const conn = net.createConnection(common.PORT); conn.on('error', common.mustCall(function() { conn.destroy(); diff --git a/test/parallel/test-net-socket-local-address.js b/test/parallel/test-net-socket-local-address.js index 82f174dc2c1924..e888667eab4c4f 100644 --- a/test/parallel/test-net-socket-local-address.js +++ b/test/parallel/test-net-socket-local-address.js @@ -9,9 +9,9 @@ if (common.inFreeBSDJail) { return; } -var conns = 0; -var clientLocalPorts = []; -var serverRemotePorts = []; +let conns = 0; +const clientLocalPorts = []; +const serverRemotePorts = []; const client = new net.Socket(); const server = net.createServer((socket) => { serverRemotePorts.push(socket.remotePort); diff --git a/test/parallel/test-net-socket-timeout-unref.js b/test/parallel/test-net-socket-timeout-unref.js index fb4f6a658e21d2..1789ec7a1cabbd 100644 --- a/test/parallel/test-net-socket-timeout-unref.js +++ b/test/parallel/test-net-socket-timeout-unref.js @@ -12,7 +12,7 @@ const server = net.createServer(function(c) { server.listen(0); server.unref(); -var connections = 0; +let connections = 0; const sockets = []; const delays = [8, 5, 3, 6, 2, 4]; diff --git a/test/parallel/test-net-stream.js b/test/parallel/test-net-stream.js index 12fcc25b0a9563..9d091bd66f3a1e 100644 --- a/test/parallel/test-net-stream.js +++ b/test/parallel/test-net-stream.js @@ -3,7 +3,7 @@ require('../common'); const assert = require('assert'); const net = require('net'); -var s = new net.Stream(); +const s = new net.Stream(); // test that destroy called on a stream with a server only ever decrements the // server connection count once @@ -18,11 +18,11 @@ assert.equal(9, s.server.connections); s.destroy(); assert.equal(9, s.server.connections); -var SIZE = 2E6; -var N = 10; -var buf = Buffer.alloc(SIZE, 'a'); +const SIZE = 2E6; +const N = 10; +const buf = Buffer.alloc(SIZE, 'a'); -var server = net.createServer(function(socket) { +const server = net.createServer(function(socket) { socket.setNoDelay(); socket.on('error', function(err) { @@ -31,13 +31,13 @@ var server = net.createServer(function(socket) { server.close(); }); - for (var i = 0; i < N; ++i) { + for (let i = 0; i < N; ++i) { socket.write(buf, function() { }); } socket.end(); }).listen(0, function() { - var conn = net.connect(this.address().port); + const conn = net.connect(this.address().port); conn.on('data', function(buf) { conn.pause(); setTimeout(function() { diff --git a/test/parallel/test-net-write-after-close.js b/test/parallel/test-net-write-after-close.js index d8213a9b863b7b..0a1dcd98b2b3c7 100644 --- a/test/parallel/test-net-write-after-close.js +++ b/test/parallel/test-net-write-after-close.js @@ -2,7 +2,7 @@ const common = require('../common'); const net = require('net'); -var server = net.createServer(common.mustCall(function(socket) { +const server = net.createServer(common.mustCall(function(socket) { socket.resume(); socket.on('error', common.mustCall(function(error) { @@ -17,7 +17,7 @@ var server = net.createServer(common.mustCall(function(socket) { })); server.listen(0, function() { - var client = net.connect(this.address().port, function() { + const client = net.connect(this.address().port, function() { client.end(); }); }); diff --git a/test/parallel/test-net-write-connect-write.js b/test/parallel/test-net-write-connect-write.js index 15a30b826e18d9..ee20ede49fb5a5 100644 --- a/test/parallel/test-net-write-connect-write.js +++ b/test/parallel/test-net-write-connect-write.js @@ -3,11 +3,11 @@ const common = require('../common'); const assert = require('assert'); const net = require('net'); -var server = net.createServer(function(socket) { +const server = net.createServer(function(socket) { socket.pipe(socket); }).listen(0, common.mustCall(function() { - var conn = net.connect(this.address().port); - var received = ''; + const conn = net.connect(this.address().port); + let received = ''; conn.setEncoding('utf8'); conn.write('before'); diff --git a/test/parallel/test-net-write-slow.js b/test/parallel/test-net-write-slow.js index 7e183068f174cf..c1b2c60e2e202a 100644 --- a/test/parallel/test-net-write-slow.js +++ b/test/parallel/test-net-write-slow.js @@ -3,20 +3,20 @@ const common = require('../common'); const assert = require('assert'); const net = require('net'); -var SIZE = 2E5; -var N = 10; -var flushed = 0; -var received = 0; -var buf = Buffer.alloc(SIZE, 'a'); +const SIZE = 2E5; +const N = 10; +let flushed = 0; +let received = 0; +const buf = Buffer.alloc(SIZE, 'a'); -var server = net.createServer(function(socket) { +const server = net.createServer(function(socket) { socket.setNoDelay(); socket.setTimeout(9999); socket.on('timeout', function() { common.fail(`flushed: ${flushed}, received: ${received}/${SIZE * N}`); }); - for (var i = 0; i < N; ++i) { + for (let i = 0; i < N; ++i) { socket.write(buf, function() { ++flushed; if (flushed === N) { @@ -27,7 +27,7 @@ var server = net.createServer(function(socket) { socket.end(); }).listen(0, common.mustCall(function() { - var conn = net.connect(this.address().port); + const conn = net.connect(this.address().port); conn.on('data', function(buf) { received += buf.length; conn.pause(); diff --git a/test/parallel/test-next-tick-domain.js b/test/parallel/test-next-tick-domain.js index 634e311da7f67b..6edb7e3050c067 100644 --- a/test/parallel/test-next-tick-domain.js +++ b/test/parallel/test-next-tick-domain.js @@ -2,7 +2,7 @@ require('../common'); const assert = require('assert'); -var origNextTick = process.nextTick; +const origNextTick = process.nextTick; require('domain'); diff --git a/test/parallel/test-next-tick-intentional-starvation.js b/test/parallel/test-next-tick-intentional-starvation.js index 3da32b8ffae15d..ee829c94ab6929 100644 --- a/test/parallel/test-next-tick-intentional-starvation.js +++ b/test/parallel/test-next-tick-intentional-starvation.js @@ -9,14 +9,14 @@ const assert = require('assert'); // WARNING: unsafe! process.maxTickDepth = Infinity; -var ran = false; -var starved = false; -var start = +new Date(); -var timerRan = false; +let ran = false; +let starved = false; +const start = +new Date(); +let timerRan = false; function spin() { ran = true; - var now = +new Date(); + const now = +new Date(); if (now - start > 100) { console.log('The timer is starving, just as we planned.'); starved = true; diff --git a/test/parallel/test-next-tick-ordering.js b/test/parallel/test-next-tick-ordering.js index 316fdb9f9ae373..2f13147d8ed733 100644 --- a/test/parallel/test-next-tick-ordering.js +++ b/test/parallel/test-next-tick-ordering.js @@ -1,10 +1,10 @@ 'use strict'; require('../common'); const assert = require('assert'); -var i; +let i; -var N = 30; -var done = []; +const N = 30; +const done = []; function get_printer(timeout) { return function() { diff --git a/test/parallel/test-next-tick-ordering2.js b/test/parallel/test-next-tick-ordering2.js index 32c5bd8e8ece51..7cfec867f3ed01 100644 --- a/test/parallel/test-next-tick-ordering2.js +++ b/test/parallel/test-next-tick-ordering2.js @@ -2,7 +2,7 @@ require('../common'); const assert = require('assert'); -var order = []; +const order = []; process.nextTick(function() { setTimeout(function() { order.push('setTimeout'); diff --git a/test/parallel/test-next-tick.js b/test/parallel/test-next-tick.js index 702d2308ae1f2e..3001ad0e561a77 100644 --- a/test/parallel/test-next-tick.js +++ b/test/parallel/test-next-tick.js @@ -14,7 +14,7 @@ setTimeout(common.mustCall(function() { process.nextTick(common.mustCall(function() {})); -var obj = {}; +const obj = {}; process.nextTick(function(a, b) { assert.equal(a, 42); diff --git a/test/parallel/test-no-enter-tickcallback.js b/test/parallel/test-no-enter-tickcallback.js index e06628628955be..aab22c5f3edc72 100644 --- a/test/parallel/test-no-enter-tickcallback.js +++ b/test/parallel/test-no-enter-tickcallback.js @@ -2,8 +2,8 @@ const common = require('../common'); const assert = require('assert'); -var allsGood = false; -var cntr = 0; +let allsGood = false; +let cntr = 0; process.on('exit', () => { assert.ok(cntr > 0, '_tickDomainCallback was never called'); diff --git a/test/parallel/test-path-makelong.js b/test/parallel/test-path-makelong.js index 9d3c3852cdbc61..293d6284f173bc 100644 --- a/test/parallel/test-path-makelong.js +++ b/test/parallel/test-path-makelong.js @@ -4,8 +4,8 @@ const assert = require('assert'); const path = require('path'); if (common.isWindows) { - var file = path.join(common.fixturesDir, 'a.js'); - var resolvedFile = path.resolve(file); + const file = path.join(common.fixturesDir, 'a.js'); + const resolvedFile = path.resolve(file); assert.equal('\\\\?\\' + resolvedFile, path._makeLong(file)); assert.equal('\\\\?\\' + resolvedFile, path._makeLong('\\\\?\\' + file)); diff --git a/test/parallel/test-path-parse-format.js b/test/parallel/test-path-parse-format.js index 2db4c27dce072a..f112bc0e4067cd 100644 --- a/test/parallel/test-path-parse-format.js +++ b/test/parallel/test-path-parse-format.js @@ -175,7 +175,7 @@ function checkErrors(path) { function checkParseFormat(path, paths) { paths.forEach(function(element) { - var output = path.parse(element); + const output = path.parse(element); assert.strictEqual(typeof output.root, 'string'); assert.strictEqual(typeof output.dir, 'string'); assert.strictEqual(typeof output.base, 'string'); diff --git a/test/parallel/test-path.js b/test/parallel/test-path.js index 0a12b5ce92ca75..3843088ebdc14b 100644 --- a/test/parallel/test-path.js +++ b/test/parallel/test-path.js @@ -450,9 +450,9 @@ if (common.isWindows) { // See https://github.com/nodejs/node/issues/7215 const currentDriveLetter = path.parse(process.cwd()).root.substring(0, 2); const resolveFixture = path.join(common.fixturesDir, 'path-resolve.js'); - var spawnResult = child.spawnSync( + const spawnResult = child.spawnSync( process.argv[0], [resolveFixture, currentDriveLetter]); - var resolvedPath = spawnResult.stdout.toString().trim(); + const resolvedPath = spawnResult.stdout.toString().trim(); assert.equal(resolvedPath.toLowerCase(), process.cwd().toLowerCase()); } diff --git a/test/parallel/test-pipe-address.js b/test/parallel/test-pipe-address.js index d4bb0ffbc5af81..49f6802d3f7c7a 100644 --- a/test/parallel/test-pipe-address.js +++ b/test/parallel/test-pipe-address.js @@ -2,7 +2,7 @@ const common = require('../common'); const assert = require('assert'); const net = require('net'); -var server = net.createServer(common.fail); +const server = net.createServer(common.fail); common.refreshTmpDir(); diff --git a/test/parallel/test-pipe-return-val.js b/test/parallel/test-pipe-return-val.js index a5f2ff6dfa8fd6..5e6e83dbc7a952 100644 --- a/test/parallel/test-pipe-return-val.js +++ b/test/parallel/test-pipe-return-val.js @@ -5,8 +5,8 @@ require('../common'); const Stream = require('stream').Stream; const assert = require('assert'); -var sourceStream = new Stream(); -var destStream = new Stream(); -var result = sourceStream.pipe(destStream); +const sourceStream = new Stream(); +const destStream = new Stream(); +const result = sourceStream.pipe(destStream); assert.strictEqual(result, destStream); diff --git a/test/parallel/test-pipe-stream.js b/test/parallel/test-pipe-stream.js index 8392c8011002aa..5e3774fc99d535 100644 --- a/test/parallel/test-pipe-stream.js +++ b/test/parallel/test-pipe-stream.js @@ -6,8 +6,8 @@ const net = require('net'); common.refreshTmpDir(); function test(clazz, cb) { - var have_ping = false; - var have_pong = false; + let have_ping = false; + let have_pong = false; function check() { assert.ok(have_ping); @@ -15,7 +15,7 @@ function test(clazz, cb) { } function ping() { - var conn = new clazz(); + const conn = new clazz(); conn.on('error', function(err) { throw err; @@ -48,11 +48,11 @@ function test(clazz, cb) { }); } - var timeout = setTimeout(function() { + const timeout = setTimeout(function() { server.close(); }, 2000); - var server = net.Server(); + const server = net.Server(); server.listen(common.PIPE, ping); server.on('connection', pong); server.on('close', function() { diff --git a/test/parallel/test-pipe-unref.js b/test/parallel/test-pipe-unref.js index f926dab3e5c98b..34b5ef651bf6aa 100644 --- a/test/parallel/test-pipe-unref.js +++ b/test/parallel/test-pipe-unref.js @@ -4,7 +4,7 @@ const net = require('net'); common.refreshTmpDir(); -var s = net.Server(); +const s = net.Server(); s.listen(common.PIPE); s.unref(); diff --git a/test/parallel/test-preload.js b/test/parallel/test-preload.js index 3413a2a6dc69c8..444c3a0a6d5e2b 100644 --- a/test/parallel/test-preload.js +++ b/test/parallel/test-preload.js @@ -14,7 +14,7 @@ if (common.isSunOS) { const nodeBinary = process.argv[0]; const preloadOption = function(preloads) { - var option = ''; + let option = ''; preloads.forEach(function(preload, index) { option += '-r ' + preload + ' '; }); @@ -75,7 +75,7 @@ const stdinProc = childProcess.spawn( {stdio: 'pipe'} ); stdinProc.stdin.end("console.log('hello');"); -var stdinStdout = ''; +let stdinStdout = ''; stdinProc.stdout.on('data', function(d) { stdinStdout += d; }); @@ -91,7 +91,7 @@ const replProc = childProcess.spawn( {stdio: 'pipe'} ); replProc.stdin.end('.exit\n'); -var replStdout = ''; +let replStdout = ''; replProc.stdout.on('data', function(d) { replStdout += d; }); diff --git a/test/parallel/test-process-argv-0.js b/test/parallel/test-process-argv-0.js index ad078d02b41b03..d6b4bfe232323e 100644 --- a/test/parallel/test-process-argv-0.js +++ b/test/parallel/test-process-argv-0.js @@ -5,11 +5,11 @@ const assert = require('assert'); const spawn = require('child_process').spawn; if (process.argv[2] !== 'child') { - var child = spawn(process.execPath, [__filename, 'child'], { + const child = spawn(process.execPath, [__filename, 'child'], { cwd: path.dirname(process.execPath) }); - var childArgv0 = ''; + let childArgv0 = ''; child.stdout.on('data', function(chunk) { childArgv0 += chunk; }); diff --git a/test/parallel/test-process-config.js b/test/parallel/test-process-config.js index e692a7bf19ae47..a1767464fd5978 100644 --- a/test/parallel/test-process-config.js +++ b/test/parallel/test-process-config.js @@ -10,8 +10,8 @@ assert(process.hasOwnProperty('config')); // ensure that `process.config` is an Object assert.strictEqual(Object(process.config), process.config); -var configPath = path.resolve(__dirname, '..', '..', 'config.gypi'); -var config = fs.readFileSync(configPath, 'utf8'); +const configPath = path.resolve(__dirname, '..', '..', 'config.gypi'); +let config = fs.readFileSync(configPath, 'utf8'); // clean up comment at the first line config = config.split('\n').slice(1).join('\n').replace(/'/g, '"'); diff --git a/test/parallel/test-process-exec-argv.js b/test/parallel/test-process-exec-argv.js index c7de82adae3e97..8125850b424d84 100644 --- a/test/parallel/test-process-exec-argv.js +++ b/test/parallel/test-process-exec-argv.js @@ -6,10 +6,10 @@ const spawn = require('child_process').spawn; if (process.argv[2] === 'child') { process.stdout.write(JSON.stringify(process.execArgv)); } else { - var execArgv = ['--stack-size=256']; - var args = [__filename, 'child', 'arg0']; - var child = spawn(process.execPath, execArgv.concat(args)); - var out = ''; + const execArgv = ['--stack-size=256']; + const args = [__filename, 'child', 'arg0']; + const child = spawn(process.execPath, execArgv.concat(args)); + let out = ''; child.stdout.on('data', function(chunk) { out += chunk; diff --git a/test/parallel/test-process-exit-code.js b/test/parallel/test-process-exit-code.js index b93ae443a73eae..337502ffcb30e8 100644 --- a/test/parallel/test-process-exit-code.js +++ b/test/parallel/test-process-exit-code.js @@ -71,9 +71,9 @@ function parent() { function test(arg, exit) { const spawn = require('child_process').spawn; - var node = process.execPath; - var f = __filename; - var option = { stdio: [ 0, 1, 'ignore' ] }; + const node = process.execPath; + const f = __filename; + const option = { stdio: [ 0, 1, 'ignore' ] }; spawn(node, [f, arg], option).on('exit', function(code) { assert.equal(code, exit, 'wrong exit for ' + arg + '\nexpected:' + exit + diff --git a/test/parallel/test-process-exit-recursive.js b/test/parallel/test-process-exit-recursive.js index 252b282b04886c..1634aad15497f5 100644 --- a/test/parallel/test-process-exit-recursive.js +++ b/test/parallel/test-process-exit-recursive.js @@ -3,7 +3,7 @@ require('../common'); const assert = require('assert'); // recursively calling .exit() should not overflow the call stack -var nexits = 0; +let nexits = 0; process.on('exit', function(code) { assert.equal(nexits++, 0); diff --git a/test/parallel/test-process-exit.js b/test/parallel/test-process-exit.js index 9d48ea9eacfe6f..f7df7737ed1531 100644 --- a/test/parallel/test-process-exit.js +++ b/test/parallel/test-process-exit.js @@ -3,7 +3,7 @@ require('../common'); const assert = require('assert'); // calling .exit() from within "exit" should not overflow the call stack -var nexits = 0; +let nexits = 0; process.on('exit', function(code) { assert.equal(nexits++, 0); diff --git a/test/parallel/test-process-getactivehandles.js b/test/parallel/test-process-getactivehandles.js index a9222c984b30ca..8ceb2bcd2a32f7 100644 --- a/test/parallel/test-process-getactivehandles.js +++ b/test/parallel/test-process-getactivehandles.js @@ -6,7 +6,7 @@ const net = require('net'); const NUM = 8; const connections = []; const clients = []; -var clients_counter = 0; +let clients_counter = 0; const server = net.createServer(function listener(c) { connections.push(c); diff --git a/test/parallel/test-process-getgroups.js b/test/parallel/test-process-getgroups.js index 9e08892b625f81..e92f04853976f7 100644 --- a/test/parallel/test-process-getgroups.js +++ b/test/parallel/test-process-getgroups.js @@ -9,12 +9,12 @@ if (common.isOSX) { } if (typeof process.getgroups === 'function') { - var groups = process.getgroups(); + const groups = process.getgroups(); assert(Array.isArray(groups)); assert(groups.length > 0); exec('id -G', function(err, stdout) { assert.ifError(err); - var real_groups = stdout.match(/\d+/g).map(Number); + const real_groups = stdout.match(/\d+/g).map(Number); assert.equal(groups.length, real_groups.length); check(groups, real_groups); check(real_groups, groups); @@ -22,5 +22,5 @@ if (typeof process.getgroups === 'function') { } function check(a, b) { - for (var i = 0; i < a.length; ++i) assert.notStrictEqual(b.indexOf(a[i]), -1); + for (let i = 0; i < a.length; ++i) assert.notStrictEqual(b.indexOf(a[i]), -1); } diff --git a/test/parallel/test-process-kill-null.js b/test/parallel/test-process-kill-null.js index 406b2943625365..6c0ee8fa049a50 100644 --- a/test/parallel/test-process-kill-null.js +++ b/test/parallel/test-process-kill-null.js @@ -3,8 +3,8 @@ require('../common'); const assert = require('assert'); const spawn = require('child_process').spawn; -var cat = spawn('cat'); -var called; +const cat = spawn('cat'); +let called; assert.ok(process.kill(cat.pid, 0)); diff --git a/test/parallel/test-process-kill-pid.js b/test/parallel/test-process-kill-pid.js index 9b4a5fa47a87cb..2c6ef37fc120df 100644 --- a/test/parallel/test-process-kill-pid.js +++ b/test/parallel/test-process-kill-pid.js @@ -34,9 +34,9 @@ assert.throws(function() { process.kill(1, 'test'); }, Error); // that we don't kill our process group, or try to actually send ANY signals on // windows, which doesn't support them. function kill(tryPid, trySig, expectPid, expectSig) { - var getPid; - var getSig; - var origKill = process._kill; + let getPid; + let getSig; + const origKill = process._kill; process._kill = function(pid, sig) { getPid = pid; getSig = sig; diff --git a/test/parallel/test-process-next-tick.js b/test/parallel/test-process-next-tick.js index 343511445280d4..e67ebae0a29559 100644 --- a/test/parallel/test-process-next-tick.js +++ b/test/parallel/test-process-next-tick.js @@ -1,12 +1,12 @@ 'use strict'; const common = require('../common'); -var N = 2; +const N = 2; function cb() { throw new Error(); } -for (var i = 0; i < N; ++i) { +for (let i = 0; i < N; ++i) { process.nextTick(common.mustCall(cb)); } diff --git a/test/parallel/test-process-raw-debug.js b/test/parallel/test-process-raw-debug.js index 41774cb87a989f..74c99b1f8f8058 100644 --- a/test/parallel/test-process-raw-debug.js +++ b/test/parallel/test-process-raw-debug.js @@ -14,9 +14,9 @@ switch (process.argv[2]) { function parent() { const spawn = require('child_process').spawn; - var child = spawn(process.execPath, [__filename, 'child']); + const child = spawn(process.execPath, [__filename, 'child']); - var output = ''; + let output = ''; child.stderr.on('data', function(c) { output += c; @@ -42,7 +42,7 @@ function child() { throw new Error('No ticking!'); }; - var stderr = process.stderr; + const stderr = process.stderr; stderr.write = function() { throw new Error('No writing to stderr!'); }; diff --git a/test/parallel/test-process-remove-all-signal-listeners.js b/test/parallel/test-process-remove-all-signal-listeners.js index 131d57cdfccaa7..76a96f7683e452 100644 --- a/test/parallel/test-process-remove-all-signal-listeners.js +++ b/test/parallel/test-process-remove-all-signal-listeners.js @@ -14,7 +14,7 @@ if (process.argv[2] !== '--do-test') { // We are the master, fork a child so we can verify it exits with correct // status. process.env.DOTEST = 'y'; - var child = spawn(process.execPath, [__filename, '--do-test']); + const child = spawn(process.execPath, [__filename, '--do-test']); child.once('exit', common.mustCall(function(code, signal) { assert.equal(signal, 'SIGINT'); diff --git a/test/parallel/test-process-versions.js b/test/parallel/test-process-versions.js index 181e3ecef2bdb0..8532b259e01092 100644 --- a/test/parallel/test-process-versions.js +++ b/test/parallel/test-process-versions.js @@ -2,8 +2,8 @@ const common = require('../common'); const assert = require('assert'); -var expected_keys = ['ares', 'http_parser', 'modules', 'node', - 'uv', 'v8', 'zlib']; +const expected_keys = ['ares', 'http_parser', 'modules', 'node', + 'uv', 'v8', 'zlib']; if (common.hasCrypto) { expected_keys.push('openssl'); diff --git a/test/parallel/test-process-wrap.js b/test/parallel/test-process-wrap.js index 08e1b152ed9e07..326854e98335df 100644 --- a/test/parallel/test-process-wrap.js +++ b/test/parallel/test-process-wrap.js @@ -1,14 +1,14 @@ 'use strict'; require('../common'); const assert = require('assert'); -var Process = process.binding('process_wrap').Process; -var Pipe = process.binding('pipe_wrap').Pipe; -var pipe = new Pipe(); -var p = new Process(); +const Process = process.binding('process_wrap').Process; +const Pipe = process.binding('pipe_wrap').Pipe; +const pipe = new Pipe(); +const p = new Process(); -var processExited = false; -var gotPipeEOF = false; -var gotPipeData = false; +let processExited = false; +let gotPipeEOF = false; +let gotPipeData = false; p.onexit = function(exitCode, signal) { console.log('exit'); @@ -45,7 +45,7 @@ p.spawn({ // 'this' safety // https://github.com/joyent/node/issues/6690 assert.throws(function() { - var notp = { spawn: p.spawn }; + const notp = { spawn: p.spawn }; notp.spawn({ file: process.execPath, args: [process.execPath, '-v'], diff --git a/test/parallel/test-promises-unhandled-rejections.js b/test/parallel/test-promises-unhandled-rejections.js index e275dac238cffc..27cb94bf704eb4 100644 --- a/test/parallel/test-promises-unhandled-rejections.js +++ b/test/parallel/test-promises-unhandled-rejections.js @@ -3,15 +3,15 @@ const common = require('../common'); const assert = require('assert'); const domain = require('domain'); -var asyncTest = (function() { - var asyncTestsEnabled = false; - var asyncTestLastCheck; - var asyncTestQueue = []; - var asyncTestHandle; - var currentTest = null; +const asyncTest = (function() { + let asyncTestsEnabled = false; + let asyncTestLastCheck; + const asyncTestQueue = []; + let asyncTestHandle; + let currentTest = null; function fail(error) { - var stack = currentTest ? + const stack = currentTest ? error.stack + '\nFrom previous event:\n' + currentTest.stack : error.stack; @@ -23,7 +23,7 @@ var asyncTest = (function() { } function nextAsyncTest() { - var called = false; + let called = false; function done(err) { if (called) return fail(new Error('done called twice')); called = true; @@ -33,7 +33,7 @@ var asyncTest = (function() { } if (asyncTestQueue.length) { - var test = asyncTestQueue.shift(); + const test = asyncTestQueue.shift(); currentTest = test; test.action(done); } else { @@ -42,7 +42,7 @@ var asyncTest = (function() { } return function asyncTest(description, fn) { - var stack = new Error().stack.split('\n').slice(1).join('\n'); + const stack = new Error().stack.split('\n').slice(1).join('\n'); asyncTestQueue.push({ action: fn, stack: stack, @@ -53,7 +53,7 @@ var asyncTest = (function() { asyncTestLastCheck = Date.now(); process.on('uncaughtException', fail); asyncTestHandle = setInterval(function() { - var now = Date.now(); + const now = Date.now(); if (now - asyncTestLastCheck > 10000) { return fail(new Error('Async test timeout exceeded')); } @@ -65,7 +65,7 @@ var asyncTest = (function() { })(); function setupException(fn) { - var listeners = process.listeners('uncaughtException'); + const listeners = process.listeners('uncaughtException'); process.removeAllListeners('uncaughtException'); process.on('uncaughtException', fn); return function clean() { @@ -108,7 +108,7 @@ function onUnhandledFail(done) { asyncTest('synchronously rejected promise should trigger' + ' unhandledRejection', function(done) { - var e = new Error(); + const e = new Error(); onUnhandledSucceed(done, function(reason, promise) { assert.strictEqual(e, reason); }); @@ -117,7 +117,7 @@ asyncTest('synchronously rejected promise should trigger' + asyncTest('synchronously rejected promise should trigger' + ' unhandledRejection', function(done) { - var e = new Error(); + const e = new Error(); onUnhandledSucceed(done, function(reason, promise) { assert.strictEqual(e, reason); }); @@ -128,7 +128,7 @@ asyncTest('synchronously rejected promise should trigger' + asyncTest('Promise rejected after setImmediate should trigger' + ' unhandledRejection', function(done) { - var e = new Error(); + const e = new Error(); onUnhandledSucceed(done, function(reason, promise) { assert.strictEqual(e, reason); }); @@ -141,7 +141,7 @@ asyncTest('Promise rejected after setImmediate should trigger' + asyncTest('Promise rejected after setTimeout(,1) should trigger' + ' unhandled rejection', function(done) { - var e = new Error(); + const e = new Error(); onUnhandledSucceed(done, function(reason, promise) { assert.strictEqual(e, reason); }); @@ -154,12 +154,12 @@ asyncTest('Promise rejected after setTimeout(,1) should trigger' + asyncTest('Catching a promise rejection after setImmediate is not' + ' soon enough to stop unhandledRejection', function(done) { - var e = new Error(); + const e = new Error(); onUnhandledSucceed(done, function(reason, promise) { assert.strictEqual(e, reason); }); - var _reject; - var promise = new Promise(function(_, reject) { + let _reject; + const promise = new Promise(function(_, reject) { _reject = reject; }); _reject(e); @@ -170,13 +170,13 @@ asyncTest('Catching a promise rejection after setImmediate is not' + asyncTest('When re-throwing new errors in a promise catch, only the' + ' re-thrown error should hit unhandledRejection', function(done) { - var e = new Error(); - var e2 = new Error(); + const e = new Error(); + const e2 = new Error(); onUnhandledSucceed(done, function(reason, promise) { assert.strictEqual(e2, reason); assert.strictEqual(promise2, promise); }); - var promise2 = Promise.reject(e).then(common.fail, function(reason) { + const promise2 = Promise.reject(e).then(common.fail, function(reason) { assert.strictEqual(e, reason); throw e2; }); @@ -184,7 +184,7 @@ asyncTest('When re-throwing new errors in a promise catch, only the' + asyncTest('Test params of unhandledRejection for a synchronously-rejected' + 'promise', function(done) { - var e = new Error(); + const e = new Error(); onUnhandledSucceed(done, function(reason, promise) { assert.strictEqual(e, reason); assert.strictEqual(promise, promise); @@ -195,13 +195,13 @@ asyncTest('Test params of unhandledRejection for a synchronously-rejected' + asyncTest('When re-throwing new errors in a promise catch, only the ' + 're-thrown error should hit unhandledRejection: original promise' + ' rejected async with setTimeout(,1)', function(done) { - var e = new Error(); - var e2 = new Error(); + const e = new Error(); + const e2 = new Error(); onUnhandledSucceed(done, function(reason, promise) { assert.strictEqual(e2, reason); assert.strictEqual(promise2, promise); }); - var promise2 = new Promise(function(_, reject) { + const promise2 = new Promise(function(_, reject) { setTimeout(function() { reject(e); }, 1); @@ -214,13 +214,13 @@ asyncTest('When re-throwing new errors in a promise catch, only the ' + asyncTest('When re-throwing new errors in a promise catch, only the re-thrown' + ' error should hit unhandledRejection: promise catch attached a' + ' process.nextTick after rejection', function(done) { - var e = new Error(); - var e2 = new Error(); + const e = new Error(); + const e2 = new Error(); onUnhandledSucceed(done, function(reason, promise) { assert.strictEqual(e2, reason); assert.strictEqual(promise2, promise); }); - var promise = new Promise(function(_, reject) { + const promise = new Promise(function(_, reject) { setTimeout(function() { reject(e); process.nextTick(function() { @@ -231,14 +231,14 @@ asyncTest('When re-throwing new errors in a promise catch, only the re-thrown' + }); }, 1); }); - var promise2; + let promise2; }); asyncTest( 'unhandledRejection should not be triggered if a promise catch is' + ' attached synchronously upon the promise\'s creation', function(done) { - var e = new Error(); + const e = new Error(); onUnhandledFail(done); Promise.reject(e).then(common.fail, function() {}); } @@ -248,7 +248,7 @@ asyncTest( 'unhandledRejection should not be triggered if a promise catch is' + ' attached synchronously upon the promise\'s creation', function(done) { - var e = new Error(); + const e = new Error(); onUnhandledFail(done); new Promise(function(_, reject) { reject(e); @@ -258,9 +258,9 @@ asyncTest( asyncTest('Attaching a promise catch in a process.nextTick is soon enough to' + ' prevent unhandledRejection', function(done) { - var e = new Error(); + const e = new Error(); onUnhandledFail(done); - var promise = Promise.reject(e); + const promise = Promise.reject(e); process.nextTick(function() { promise.then(common.fail, function() {}); }); @@ -268,9 +268,9 @@ asyncTest('Attaching a promise catch in a process.nextTick is soon enough to' + asyncTest('Attaching a promise catch in a process.nextTick is soon enough to' + ' prevent unhandledRejection', function(done) { - var e = new Error(); + const e = new Error(); onUnhandledFail(done); - var promise = new Promise(function(_, reject) { + const promise = new Promise(function(_, reject) { reject(e); }); process.nextTick(function() { @@ -297,7 +297,7 @@ asyncTest('While inside setImmediate, catching a rejected promise derived ' + asyncTest('catching a promise which is asynchronously rejected (via' + 'resolution to an asynchronously-rejected promise) prevents' + ' unhandledRejection', function(done) { - var e = new Error(); + const e = new Error(); onUnhandledFail(done); Promise.resolve().then(function() { return new Promise(function(_, reject) { @@ -312,7 +312,7 @@ asyncTest('catching a promise which is asynchronously rejected (via' + asyncTest('Catching a rejected promise derived from throwing in a' + ' fulfillment handler prevents unhandledRejection', function(done) { - var e = new Error(); + const e = new Error(); onUnhandledFail(done); Promise.resolve().then(function() { throw e; @@ -324,7 +324,7 @@ asyncTest('Catching a rejected promise derived from throwing in a' + asyncTest('Catching a rejected promise derived from returning a' + ' synchronously-rejected promise in a fulfillment handler' + ' prevents unhandledRejection', function(done) { - var e = new Error(); + const e = new Error(); onUnhandledFail(done); Promise.resolve().then(function() { return Promise.reject(e); @@ -336,13 +336,12 @@ asyncTest('Catching a rejected promise derived from returning a' + asyncTest('A rejected promise derived from returning an' + ' asynchronously-rejected promise in a fulfillment handler' + ' does trigger unhandledRejection', function(done) { - var e = new Error(); - var _promise; + const e = new Error(); onUnhandledSucceed(done, function(reason, promise) { assert.strictEqual(e, reason); assert.strictEqual(_promise, promise); }); - _promise = Promise.resolve().then(function() { + const _promise = Promise.resolve().then(function() { return new Promise(function(_, reject) { setTimeout(function() { reject(e); @@ -353,13 +352,12 @@ asyncTest('A rejected promise derived from returning an' + asyncTest('A rejected promise derived from throwing in a fulfillment handler' + ' does trigger unhandledRejection', function(done) { - var e = new Error(); - var _promise; + const e = new Error(); onUnhandledSucceed(done, function(reason, promise) { assert.strictEqual(e, reason); assert.strictEqual(_promise, promise); }); - _promise = Promise.resolve().then(function() { + const _promise = Promise.resolve().then(function() { throw e; }); }); @@ -368,13 +366,12 @@ asyncTest( 'A rejected promise derived from returning a synchronously-rejected' + ' promise in a fulfillment handler does trigger unhandledRejection', function(done) { - var e = new Error(); - var _promise; + const e = new Error(); onUnhandledSucceed(done, function(reason, promise) { assert.strictEqual(e, reason); assert.strictEqual(_promise, promise); }); - _promise = Promise.resolve().then(function() { + const _promise = Promise.resolve().then(function() { return Promise.reject(e); }); } @@ -383,7 +380,7 @@ asyncTest( // Combinations with Promise.all asyncTest('Catching the Promise.all() of a collection that includes a' + 'rejected promise prevents unhandledRejection', function(done) { - var e = new Error(); + const e = new Error(); onUnhandledFail(done); Promise.all([Promise.reject(e)]).then(common.fail, function() {}); }); @@ -392,9 +389,9 @@ asyncTest( 'Catching the Promise.all() of a collection that includes a ' + 'nextTick-async rejected promise prevents unhandledRejection', function(done) { - var e = new Error(); + const e = new Error(); onUnhandledFail(done); - var p = new Promise(function(_, reject) { + let p = new Promise(function(_, reject) { process.nextTick(function() { reject(e); }); @@ -409,19 +406,19 @@ asyncTest( asyncTest('Failing to catch the Promise.all() of a collection that includes' + ' a rejected promise triggers unhandledRejection for the returned' + ' promise, not the passed promise', function(done) { - var e = new Error(); + const e = new Error(); onUnhandledSucceed(done, function(reason, promise) { assert.strictEqual(e, reason); assert.strictEqual(p, promise); }); - var p = Promise.all([Promise.reject(e)]); + const p = Promise.all([Promise.reject(e)]); }); asyncTest('Waiting setTimeout(, 10) to catch a promise causes an' + ' unhandledRejection + rejectionHandled pair', function(done) { clean(); - var unhandledPromises = []; - var e = new Error(); + const unhandledPromises = []; + const e = new Error(); process.on('unhandledRejection', function(reason, promise) { assert.strictEqual(e, reason); unhandledPromises.push(promise); @@ -433,7 +430,7 @@ asyncTest('Waiting setTimeout(, 10) to catch a promise causes an' + done(); }); - var thePromise = new Promise(function() { + const thePromise = new Promise(function() { throw e; }); setTimeout(function() { @@ -446,11 +443,11 @@ asyncTest('Waiting setTimeout(, 10) to catch a promise causes an' + asyncTest('Waiting for some combination of process.nextTick + promise' + ' microtasks to attach a catch handler is still soon enough to' + ' prevent unhandledRejection', function(done) { - var e = new Error(); + const e = new Error(); onUnhandledFail(done); - var a = Promise.reject(e); + const a = Promise.reject(e); process.nextTick(function() { Promise.resolve().then(function() { process.nextTick(function() { @@ -465,11 +462,11 @@ asyncTest('Waiting for some combination of process.nextTick + promise' + asyncTest('Waiting for some combination of process.nextTick + promise' + ' microtasks to attach a catch handler is still soon enough to ' + 'prevent unhandledRejection: inside setImmediate', function(done) { - var e = new Error(); + const e = new Error(); onUnhandledFail(done); setImmediate(function() { - var a = Promise.reject(e); + const a = Promise.reject(e); process.nextTick(function() { Promise.resolve().then(function() { process.nextTick(function() { @@ -485,11 +482,11 @@ asyncTest('Waiting for some combination of process.nextTick + promise' + asyncTest('Waiting for some combination of process.nextTick + promise ' + 'microtasks to attach a catch handler is still soon enough to ' + 'prevent unhandledRejection: inside setTimeout', function(done) { - var e = new Error(); + const e = new Error(); onUnhandledFail(done); setTimeout(function() { - var a = Promise.reject(e); + const a = Promise.reject(e); process.nextTick(function() { Promise.resolve().then(function() { process.nextTick(function() { @@ -505,11 +502,11 @@ asyncTest('Waiting for some combination of process.nextTick + promise ' + asyncTest('Waiting for some combination of promise microtasks + ' + 'process.nextTick to attach a catch handler is still soon enough' + ' to prevent unhandledRejection', function(done) { - var e = new Error(); + const e = new Error(); onUnhandledFail(done); - var a = Promise.reject(e); + const a = Promise.reject(e); Promise.resolve().then(function() { process.nextTick(function() { Promise.resolve().then(function() { @@ -526,11 +523,11 @@ asyncTest( ' process.nextTick to attach a catch handler is still soon enough' + ' to prevent unhandledRejection: inside setImmediate', function(done) { - var e = new Error(); + const e = new Error(); onUnhandledFail(done); setImmediate(function() { - var a = Promise.reject(e); + const a = Promise.reject(e); Promise.resolve().then(function() { process.nextTick(function() { Promise.resolve().then(function() { @@ -547,11 +544,11 @@ asyncTest( asyncTest('Waiting for some combination of promise microtasks +' + ' process.nextTick to attach a catch handler is still soon enough' + ' to prevent unhandledRejection: inside setTimeout', function(done) { - var e = new Error(); + const e = new Error(); onUnhandledFail(done); setTimeout(function() { - var a = Promise.reject(e); + const a = Promise.reject(e); Promise.resolve().then(function() { process.nextTick(function() { Promise.resolve().then(function() { @@ -567,12 +564,12 @@ asyncTest('Waiting for some combination of promise microtasks +' + asyncTest('setImmediate + promise microtasks is too late to attach a catch' + ' handler; unhandledRejection will be triggered in that case.' + ' (setImmediate before promise creation/rejection)', function(done) { - var e = new Error(); + const e = new Error(); onUnhandledSucceed(done, function(reason, promise) { assert.strictEqual(e, reason); assert.strictEqual(p, promise); }); - var p = Promise.reject(e); + const p = Promise.reject(e); setImmediate(function() { Promise.resolve().then(function() { p.catch(function() {}); @@ -598,7 +595,7 @@ asyncTest('setImmediate + promise microtasks is too late to attach a catch' + }); }); }); - var p = Promise.reject(); + const p = Promise.reject(); }); asyncTest('setImmediate + promise microtasks is too late to attach a catch' + @@ -608,7 +605,7 @@ asyncTest('setImmediate + promise microtasks is too late to attach a catch' + assert.strictEqual(undefined, reason); assert.strictEqual(p, promise); }); - var p = Promise.reject(); + const p = Promise.reject(); setImmediate(function() { Promise.resolve().then(function() { Promise.resolve().then(function() { @@ -626,14 +623,14 @@ asyncTest( 'Promise unhandledRejection handler does not interfere with domain' + ' error handlers being given exceptions thrown from nextTick.', function(done) { - var d = domain.create(); - var domainReceivedError; + const d = domain.create(); + let domainReceivedError; d.on('error', function(e) { domainReceivedError = e; }); d.run(function() { - var e = new Error('error'); - var domainError = new Error('domain error'); + const e = new Error('error'); + const domainError = new Error('domain error'); onUnhandledSucceed(done, function(reason, promise) { assert.strictEqual(reason, e); assert.strictEqual(domainReceivedError, domainError); @@ -650,9 +647,9 @@ asyncTest( asyncTest('nextTick is immediately scheduled when called inside an event' + ' handler', function(done) { clean(); - var e = new Error('error'); + const e = new Error('error'); process.on('unhandledRejection', function(reason, promise) { - var order = []; + const order = []; process.nextTick(function() { order.push(1); }); @@ -669,9 +666,9 @@ asyncTest('Throwing an error inside a rejectionHandled handler goes to' + ' unhandledException, and does not cause .catch() to throw an' + 'exception', function(done) { clean(); - var e = new Error(); - var e2 = new Error(); - var tearDownException = setupException(function(err) { + const e = new Error(); + const e2 = new Error(); + const tearDownException = setupException(function(err) { assert.equal(e2, err); tearDownException(); done(); @@ -679,7 +676,7 @@ asyncTest('Throwing an error inside a rejectionHandled handler goes to' + process.on('rejectionHandled', function() { throw e2; }); - var p = Promise.reject(e); + const p = Promise.reject(e); setTimeout(function() { try { p.catch(function() {}); diff --git a/test/parallel/test-promises-warning-on-unhandled-rejection.js b/test/parallel/test-promises-warning-on-unhandled-rejection.js index b50a5cae416942..10f95162a09597 100644 --- a/test/parallel/test-promises-warning-on-unhandled-rejection.js +++ b/test/parallel/test-promises-warning-on-unhandled-rejection.js @@ -7,7 +7,7 @@ const common = require('../common'); const assert = require('assert'); -var b = 0; +let b = 0; process.on('warning', common.mustCall((warning) => { switch (b++) { diff --git a/test/parallel/test-querystring-maxKeys-non-finite.js b/test/parallel/test-querystring-maxKeys-non-finite.js index aab7c45f1b6bed..8aa47f7de0e2dc 100644 --- a/test/parallel/test-querystring-maxKeys-non-finite.js +++ b/test/parallel/test-querystring-maxKeys-non-finite.js @@ -13,7 +13,7 @@ https://github.com/expressjs/body-parser/ blob/ed25264fb494cf0c8bc992b8257092cd4f694d5e/test/urlencoded.js#L636-L651 */ function createManyParams(count) { - var str = ''; + let str = ''; if (count === 0) { return str; @@ -21,8 +21,8 @@ function createManyParams(count) { str += '0=0'; - for (var i = 1; i < count; i++) { - var n = i.toString(36); + for (let i = 1; i < count; i++) { + const n = i.toString(36); str += '&' + n + '=' + n; } diff --git a/test/parallel/test-querystring.js b/test/parallel/test-querystring.js index 7192ac6a1bbff0..8cc589944b0508 100644 --- a/test/parallel/test-querystring.js +++ b/test/parallel/test-querystring.js @@ -15,7 +15,7 @@ function createWithNoPrototype(properties) { // folding block, commented to pass gjslint // {{{ // [ wonkyQS, canonicalQS, obj ] -var qsTestCases = [ +const qsTestCases = [ ['__proto__=1', '__proto__=1', createWithNoPrototype([{key: '__proto__', value: '1'}])], @@ -56,7 +56,7 @@ var qsTestCases = [ ]; // [ wonkyQS, canonicalQS, obj ] -var qsColonTestCases = [ +const qsColonTestCases = [ ['foo:bar', 'foo:bar', {'foo': 'bar'}], ['foo:bar;foo:quux', 'foo:bar;foo:quux', {'foo': ['bar', 'quux']}], ['foo:1&bar:2;baz:quux', @@ -67,9 +67,9 @@ var qsColonTestCases = [ ]; // [wonkyObj, qs, canonicalObj] -var extendedFunction = function() {}; +const extendedFunction = function() {}; extendedFunction.prototype = {a: 'b'}; -var qsWeirdObjects = [ +const qsWeirdObjects = [ [{regexp: /./g}, 'regexp=', {'regexp': ''}], [{regexp: new RegExp('.', 'g')}, 'regexp=', {'regexp': ''}], [{fn: function() {}}, 'fn=', {'fn': ''}], @@ -88,9 +88,9 @@ var qsWeirdObjects = [ // }}} const vm = require('vm'); -var foreignObject = vm.runInNewContext('({"foo": ["bar", "baz"]})'); +const foreignObject = vm.runInNewContext('({"foo": ["bar", "baz"]})'); -var qsNoMungeTestCases = [ +const qsNoMungeTestCases = [ ['', {}], ['foo=bar&foo=baz', {'foo': ['bar', 'baz']}], ['foo=bar&foo=baz', foreignObject], @@ -232,7 +232,7 @@ assert.equal( function testUnlimitedKeys() { const query = {}; - for (var i = 0; i < 2000; i++) query[i] = i; + for (let i = 0; i < 2000; i++) query[i] = i; const url = qs.stringify(query); @@ -243,7 +243,7 @@ function testUnlimitedKeys() { testUnlimitedKeys(); -var b = qs.unescapeBuffer('%d3%f2Ug%1f6v%24%5e%98%cb' + +const b = qs.unescapeBuffer('%d3%f2Ug%1f6v%24%5e%98%cb' + '%0d%ac%a2%2f%9d%eb%d8%a2%e6'); // assert.equal(0xd3, b[0]); @@ -280,13 +280,13 @@ check(qs.parse('a=a&b=b&c=c', null, null, { decodeURIComponent: demoDecode }), function demoEncode(str) { return str[0]; } -var obj = { aa: 'aa', bb: 'bb', cc: 'cc' }; +const obj = { aa: 'aa', bb: 'bb', cc: 'cc' }; assert.equal( qs.stringify(obj, null, null, { encodeURIComponent: demoEncode }), 'a=a&b=b&c=c'); // test overriding .unescape -var prevUnescape = qs.unescape; +const prevUnescape = qs.unescape; qs.unescape = function(str) { return str.replace(/o/g, '_'); }; diff --git a/test/parallel/test-readdouble.js b/test/parallel/test-readdouble.js index a6fc91c351f089..728a2b4605d9ff 100644 --- a/test/parallel/test-readdouble.js +++ b/test/parallel/test-readdouble.js @@ -9,7 +9,7 @@ const assert = require('assert'); * Test (64 bit) double */ function test(clazz) { - var buffer = new clazz(8); + const buffer = new clazz(8); buffer[0] = 0x55; buffer[1] = 0x55; diff --git a/test/parallel/test-readfloat.js b/test/parallel/test-readfloat.js index 533b7caa8f1047..437e4778671bd2 100644 --- a/test/parallel/test-readfloat.js +++ b/test/parallel/test-readfloat.js @@ -9,7 +9,7 @@ const assert = require('assert'); * Test (32 bit) float */ function test(clazz) { - var buffer = new clazz(4); + const buffer = new clazz(4); buffer[0] = 0; buffer[1] = 0; diff --git a/test/parallel/test-readint.js b/test/parallel/test-readint.js index c068ddcb6c554a..086dd4e3aa0d1a 100644 --- a/test/parallel/test-readint.js +++ b/test/parallel/test-readint.js @@ -9,7 +9,7 @@ const assert = require('assert'); * Test 8 bit signed integers */ function test8(clazz) { - var data = new clazz(4); + const data = new clazz(4); data[0] = 0x23; assert.equal(0x23, data.readInt8(0)); @@ -29,7 +29,7 @@ function test8(clazz) { function test16(clazz) { - var buffer = new clazz(6); + const buffer = new clazz(6); buffer[0] = 0x16; buffer[1] = 0x79; @@ -62,7 +62,7 @@ function test16(clazz) { function test32(clazz) { - var buffer = new clazz(6); + const buffer = new clazz(6); buffer[0] = 0x43; buffer[1] = 0x53; diff --git a/test/parallel/test-readline-interface.js b/test/parallel/test-readline-interface.js index 509995bc9ad619..e8fc92ad1c9e27 100644 --- a/test/parallel/test-readline-interface.js +++ b/test/parallel/test-readline-interface.js @@ -19,8 +19,8 @@ FakeInput.prototype.write = function() {}; FakeInput.prototype.end = function() {}; function isWarned(emitter) { - for (var name in emitter) { - var listeners = emitter[name]; + for (const name in emitter) { + const listeners = emitter[name]; if (listeners.warned) return true; } return false; @@ -55,9 +55,9 @@ function isWarned(emitter) { } [ true, false ].forEach(function(terminal) { - var fi; - var rli; - var called; + let fi; + let rli; + let called; // disable history fi = new FakeInput(); @@ -128,8 +128,8 @@ function isWarned(emitter) { // sending multiple newlines at once fi = new FakeInput(); rli = new readline.Interface({ input: fi, output: fi, terminal: terminal }); - var expectedLines = ['foo', 'bar', 'baz']; - var callCount = 0; + let expectedLines = ['foo', 'bar', 'baz']; + let callCount = 0; rli.on('line', function(line) { assert.equal(line, expectedLines[callCount]); callCount++; @@ -267,7 +267,7 @@ function isWarned(emitter) { // \t does not become part of the input when there is a completer function fi = new FakeInput(); - var completer = function(line) { + const completer = function(line) { return [[], line]; }; rli = new readline.Interface({ @@ -282,7 +282,7 @@ function isWarned(emitter) { assert.strictEqual(called, false); called = true; }); - for (var character of '\tfo\to\t') { + for (const character of '\tfo\to\t') { fi.emit('data', character); } fi.emit('data', '\n'); @@ -306,7 +306,7 @@ function isWarned(emitter) { }); // sending a multi-byte utf8 char over multiple writes - var buf = Buffer.from('☮', 'utf8'); + const buf = Buffer.from('☮', 'utf8'); fi = new FakeInput(); rli = new readline.Interface({ input: fi, output: fi, terminal: terminal }); callCount = 0; @@ -326,7 +326,7 @@ function isWarned(emitter) { // check that nothing fails if 'keypress' event throws. fi = new FakeInput(); rli = new readline.Interface({ input: fi, output: fi, terminal: true }); - var keys = []; + const keys = []; fi.on('keypress', function(key) { keys.push(key); if (key === 'X') { @@ -360,7 +360,7 @@ function isWarned(emitter) { rli.question(expectedLines[0], function() { rli.close(); }); - var cursorPos = rli._getCursorPos(); + let cursorPos = rli._getCursorPos(); assert.equal(cursorPos.rows, 0); assert.equal(cursorPos.cols, expectedLines[0].length); rli.close(); @@ -421,8 +421,8 @@ function isWarned(emitter) { assert.deepStrictEqual(fi.listeners(terminal ? 'keypress' : 'data'), []); // check EventEmitter memory leak - for (var i = 0; i < 12; i++) { - var rl = readline.createInterface({ + for (let i = 0; i < 12; i++) { + const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); diff --git a/test/parallel/test-readline-keys.js b/test/parallel/test-readline-keys.js index eae4ba55b73e6e..258127655606f1 100644 --- a/test/parallel/test-readline-keys.js +++ b/test/parallel/test-readline-keys.js @@ -13,11 +13,11 @@ function FakeInput() { inherits(FakeInput, PassThrough); -var fi = new FakeInput(); -var fo = new FakeInput(); +const fi = new FakeInput(); +const fo = new FakeInput(); new Interface({ input: fi, output: fo, terminal: true }); -var keys = []; +let keys = []; fi.on('keypress', function(s, k) { keys.push(k); }); diff --git a/test/parallel/test-readline-set-raw-mode.js b/test/parallel/test-readline-set-raw-mode.js index e9e0ff4b4d05f0..78c42f5f5f627d 100644 --- a/test/parallel/test-readline-set-raw-mode.js +++ b/test/parallel/test-readline-set-raw-mode.js @@ -4,11 +4,11 @@ const assert = require('assert'); const readline = require('readline'); const Stream = require('stream'); -var stream = new Stream(); -var expectedRawMode = true; -var rawModeCalled = false; -var resumeCalled = false; -var pauseCalled = false; +const stream = new Stream(); +let expectedRawMode = true; +let rawModeCalled = false; +let resumeCalled = false; +let pauseCalled = false; stream.setRawMode = function(mode) { rawModeCalled = true; @@ -23,7 +23,7 @@ stream.pause = function() { // when the "readline" starts in "terminal" mode, // then setRawMode(true) should be called -var rli = readline.createInterface({ +const rli = readline.createInterface({ input: stream, output: stream, terminal: true diff --git a/test/parallel/test-readline-undefined-columns.js b/test/parallel/test-readline-undefined-columns.js index 5f8a1c02d3a90b..14895ac637429c 100644 --- a/test/parallel/test-readline-undefined-columns.js +++ b/test/parallel/test-readline-undefined-columns.js @@ -20,7 +20,7 @@ readline.createInterface({ } }); -var output = ''; +let output = ''; oStream.on('data', function(data) { output += data; diff --git a/test/parallel/test-readuint.js b/test/parallel/test-readuint.js index 9fcaf45603fd83..0d1f79b12eabd4 100644 --- a/test/parallel/test-readuint.js +++ b/test/parallel/test-readuint.js @@ -14,7 +14,7 @@ const assert = require('assert'); * - Correctly interpreting values that are beyond the signed range as unsigned */ function test8(clazz) { - var data = new clazz(4); + const data = new clazz(4); data[0] = 23; data[1] = 23; @@ -39,7 +39,7 @@ function test8(clazz) { * - Correctly interpreting values that are beyond the signed range as unsigned */ function test16(clazz) { - var data = new clazz(4); + const data = new clazz(4); data[0] = 0; data[1] = 0x23; @@ -67,7 +67,7 @@ function test16(clazz) { * - Correctly interpreting values that are beyond the signed range as unsigned */ function test32(clazz) { - var data = new clazz(8); + const data = new clazz(8); data[0] = 0x32; data[1] = 0x65; diff --git a/test/parallel/test-regress-GH-1531.js b/test/parallel/test-regress-GH-1531.js index 0ca1186d019183..5189e50929105c 100644 --- a/test/parallel/test-regress-GH-1531.js +++ b/test/parallel/test-regress-GH-1531.js @@ -9,12 +9,12 @@ const https = require('https'); const fs = require('fs'); -var options = { +const options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }; -var server = https.createServer(options, function(req, res) { +const server = https.createServer(options, function(req, res) { res.writeHead(200); res.end('hello world\n'); }); diff --git a/test/parallel/test-regress-GH-1899.js b/test/parallel/test-regress-GH-1899.js index 1c98b30a8d66fc..838391acd23b5f 100644 --- a/test/parallel/test-regress-GH-1899.js +++ b/test/parallel/test-regress-GH-1899.js @@ -4,10 +4,10 @@ const path = require('path'); const assert = require('assert'); const spawn = require('child_process').spawn; -var child = spawn(process.argv[0], [ +const child = spawn(process.argv[0], [ path.join(common.fixturesDir, 'GH-1899-output.js') ]); -var output = ''; +let output = ''; child.stdout.on('data', function(data) { output += data; diff --git a/test/parallel/test-regress-GH-2245.js b/test/parallel/test-regress-GH-2245.js index 129b1428d367cf..c5b0ae4982d993 100644 --- a/test/parallel/test-regress-GH-2245.js +++ b/test/parallel/test-regress-GH-2245.js @@ -10,7 +10,7 @@ their environment when evaluated. When run in 0.10 `test()` fails with a function test() { - var code = [ + const code = [ 'var foo = {m: 1};', '', 'function bar() {', diff --git a/test/parallel/test-regress-GH-3542.js b/test/parallel/test-regress-GH-3542.js index 8db34e72157371..cc0285f7475697 100644 --- a/test/parallel/test-regress-GH-3542.js +++ b/test/parallel/test-regress-GH-3542.js @@ -11,7 +11,7 @@ if (!common.isWindows) { } function test(p) { - var result = fs.realpathSync(p); + const result = fs.realpathSync(p); assert.strictEqual(result.toLowerCase(), path.resolve(p).toLowerCase()); fs.realpath(p, common.mustCall(function(err, result) { diff --git a/test/parallel/test-regress-GH-3739.js b/test/parallel/test-regress-GH-3739.js index 11caddae0847aa..b845a2b7f18f9a 100644 --- a/test/parallel/test-regress-GH-3739.js +++ b/test/parallel/test-regress-GH-3739.js @@ -5,13 +5,13 @@ const assert = require('assert'); const fs = require('fs'); const path = require('path'); -var dir = path.resolve(common.tmpDir); +let dir = path.resolve(common.tmpDir); // Make sure that the tmp directory is clean common.refreshTmpDir(); // Make a long path. -for (var i = 0; i < 50; i++) { +for (let i = 0; i < 50; i++) { dir = dir + '/1234567890'; try { fs.mkdirSync(dir, '0777'); diff --git a/test/parallel/test-regress-GH-4948.js b/test/parallel/test-regress-GH-4948.js index 69f4e4732470a5..196c973cd093e3 100644 --- a/test/parallel/test-regress-GH-4948.js +++ b/test/parallel/test-regress-GH-4948.js @@ -4,8 +4,8 @@ require('../common'); const http = require('http'); -var reqCount = 0; -var server = http.createServer(function(serverReq, serverRes) { +let reqCount = 0; +const server = http.createServer(function(serverReq, serverRes) { if (reqCount) { serverRes.end(); server.close(); @@ -16,8 +16,8 @@ var server = http.createServer(function(serverReq, serverRes) { // normally the use case would be to call an external site // does not require connecting locally or to itself to fail - var r = http.request({hostname: 'localhost', - port: this.address().port}, function(res) { + const r = http.request({hostname: 'localhost', + port: this.address().port}, function(res) { // required, just needs to be in the client response somewhere serverRes.end(); @@ -33,7 +33,7 @@ var server = http.createServer(function(serverReq, serverRes) { // simulate a client request that closes early const net = require('net'); - var sock = new net.Socket(); + const sock = new net.Socket(); sock.connect(this.address().port, 'localhost'); sock.on('connect', function() { diff --git a/test/parallel/test-regress-GH-5927.js b/test/parallel/test-regress-GH-5927.js index 779a2c2c649ed3..7f55356a15e027 100644 --- a/test/parallel/test-regress-GH-5927.js +++ b/test/parallel/test-regress-GH-5927.js @@ -3,18 +3,18 @@ require('../common'); const assert = require('assert'); const readline = require('readline'); -var rl = readline.createInterface(process.stdin, process.stdout); +const rl = readline.createInterface(process.stdin, process.stdout); rl.resume(); -var hasPaused = false; +let hasPaused = false; -var origPause = rl.pause; +const origPause = rl.pause; rl.pause = function() { hasPaused = true; origPause.apply(this, arguments); }; -var origSetRawMode = rl._setRawMode; +const origSetRawMode = rl._setRawMode; rl._setRawMode = function(mode) { assert.ok(hasPaused); origSetRawMode.apply(this, arguments); diff --git a/test/parallel/test-regress-GH-746.js b/test/parallel/test-regress-GH-746.js index a5e0d9d447360e..9a6e0e8980f311 100644 --- a/test/parallel/test-regress-GH-746.js +++ b/test/parallel/test-regress-GH-746.js @@ -7,7 +7,7 @@ const net = require('net'); process.stdin.destroy(); -var server = net.createServer(common.mustCall(function(socket) { +const server = net.createServer(common.mustCall(function(socket) { console.log('accepted'); socket.end(); server.close(); diff --git a/test/parallel/test-regress-GH-7511.js b/test/parallel/test-regress-GH-7511.js index 97e2fdb8114193..a7ce8311d7237f 100644 --- a/test/parallel/test-regress-GH-7511.js +++ b/test/parallel/test-regress-GH-7511.js @@ -4,7 +4,7 @@ const assert = require('assert'); const vm = require('vm'); assert.doesNotThrow(function() { - var context = vm.createContext({ process: process }); - var result = vm.runInContext('process.env["PATH"]', context); + const context = vm.createContext({ process: process }); + const result = vm.runInContext('process.env["PATH"]', context); assert.notStrictEqual(undefined, result); }); diff --git a/test/parallel/test-regress-GH-819.js b/test/parallel/test-regress-GH-819.js index bc2201b614974b..719d4398251eab 100644 --- a/test/parallel/test-regress-GH-819.js +++ b/test/parallel/test-regress-GH-819.js @@ -3,5 +3,5 @@ require('../common'); const net = require('net'); // Connect to something that we need to DNS resolve -var c = net.createConnection(80, 'google.com'); +const c = net.createConnection(80, 'google.com'); c.destroy(); diff --git a/test/parallel/test-regress-GH-node-9326.js b/test/parallel/test-regress-GH-node-9326.js index 3dbbe2958b8aef..78565e3f596594 100644 --- a/test/parallel/test-regress-GH-node-9326.js +++ b/test/parallel/test-regress-GH-node-9326.js @@ -4,7 +4,7 @@ const assert = require('assert'); const child_process = require('child_process'); // NOTE: Was crashing on FreeBSD -var cp = child_process.spawn(process.execPath, [ +const cp = child_process.spawn(process.execPath, [ '-e', 'process.kill(process.pid, "SIGINT")' ]); diff --git a/test/parallel/test-repl-.save.load.js b/test/parallel/test-repl-.save.load.js index 98417e0d063d57..00d5f6791d54a5 100644 --- a/test/parallel/test-repl-.save.load.js +++ b/test/parallel/test-repl-.save.load.js @@ -8,17 +8,17 @@ common.refreshTmpDir(); const repl = require('repl'); -var works = [['inner.one'], 'inner.o']; +const works = [['inner.one'], 'inner.o']; const putIn = new common.ArrayStream(); -var testMe = repl.start('', putIn); +const testMe = repl.start('', putIn); -var testFile = [ +const testFile = [ 'var top = function() {', 'var inner = {one:1};' ]; -var saveFileName = join(common.tmpDir, 'test.save.js'); +const saveFileName = join(common.tmpDir, 'test.save.js'); // input some data putIn.run(testFile); @@ -69,7 +69,7 @@ testMe.complete('inner.o', function(error, data) { // clear the REPL putIn.run(['.clear']); -var loadFile = join(common.tmpDir, 'file.does.not.exist'); +let loadFile = join(common.tmpDir, 'file.does.not.exist'); // should not break putIn.write = function(data) { diff --git a/test/parallel/test-repl-autolibs.js b/test/parallel/test-repl-autolibs.js index 3cc2ba4aa5988f..e0554831cdca50 100644 --- a/test/parallel/test-repl-autolibs.js +++ b/test/parallel/test-repl-autolibs.js @@ -13,7 +13,7 @@ repl.start('', putIn, null, true); test1(); function test1() { - var gotWrite = false; + let gotWrite = false; putIn.write = function(data) { gotWrite = true; if (data.length) { @@ -31,7 +31,7 @@ function test1() { } function test2() { - var gotWrite = false; + let gotWrite = false; putIn.write = function(data) { gotWrite = true; if (data.length) { @@ -41,7 +41,7 @@ function test2() { assert.equal(val, global.url); } }; - var val = {}; + const val = {}; global.url = val; assert(!gotWrite); putIn.run(['url']); diff --git a/test/parallel/test-repl-console.js b/test/parallel/test-repl-console.js index 98cb958cac8e68..f37dde008044ed 100644 --- a/test/parallel/test-repl-console.js +++ b/test/parallel/test-repl-console.js @@ -6,7 +6,7 @@ const repl = require('repl'); // Create a dummy stream that does nothing const stream = new common.ArrayStream(); -var r = repl.start({ +const r = repl.start({ input: stream, output: stream, useGlobal: false diff --git a/test/parallel/test-repl-definecommand.js b/test/parallel/test-repl-definecommand.js index 6c0c75bca8db79..07732d534e9def 100644 --- a/test/parallel/test-repl-definecommand.js +++ b/test/parallel/test-repl-definecommand.js @@ -6,7 +6,7 @@ const stream = require('stream'); const assert = require('assert'); const repl = require('repl'); -var output = ''; +let output = ''; const inputStream = new stream.PassThrough(); const outputStream = new stream.PassThrough(); outputStream.on('data', function(d) { diff --git a/test/parallel/test-repl-end-emits-exit.js b/test/parallel/test-repl-end-emits-exit.js index 7f2c4b9eb2893f..661f9f0ad0e3a4 100644 --- a/test/parallel/test-repl-end-emits-exit.js +++ b/test/parallel/test-repl-end-emits-exit.js @@ -9,7 +9,7 @@ let regularExit = 0; const stream = new common.ArrayStream(); function testTerminalMode() { - var r1 = repl.start({ + const r1 = repl.start({ input: stream, output: stream, terminal: true @@ -28,7 +28,7 @@ function testTerminalMode() { } function testRegularMode() { - var r2 = repl.start({ + const r2 = repl.start({ input: stream, output: stream, terminal: false diff --git a/test/parallel/test-repl-harmony.js b/test/parallel/test-repl-harmony.js index b3e25e62ab0a84..743bbe4fabfcd1 100644 --- a/test/parallel/test-repl-harmony.js +++ b/test/parallel/test-repl-harmony.js @@ -3,11 +3,11 @@ require('../common'); const assert = require('assert'); const spawn = require('child_process').spawn; -var args = ['-i']; -var child = spawn(process.execPath, args); +const args = ['-i']; +const child = spawn(process.execPath, args); -var input = '(function(){"use strict"; const y=1;y=2})()\n'; -var expectOut = /^> TypeError: Assignment to constant variable.\n/; +const input = '(function(){"use strict"; const y=1;y=2})()\n'; +const expectOut = /^> TypeError: Assignment to constant variable.\n/; child.stderr.setEncoding('utf8'); child.stderr.on('data', function(c) { @@ -15,7 +15,7 @@ child.stderr.on('data', function(c) { }); child.stdout.setEncoding('utf8'); -var out = ''; +let out = ''; child.stdout.on('data', function(c) { out += c; }); diff --git a/test/parallel/test-repl-history-perm.js b/test/parallel/test-repl-history-perm.js index 16732a44296f1d..25d2aa63ff0086 100644 --- a/test/parallel/test-repl-history-perm.js +++ b/test/parallel/test-repl-history-perm.js @@ -18,7 +18,7 @@ const Duplex = require('stream').Duplex; // Invoking the REPL should create a repl history file at the specified path // and mode 600. -var stream = new Duplex(); +const stream = new Duplex(); stream.pause = stream.resume = function() {}; // ends immediately stream._read = function() { diff --git a/test/parallel/test-repl-null.js b/test/parallel/test-repl-null.js index 337e194447d1f8..66d09b28f28b84 100644 --- a/test/parallel/test-repl-null.js +++ b/test/parallel/test-repl-null.js @@ -3,7 +3,7 @@ require('../common'); const repl = require('repl'); const assert = require('assert'); -var replserver = new repl.REPLServer(); +const replserver = new repl.REPLServer(); replserver._inTemplateLiteral = true; diff --git a/test/parallel/test-repl-options.js b/test/parallel/test-repl-options.js index 70244802dd0f45..79994c66d148c0 100644 --- a/test/parallel/test-repl-options.js +++ b/test/parallel/test-repl-options.js @@ -9,7 +9,7 @@ common.globalCheck = false; const stream = new common.ArrayStream(); // 1, mostly defaults -var r1 = repl.start({ +const r1 = repl.start({ input: stream, output: stream, terminal: true @@ -37,7 +37,7 @@ assert.equal(r1.useColors, r1.rli.terminal); // 2 function writer() {} function evaler() {} -var r2 = repl.start({ +const r2 = repl.start({ input: stream, output: stream, terminal: false, @@ -67,7 +67,7 @@ assert.equal(r2.rli.output, r2.outputStream); assert.equal(r2.rli.terminal, false); // testing out "magic" replMode -var r3 = repl.start({ +const r3 = repl.start({ input: stream, output: stream, writer: writer, diff --git a/test/parallel/test-repl-persistent-history.js b/test/parallel/test-repl-persistent-history.js index 25fdef81a8d5ab..2b0ceac530a65f 100644 --- a/test/parallel/test-repl-persistent-history.js +++ b/test/parallel/test-repl-persistent-history.js @@ -178,7 +178,7 @@ const tests = [ const numtests = tests.length; -var testsNotRan = tests.length; +let testsNotRan = tests.length; process.on('beforeExit', () => assert.strictEqual(testsNotRan, 0) diff --git a/test/parallel/test-repl-require.js b/test/parallel/test-repl-require.js index 9dc3b51de7a88a..25aaac47a4ed36 100644 --- a/test/parallel/test-repl-require.js +++ b/test/parallel/test-repl-require.js @@ -18,7 +18,7 @@ const host = common.localhostIPv4; const port = 0; const options = { host, port }; -var answer = ''; +let answer = ''; server.listen(options, function() { options.port = this.address().port; const conn = net.connect(options); diff --git a/test/parallel/test-repl-setprompt.js b/test/parallel/test-repl-setprompt.js index 2708a3e6af5448..8dcc4fe94452da 100644 --- a/test/parallel/test-repl-setprompt.js +++ b/test/parallel/test-repl-setprompt.js @@ -4,18 +4,18 @@ const assert = require('assert'); const spawn = require('child_process').spawn; const os = require('os'); -var args = [ +const args = [ '-e', 'var e = new (require("repl")).REPLServer("foo.. "); e.context.e = e;', ]; -var p = 'bar.. '; +const p = 'bar.. '; -var child = spawn(process.execPath, args); +const child = spawn(process.execPath, args); child.stdout.setEncoding('utf8'); -var data = ''; +let data = ''; child.stdout.on('data', function(d) { data += d; }); child.stdin.end(`e.setPrompt("${p}");${os.EOL}`); @@ -23,6 +23,6 @@ child.stdin.end(`e.setPrompt("${p}");${os.EOL}`); child.on('close', function(code, signal) { assert.strictEqual(code, 0); assert.ok(!signal); - var lines = data.split(/\n/); + const lines = data.split(/\n/); assert.strictEqual(lines.pop(), p); }); diff --git a/test/parallel/test-repl-syntax-error-handling.js b/test/parallel/test-repl-syntax-error-handling.js index 2728ffdfe92129..6a65d53a029379 100644 --- a/test/parallel/test-repl-syntax-error-handling.js +++ b/test/parallel/test-repl-syntax-error-handling.js @@ -13,7 +13,7 @@ switch (process.argv[2]) { function parent() { const spawn = require('child_process').spawn; - var child = spawn(process.execPath, [__filename, 'child']); + const child = spawn(process.execPath, [__filename, 'child']); child.stderr.setEncoding('utf8'); child.stderr.on('data', function(c) { @@ -22,7 +22,7 @@ function parent() { }); child.stdout.setEncoding('utf8'); - var out = ''; + let out = ''; child.stdout.on('data', function(c) { out += c; }); @@ -39,10 +39,11 @@ function parent() { function child() { const vm = require('vm'); + let caught; try { vm.runInThisContext('haf!@##&$!@$*!@', { displayErrors: false }); } catch (er) { - var caught = true; + caught = true; } assert(caught); vm.runInThisContext('console.log(10)', { displayErrors: false }); diff --git a/test/parallel/test-repl-tab-complete.js b/test/parallel/test-repl-tab-complete.js index 4e05714ab5fc56..1a1a2a8628809c 100644 --- a/test/parallel/test-repl-tab-complete.js +++ b/test/parallel/test-repl-tab-complete.js @@ -17,9 +17,9 @@ function getNoResultsFunction() { }); } -var works = [['inner.one'], 'inner.o']; +const works = [['inner.one'], 'inner.o']; const putIn = new common.ArrayStream(); -var testMe = repl.start('', putIn); +const testMe = repl.start('', putIn); // Some errors are passed to the domain, but do not callback testMe._domain.on('error', function(err) { @@ -165,7 +165,7 @@ testMe.complete('str.len', common.mustCall(function(error, data) { putIn.run(['.clear']); // tab completion should not break on spaces -var spaceTimeout = setTimeout(function() { +const spaceTimeout = setTimeout(function() { throw new Error('timeout'); }, 1000); diff --git a/test/parallel/test-repl-tab.js b/test/parallel/test-repl-tab.js index b41f43c667f666..7baa7d0aace812 100644 --- a/test/parallel/test-repl-tab.js +++ b/test/parallel/test-repl-tab.js @@ -5,8 +5,9 @@ const repl = require('repl'); const zlib = require('zlib'); // just use builtin stream inherited from Duplex -var putIn = zlib.createGzip(); -var testMe = repl.start('', putIn, function(cmd, context, filename, callback) { +const putIn = zlib.createGzip(); +const testMe = repl.start('', putIn, function(cmd, context, filename, + callback) { callback(null, cmd); }); diff --git a/test/parallel/test-repl-unexpected-token-recoverable.js b/test/parallel/test-repl-unexpected-token-recoverable.js index 7ace511d097ef8..0f783d3dcaf27b 100644 --- a/test/parallel/test-repl-unexpected-token-recoverable.js +++ b/test/parallel/test-repl-unexpected-token-recoverable.js @@ -7,12 +7,12 @@ const assert = require('assert'); const spawn = require('child_process').spawn; // use -i to force node into interactive mode, despite stdout not being a TTY -var args = [ '-i' ]; -var child = spawn(process.execPath, args); +const args = [ '-i' ]; +const child = spawn(process.execPath, args); -var input = 'var foo = "bar\\\nbaz"'; +const input = 'var foo = "bar\\\nbaz"'; // Match '...' as well since it marks a multi-line statement -var expectOut = /^> ... undefined\n/; +const expectOut = /^> ... undefined\n/; child.stderr.setEncoding('utf8'); child.stderr.on('data', function(c) { @@ -20,7 +20,7 @@ child.stderr.on('data', function(c) { }); child.stdout.setEncoding('utf8'); -var out = ''; +let out = ''; child.stdout.on('data', function(c) { out += c; }); diff --git a/test/parallel/test-sigint-infinite-loop.js b/test/parallel/test-sigint-infinite-loop.js index aafcd9e41d7394..30eb98ecb8a265 100644 --- a/test/parallel/test-sigint-infinite-loop.js +++ b/test/parallel/test-sigint-infinite-loop.js @@ -8,9 +8,9 @@ const spawn = require('child_process').spawn; console.log('start'); -var c = spawn(process.execPath, ['-e', 'while(true) { console.log("hi"); }']); +const c = spawn(process.execPath, ['-e', 'while(true) { console.log("hi"); }']); -var sentKill = false; +let sentKill = false; c.stdout.on('data', function(s) { // Prevent race condition: diff --git a/test/parallel/test-signal-handler.js b/test/parallel/test-signal-handler.js index 079c72a9e56a8a..b796ebb11d211c 100644 --- a/test/parallel/test-signal-handler.js +++ b/test/parallel/test-signal-handler.js @@ -18,7 +18,7 @@ process.on('SIGUSR1', common.mustCall(function() { }, 5); })); -var i = 0; +let i = 0; setInterval(function() { console.log('running process...' + ++i); diff --git a/test/parallel/test-signal-safety.js b/test/parallel/test-signal-safety.js index eb29554b8b29bb..34722b712f8889 100644 --- a/test/parallel/test-signal-safety.js +++ b/test/parallel/test-signal-safety.js @@ -1,12 +1,12 @@ 'use strict'; require('../common'); const assert = require('assert'); -var Signal = process.binding('signal_wrap').Signal; +const Signal = process.binding('signal_wrap').Signal; // Test Signal `this` safety // https://github.com/joyent/node/issues/6690 assert.throws(function() { - var s = new Signal(); - var nots = { start: s.start }; + const s = new Signal(); + const nots = { start: s.start }; nots.start(9); }, TypeError); diff --git a/test/parallel/test-socket-write-after-fin-error.js b/test/parallel/test-socket-write-after-fin-error.js index 0d280115a43653..f21b52d519b2ba 100644 --- a/test/parallel/test-socket-write-after-fin-error.js +++ b/test/parallel/test-socket-write-after-fin-error.js @@ -8,13 +8,13 @@ const assert = require('assert'); // message is too vague, and doesn't actually tell you what happens. const net = require('net'); -var serverData = ''; -var gotServerEnd = false; -var clientData = ''; -var gotClientEnd = false; -var gotServerError = false; +let serverData = ''; +let gotServerEnd = false; +let clientData = ''; +let gotClientEnd = false; +let gotServerError = false; -var server = net.createServer(function(sock) { +const server = net.createServer(function(sock) { sock.setEncoding('utf8'); sock.on('error', function(er) { console.error(er.code + ': ' + er.message); @@ -32,7 +32,7 @@ var server = net.createServer(function(sock) { server.close(); }); server.listen(0, function() { - var sock = net.connect(this.address().port); + const sock = net.connect(this.address().port); sock.setEncoding('utf8'); sock.on('data', function(c) { clientData += c; diff --git a/test/parallel/test-socket-write-after-fin.js b/test/parallel/test-socket-write-after-fin.js index 17847f973387f1..c8ff56871734af 100644 --- a/test/parallel/test-socket-write-after-fin.js +++ b/test/parallel/test-socket-write-after-fin.js @@ -4,10 +4,10 @@ const assert = require('assert'); const net = require('net'); const expected = 'hello1hello2hello3\nTHUNDERMUSCLE!'; -var server = net.createServer({ +const server = net.createServer({ allowHalfOpen: true }, common.mustCall(function(sock) { - var serverData = ''; + let serverData = ''; sock.setEncoding('utf8'); sock.on('data', function(c) { @@ -20,8 +20,8 @@ var server = net.createServer({ })); })); server.listen(0, common.mustCall(function() { - var sock = net.connect(this.address().port); - var clientData = ''; + const sock = net.connect(this.address().port); + let clientData = ''; sock.setEncoding('utf8'); sock.on('data', function(c) { diff --git a/test/parallel/test-stdin-pipe-resume.js b/test/parallel/test-stdin-pipe-resume.js index 663649134fe397..06cce3edfe403f 100644 --- a/test/parallel/test-stdin-pipe-resume.js +++ b/test/parallel/test-stdin-pipe-resume.js @@ -7,13 +7,13 @@ if (process.argv[2] === 'child') { process.stdin.pipe(process.stdout); } else { const spawn = require('child_process').spawn; - var buffers = []; - var child = spawn(process.execPath, [__filename, 'child']); + const buffers = []; + const child = spawn(process.execPath, [__filename, 'child']); child.stdout.on('data', function(c) { buffers.push(c); }); child.stdout.on('close', function() { - var b = Buffer.concat(buffers).toString(); + const b = Buffer.concat(buffers).toString(); assert.equal(b, 'Hello, world\n'); console.log('ok'); }); diff --git a/test/parallel/test-stdin-script-child.js b/test/parallel/test-stdin-script-child.js index 091c5cb29ad296..a8a161686eeeef 100644 --- a/test/parallel/test-stdin-script-child.js +++ b/test/parallel/test-stdin-script-child.js @@ -9,7 +9,7 @@ const child = spawn(process.execPath, [], { }) }); const wanted = child.pid + '\n'; -var found = ''; +let found = ''; child.stdout.setEncoding('utf8'); child.stdout.on('data', function(c) { diff --git a/test/parallel/test-stdout-cannot-be-closed-child-process-pipe.js b/test/parallel/test-stdout-cannot-be-closed-child-process-pipe.js index bfc7a1ddf4dc8e..aa1939ebe2c334 100644 --- a/test/parallel/test-stdout-cannot-be-closed-child-process-pipe.js +++ b/test/parallel/test-stdout-cannot-be-closed-child-process-pipe.js @@ -9,9 +9,9 @@ else function parent() { const spawn = require('child_process').spawn; - var child = spawn(process.execPath, [__filename, 'child']); - var out = ''; - var err = ''; + const child = spawn(process.execPath, [__filename, 'child']); + let out = ''; + let err = ''; child.stdout.setEncoding('utf8'); child.stderr.setEncoding('utf8'); diff --git a/test/parallel/test-stdout-stderr-reading.js b/test/parallel/test-stdout-stderr-reading.js index b61edf194fc4ac..6aa961301349fc 100644 --- a/test/parallel/test-stdout-stderr-reading.js +++ b/test/parallel/test-stdout-stderr-reading.js @@ -4,7 +4,7 @@ const assert = require('assert'); // verify that stdout is never read from. const net = require('net'); -var read = net.Socket.prototype.read; +const read = net.Socket.prototype.read; net.Socket.prototype.read = function() { if (this.fd === 1) @@ -21,10 +21,10 @@ else function parent() { const spawn = require('child_process').spawn; - var node = process.execPath; + const node = process.execPath; - var c1 = spawn(node, [__filename, 'child']); - var c1out = ''; + const c1 = spawn(node, [__filename, 'child']); + let c1out = ''; c1.stdout.setEncoding('utf8'); c1.stdout.on('data', function(chunk) { c1out += chunk; @@ -40,8 +40,8 @@ function parent() { console.log('ok'); })); - var c2 = spawn(node, ['-e', 'console.log("ok")']); - var c2out = ''; + const c2 = spawn(node, ['-e', 'console.log("ok")']); + let c2out = ''; c2.stdout.setEncoding('utf8'); c2.stdout.on('data', function(chunk) { c2out += chunk; diff --git a/test/parallel/test-stdout-to-file.js b/test/parallel/test-stdout-to-file.js index 80093160212f9a..914fe5673ed10c 100644 --- a/test/parallel/test-stdout-to-file.js +++ b/test/parallel/test-stdout-to-file.js @@ -13,13 +13,13 @@ const tmpFile = path.join(common.tmpDir, 'stdout.txt'); common.refreshTmpDir(); function test(size, useBuffer, cb) { - var cmd = '"' + process.argv[0] + '"' + - ' ' + - '"' + (useBuffer ? scriptBuffer : scriptString) + '"' + - ' ' + - size + - ' > ' + - '"' + tmpFile + '"'; + const cmd = '"' + process.argv[0] + '"' + + ' ' + + '"' + (useBuffer ? scriptBuffer : scriptString) + '"' + + ' ' + + size + + ' > ' + + '"' + tmpFile + '"'; try { fs.unlinkSync(tmpFile); @@ -31,7 +31,7 @@ function test(size, useBuffer, cb) { assert.ifError(err); console.log('done!'); - var stat = fs.statSync(tmpFile); + const stat = fs.statSync(tmpFile); console.log(`${tmpFile} has ${stat.size} bytes`); diff --git a/test/parallel/test-stream-base-no-abort.js b/test/parallel/test-stream-base-no-abort.js index 329948836a5f9f..6b1cc67ee7777e 100644 --- a/test/parallel/test-stream-base-no-abort.js +++ b/test/parallel/test-stream-base-no-abort.js @@ -14,7 +14,7 @@ const fs = require('fs'); const net = require('net'); const tls = require('tls'); const providers = Object.keys(async_wrap.Providers); -var flags = 0; +let flags = 0; // Make sure all asserts have run at least once. process.on('exit', () => assert.equal(flags, 0b111)); diff --git a/test/parallel/test-stream-big-push.js b/test/parallel/test-stream-big-push.js index 27feef35ef536d..9083820d42b546 100644 --- a/test/parallel/test-stream-big-push.js +++ b/test/parallel/test-stream-big-push.js @@ -18,7 +18,7 @@ function _read() { }, 1); reads++; } else if (reads === 1) { - var ret = r.push(str); + const ret = r.push(str); assert.strictEqual(ret, false); reads++; } else { @@ -32,10 +32,10 @@ r.on('end', common.mustCall(function() {})); // push some data in to start. // we've never gotten any read event at this point. -var ret = r.push(str); +const ret = r.push(str); // should be false. > hwm assert(!ret); -var chunk = r.read(); +let chunk = r.read(); assert.strictEqual(chunk, str); chunk = r.read(); assert.strictEqual(chunk, null); diff --git a/test/parallel/test-stream-pipe-event.js b/test/parallel/test-stream-pipe-event.js index 77cd5d26f9fc11..1b5447eaa21ff9 100644 --- a/test/parallel/test-stream-pipe-event.js +++ b/test/parallel/test-stream-pipe-event.js @@ -16,14 +16,14 @@ function Readable() { } util.inherits(Readable, stream.Stream); -var passed = false; +let passed = false; -var w = new Writable(); +const w = new Writable(); w.on('pipe', function(src) { passed = true; }); -var r = new Readable(); +const r = new Readable(); r.pipe(w); assert.ok(passed); diff --git a/test/parallel/test-stream-push-order.js b/test/parallel/test-stream-push-order.js index 4be2ca4a9fbe00..5fc1f5e89cf156 100644 --- a/test/parallel/test-stream-push-order.js +++ b/test/parallel/test-stream-push-order.js @@ -3,19 +3,19 @@ require('../common'); const Readable = require('stream').Readable; const assert = require('assert'); -var s = new Readable({ +const s = new Readable({ highWaterMark: 20, encoding: 'ascii' }); -var list = ['1', '2', '3', '4', '5', '6']; +const list = ['1', '2', '3', '4', '5', '6']; s._read = function(n) { - var one = list.shift(); + const one = list.shift(); if (!one) { s.push(null); } else { - var two = list.shift(); + const two = list.shift(); s.push(one); s.push(two); } diff --git a/test/parallel/test-stream-push-strings.js b/test/parallel/test-stream-push-strings.js index 85f5a6bf27d4ad..7bce493bbd33ce 100644 --- a/test/parallel/test-stream-push-strings.js +++ b/test/parallel/test-stream-push-strings.js @@ -30,15 +30,15 @@ MyStream.prototype._read = function(n) { } }; -var ms = new MyStream(); -var results = []; +const ms = new MyStream(); +const results = []; ms.on('readable', function() { - var chunk; + let chunk; while (null !== (chunk = ms.read())) results.push(chunk + ''); }); -var expect = [ 'first chunksecond to last chunk', 'last chunk' ]; +const expect = [ 'first chunksecond to last chunk', 'last chunk' ]; process.on('exit', function() { assert.equal(ms._chunks, -1); assert.deepStrictEqual(results, expect); diff --git a/test/parallel/test-stream-readable-constructor-set-methods.js b/test/parallel/test-stream-readable-constructor-set-methods.js index 86fab5ae54b90c..a5d7e48bfb3fa9 100644 --- a/test/parallel/test-stream-readable-constructor-set-methods.js +++ b/test/parallel/test-stream-readable-constructor-set-methods.js @@ -4,13 +4,13 @@ const assert = require('assert'); const Readable = require('stream').Readable; -var _readCalled = false; +let _readCalled = false; function _read(n) { _readCalled = true; this.push(null); } -var r = new Readable({ read: _read }); +const r = new Readable({ read: _read }); r.resume(); process.on('exit', function() { diff --git a/test/parallel/test-stream-readable-flow-recursion.js b/test/parallel/test-stream-readable-flow-recursion.js index 48615ed0a95414..b1e421a71fd15b 100644 --- a/test/parallel/test-stream-readable-flow-recursion.js +++ b/test/parallel/test-stream-readable-flow-recursion.js @@ -12,9 +12,9 @@ const Readable = require('stream').Readable; // throw an error if we trigger a nextTick warning. process.throwDeprecation = true; -var stream = new Readable({ highWaterMark: 2 }); -var reads = 0; -var total = 5000; +const stream = new Readable({ highWaterMark: 2 }); +let reads = 0; +let total = 5000; stream._read = function(size) { reads++; size = Math.min(size, total); @@ -25,11 +25,11 @@ stream._read = function(size) { stream.push(Buffer.allocUnsafe(size)); }; -var depth = 0; +let depth = 0; function flow(stream, size, callback) { depth += 1; - var chunk = stream.read(size); + const chunk = stream.read(size); if (!chunk) stream.once('readable', flow.bind(null, stream, size, callback)); diff --git a/test/parallel/test-stream-transform-constructor-set-methods.js b/test/parallel/test-stream-transform-constructor-set-methods.js index c57a633c55441e..7be673c517b30b 100644 --- a/test/parallel/test-stream-transform-constructor-set-methods.js +++ b/test/parallel/test-stream-transform-constructor-set-methods.js @@ -4,19 +4,19 @@ const assert = require('assert'); const Transform = require('stream').Transform; -var _transformCalled = false; +let _transformCalled = false; function _transform(d, e, n) { _transformCalled = true; n(); } -var _flushCalled = false; +let _flushCalled = false; function _flush(n) { _flushCalled = true; n(); } -var t = new Transform({ +const t = new Transform({ transform: _transform, flush: _flush }); diff --git a/test/parallel/test-stream-transform-flush-data.js b/test/parallel/test-stream-transform-flush-data.js index dede64ba10f9da..6d6aedd3a72bf8 100644 --- a/test/parallel/test-stream-transform-flush-data.js +++ b/test/parallel/test-stream-transform-flush-data.js @@ -16,7 +16,7 @@ function _flush(n) { n(null, expected); } -var t = new Transform({ +const t = new Transform({ transform: _transform, flush: _flush }); diff --git a/test/parallel/test-stream-transform-split-objectmode.js b/test/parallel/test-stream-transform-split-objectmode.js index 10fae6573c5e8f..52185e18711090 100644 --- a/test/parallel/test-stream-transform-split-objectmode.js +++ b/test/parallel/test-stream-transform-split-objectmode.js @@ -4,7 +4,7 @@ const assert = require('assert'); const Transform = require('stream').Transform; -var parser = new Transform({ readableObjectMode: true }); +const parser = new Transform({ readableObjectMode: true }); assert(parser._readableState.objectMode); assert(!parser._writableState.objectMode); @@ -15,7 +15,7 @@ parser._transform = function(chunk, enc, callback) { callback(null, { val: chunk[0] }); }; -var parsed; +let parsed; parser.on('data', function(obj) { parsed = obj; @@ -28,7 +28,7 @@ process.on('exit', function() { }); -var serializer = new Transform({ writableObjectMode: true }); +const serializer = new Transform({ writableObjectMode: true }); assert(!serializer._readableState.objectMode); assert(serializer._writableState.objectMode); @@ -39,7 +39,7 @@ serializer._transform = function(obj, _, callback) { callback(null, Buffer.from([obj.val])); }; -var serialized; +let serialized; serializer.on('data', function(chunk) { serialized = chunk; diff --git a/test/parallel/test-stream-unshift-empty-chunk.js b/test/parallel/test-stream-unshift-empty-chunk.js index 196a36e7ebdbf1..d555fd7cae2330 100644 --- a/test/parallel/test-stream-unshift-empty-chunk.js +++ b/test/parallel/test-stream-unshift-empty-chunk.js @@ -6,9 +6,9 @@ const assert = require('assert'); // stream.unshift('') does not set state.reading=false. const Readable = require('stream').Readable; -var r = new Readable(); -var nChunks = 10; -var chunk = Buffer.alloc(10, 'x'); +const r = new Readable(); +let nChunks = 10; +const chunk = Buffer.alloc(10, 'x'); r._read = function(n) { setImmediate(function() { @@ -16,10 +16,10 @@ r._read = function(n) { }); }; -var readAll = false; -var seen = []; +let readAll = false; +const seen = []; r.on('readable', function() { - var chunk; + let chunk; while (chunk = r.read()) { seen.push(chunk.toString()); // simulate only reading a certain amount of the data, @@ -27,13 +27,13 @@ r.on('readable', function() { // stream, like a parser might do. We just fill it with // 'y' so that it's easy to see which bits were touched, // and which were not. - var putBack = Buffer.alloc(readAll ? 0 : 5, 'y'); + const putBack = Buffer.alloc(readAll ? 0 : 5, 'y'); readAll = !readAll; r.unshift(putBack); } }); -var expect = +const expect = [ 'xxxxxxxxxx', 'yyyyy', 'xxxxxxxxxx', diff --git a/test/parallel/test-stream-wrap.js b/test/parallel/test-stream-wrap.js index 69e4dee89d3b13..dbcb58a98cd8b2 100644 --- a/test/parallel/test-stream-wrap.js +++ b/test/parallel/test-stream-wrap.js @@ -7,16 +7,16 @@ const Duplex = require('stream').Duplex; const ShutdownWrap = process.binding('stream_wrap').ShutdownWrap; function testShutdown(callback) { - var stream = new Duplex({ + const stream = new Duplex({ read: function() { }, write: function() { } }); - var wrap = new StreamWrap(stream); + const wrap = new StreamWrap(stream); - var req = new ShutdownWrap(); + const req = new ShutdownWrap(); req.oncomplete = function(code) { assert(code < 0); callback(); diff --git a/test/parallel/test-stream-writable-change-default-encoding.js b/test/parallel/test-stream-writable-change-default-encoding.js index 9d527fa9c5e764..9eac52bc1aea44 100644 --- a/test/parallel/test-stream-writable-change-default-encoding.js +++ b/test/parallel/test-stream-writable-change-default-encoding.js @@ -18,7 +18,7 @@ MyWritable.prototype._write = function(chunk, encoding, callback) { }; (function defaultCondingIsUtf8() { - var m = new MyWritable(function(isBuffer, type, enc) { + const m = new MyWritable(function(isBuffer, type, enc) { assert.equal(enc, 'utf8'); }, { decodeStrings: false }); m.write('foo'); @@ -26,7 +26,7 @@ MyWritable.prototype._write = function(chunk, encoding, callback) { }()); (function changeDefaultEncodingToAscii() { - var m = new MyWritable(function(isBuffer, type, enc) { + const m = new MyWritable(function(isBuffer, type, enc) { assert.equal(enc, 'ascii'); }, { decodeStrings: false }); m.setDefaultEncoding('ascii'); @@ -35,7 +35,7 @@ MyWritable.prototype._write = function(chunk, encoding, callback) { }()); assert.throws(function changeDefaultEncodingToInvalidValue() { - var m = new MyWritable(function(isBuffer, type, enc) { + const m = new MyWritable(function(isBuffer, type, enc) { }, { decodeStrings: false }); m.setDefaultEncoding({}); m.write('bar'); @@ -43,7 +43,7 @@ assert.throws(function changeDefaultEncodingToInvalidValue() { }, TypeError); (function checkVairableCaseEncoding() { - var m = new MyWritable(function(isBuffer, type, enc) { + const m = new MyWritable(function(isBuffer, type, enc) { assert.equal(enc, 'ascii'); }, { decodeStrings: false }); m.setDefaultEncoding('AsCii'); diff --git a/test/parallel/test-stream-writable-constructor-set-methods.js b/test/parallel/test-stream-writable-constructor-set-methods.js index 40f624f293b05e..9b344487f61580 100644 --- a/test/parallel/test-stream-writable-constructor-set-methods.js +++ b/test/parallel/test-stream-writable-constructor-set-methods.js @@ -4,22 +4,22 @@ const assert = require('assert'); const Writable = require('stream').Writable; -var _writeCalled = false; +let _writeCalled = false; function _write(d, e, n) { _writeCalled = true; } -var w = new Writable({ write: _write }); +const w = new Writable({ write: _write }); w.end(Buffer.from('blerg')); -var _writevCalled = false; -var dLength = 0; +let _writevCalled = false; +let dLength = 0; function _writev(d, n) { dLength = d.length; _writevCalled = true; } -var w2 = new Writable({ writev: _writev }); +const w2 = new Writable({ writev: _writev }); w2.cork(); w2.write(Buffer.from('blerg')); diff --git a/test/parallel/test-stream-writable-null.js b/test/parallel/test-stream-writable-null.js index 2cc396bd916a3e..438f250a17dde6 100644 --- a/test/parallel/test-stream-writable-null.js +++ b/test/parallel/test-stream-writable-null.js @@ -17,11 +17,11 @@ MyWritable.prototype._write = function(chunk, encoding, callback) { }; assert.throws(() => { - var m = new MyWritable({objectMode: true}); + const m = new MyWritable({objectMode: true}); m.write(null, (err) => assert.ok(err)); }, TypeError, 'May not write null values to stream'); assert.doesNotThrow(() => { - var m = new MyWritable({objectMode: true}).on('error', (e) => { + const m = new MyWritable({objectMode: true}).on('error', (e) => { assert.ok(e); }); m.write(null, (err) => { @@ -30,11 +30,11 @@ assert.doesNotThrow(() => { }); assert.throws(() => { - var m = new MyWritable(); + const m = new MyWritable(); m.write(false, (err) => assert.ok(err)); }, TypeError, 'Invalid non-string/buffer chunk'); assert.doesNotThrow(() => { - var m = new MyWritable().on('error', (e) => { + const m = new MyWritable().on('error', (e) => { assert.ok(e); }); m.write(false, (err) => { @@ -43,11 +43,11 @@ assert.doesNotThrow(() => { }); assert.doesNotThrow(() => { - var m = new MyWritable({objectMode: true}); + const m = new MyWritable({objectMode: true}); m.write(false, (err) => assert.ifError(err)); }); assert.doesNotThrow(() => { - var m = new MyWritable({objectMode: true}).on('error', (e) => { + const m = new MyWritable({objectMode: true}).on('error', (e) => { assert.ifError(e || new Error('should not get here')); }); m.write(false, (err) => { diff --git a/test/parallel/test-stream-writev.js b/test/parallel/test-stream-writev.js index fc3b09985724d8..4e05d2ba8e70e8 100644 --- a/test/parallel/test-stream-writev.js +++ b/test/parallel/test-stream-writev.js @@ -4,10 +4,10 @@ const assert = require('assert'); const stream = require('stream'); -var queue = []; -for (var decode = 0; decode < 2; decode++) { - for (var uncork = 0; uncork < 2; uncork++) { - for (var multi = 0; multi < 2; multi++) { +const queue = []; +for (let decode = 0; decode < 2; decode++) { + for (let uncork = 0; uncork < 2; uncork++) { + for (let multi = 0; multi < 2; multi++) { queue.push([!!decode, !!uncork, !!multi]); } } @@ -16,7 +16,7 @@ for (var decode = 0; decode < 2; decode++) { run(); function run() { - var t = queue.pop(); + const t = queue.pop(); if (t) test(t[0], t[1], t[2], run); else @@ -25,11 +25,11 @@ function run() { function test(decode, uncork, multi, next) { console.log('# decode=%j uncork=%j multi=%j', decode, uncork, multi); - var counter = 0; - var expectCount = 0; + let counter = 0; + let expectCount = 0; function cnt(msg) { expectCount++; - var expect = expectCount; + const expect = expectCount; return function(er) { assert.ifError(er); counter++; @@ -37,12 +37,12 @@ function test(decode, uncork, multi, next) { }; } - var w = new stream.Writable({ decodeStrings: decode }); + const w = new stream.Writable({ decodeStrings: decode }); w._write = function(chunk, e, cb) { assert(false, 'Should not call _write'); }; - var expectChunks = decode ? [ + const expectChunks = decode ? [ { encoding: 'buffer', chunk: [104, 101, 108, 108, 111, 44, 32] }, { encoding: 'buffer', @@ -61,7 +61,7 @@ function test(decode, uncork, multi, next) { { encoding: 'hex', chunk: 'facebea7deadbeefdecafbad' } ]; - var actualChunks; + let actualChunks; w._writev = function(chunks, cb) { actualChunks = chunks.map(function(chunk) { return { diff --git a/test/parallel/test-stream2-base64-single-char-read-end.js b/test/parallel/test-stream2-base64-single-char-read-end.js index 41075334241f7a..da63644de099a1 100644 --- a/test/parallel/test-stream2-base64-single-char-read-end.js +++ b/test/parallel/test-stream2-base64-single-char-read-end.js @@ -4,11 +4,10 @@ const R = require('_stream_readable'); const W = require('_stream_writable'); const assert = require('assert'); -var src = new R({encoding: 'base64'}); -var dst = new W(); -var hasRead = false; -var accum = []; -var timeout; +const src = new R({encoding: 'base64'}); +const dst = new W(); +let hasRead = false; +const accum = []; src._read = function(n) { if (!hasRead) { @@ -32,6 +31,6 @@ src.on('end', function() { src.pipe(dst); -timeout = setTimeout(function() { +const timeout = setTimeout(function() { common.fail('timed out waiting for _write'); }, 100); diff --git a/test/parallel/test-stream2-compatibility.js b/test/parallel/test-stream2-compatibility.js index d4bf32a19922d0..f7c980791311da 100644 --- a/test/parallel/test-stream2-compatibility.js +++ b/test/parallel/test-stream2-compatibility.js @@ -6,7 +6,7 @@ const assert = require('assert'); const util = require('util'); -var ondataCalled = 0; +let ondataCalled = 0; function TestReader() { R.apply(this); @@ -24,7 +24,7 @@ TestReader.prototype._read = function(n) { this._buffer = Buffer.alloc(0); }; -var reader = new TestReader(); +const reader = new TestReader(); setImmediate(function() { assert.equal(ondataCalled, 1); console.log('ok'); @@ -43,7 +43,7 @@ TestWriter.prototype._write = function(chunk, enc, cb) { cb(); }; -var writer = new TestWriter(); +const writer = new TestWriter(); process.on('exit', function() { assert.strictEqual(reader.readable, false); diff --git a/test/parallel/test-stream2-decode-partial.js b/test/parallel/test-stream2-decode-partial.js index b58e192b9c33bb..b43101dbc84c3a 100644 --- a/test/parallel/test-stream2-decode-partial.js +++ b/test/parallel/test-stream2-decode-partial.js @@ -3,7 +3,7 @@ require('../common'); const Readable = require('_stream_readable'); const assert = require('assert'); -var buf = ''; +let buf = ''; const euro = new Buffer([0xE2, 0x82, 0xAC]); const cent = new Buffer([0xC2, 0xA2]); const source = Buffer.concat([euro, cent]); diff --git a/test/parallel/test-stream2-finish-pipe.js b/test/parallel/test-stream2-finish-pipe.js index ee9ee20bd5237d..87edf5a5fa6437 100644 --- a/test/parallel/test-stream2-finish-pipe.js +++ b/test/parallel/test-stream2-finish-pipe.js @@ -3,12 +3,12 @@ require('../common'); const stream = require('stream'); const Buffer = require('buffer').Buffer; -var r = new stream.Readable(); +const r = new stream.Readable(); r._read = function(size) { r.push(Buffer.allocUnsafe(size)); }; -var w = new stream.Writable(); +const w = new stream.Writable(); w._write = function(data, encoding, cb) { cb(null); }; diff --git a/test/parallel/test-stream2-httpclient-response-end.js b/test/parallel/test-stream2-httpclient-response-end.js index c4570e8b02db43..6d3da191b06cb9 100644 --- a/test/parallel/test-stream2-httpclient-response-end.js +++ b/test/parallel/test-stream2-httpclient-response-end.js @@ -2,13 +2,13 @@ const common = require('../common'); const assert = require('assert'); const http = require('http'); -var msg = 'Hello'; -var server = http.createServer(function(req, res) { +const msg = 'Hello'; +const server = http.createServer(function(req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end(msg); }).listen(0, function() { http.get({port: this.address().port}, function(res) { - var data = ''; + let data = ''; res.on('readable', common.mustCall(function() { console.log('readable event'); data += res.read(); diff --git a/test/parallel/test-stream2-large-read-stall.js b/test/parallel/test-stream2-large-read-stall.js index 60e4a2873a0945..88fef4f24b6c30 100644 --- a/test/parallel/test-stream2-large-read-stall.js +++ b/test/parallel/test-stream2-large-read-stall.js @@ -5,24 +5,25 @@ const assert = require('assert'); // If everything aligns so that you do a read(n) of exactly the // remaining buffer, then make sure that 'end' still emits. -var READSIZE = 100; -var PUSHSIZE = 20; -var PUSHCOUNT = 1000; -var HWM = 50; +const READSIZE = 100; +const PUSHSIZE = 20; +const PUSHCOUNT = 1000; +const HWM = 50; const Readable = require('stream').Readable; -var r = new Readable({ +const r = new Readable({ highWaterMark: HWM }); -var rs = r._readableState; +const rs = r._readableState; r._read = push; r.on('readable', function() { console.error('>> readable'); + let ret; do { console.error(' > read(%d)', READSIZE); - var ret = r.read(READSIZE); + ret = r.read(READSIZE); console.error(' < %j (%d remain)', ret && ret.length, rs.length); } while (ret && ret.length === READSIZE); @@ -34,7 +35,7 @@ r.on('readable', function() { r.on('end', common.mustCall(function() {})); -var pushes = 0; +let pushes = 0; function push() { if (pushes > PUSHCOUNT) return; diff --git a/test/parallel/test-stream2-objects.js b/test/parallel/test-stream2-objects.js index 6b50ba8436bfa6..6c00f1b8691364 100644 --- a/test/parallel/test-stream2-objects.js +++ b/test/parallel/test-stream2-objects.js @@ -5,8 +5,8 @@ const Writable = require('_stream_writable'); const assert = require('assert'); // tiny node-tap lookalike. -var tests = []; -var count = 0; +const tests = []; +let count = 0; function test(name, fn) { count++; @@ -14,12 +14,12 @@ function test(name, fn) { } function run() { - var next = tests.shift(); + const next = tests.shift(); if (!next) return console.error('ok'); - var name = next[0]; - var fn = next[1]; + const name = next[0]; + const fn = next[1]; console.log('# %s', name); fn({ same: assert.deepStrictEqual, @@ -39,8 +39,8 @@ process.on('exit', function() { process.nextTick(run); function toArray(callback) { - var stream = new Writable({ objectMode: true }); - var list = []; + const stream = new Writable({ objectMode: true }); + const list = []; stream.write = function(chunk) { list.push(chunk); }; @@ -53,7 +53,7 @@ function toArray(callback) { } function fromArray(list) { - var r = new Readable({ objectMode: true }); + const r = new Readable({ objectMode: true }); r._read = noop; list.forEach(function(chunk) { r.push(chunk); @@ -66,11 +66,11 @@ function fromArray(list) { function noop() {} test('can read objects from stream', function(t) { - var r = fromArray([{ one: '1'}, { two: '2' }]); + const r = fromArray([{ one: '1'}, { two: '2' }]); - var v1 = r.read(); - var v2 = r.read(); - var v3 = r.read(); + const v1 = r.read(); + const v2 = r.read(); + const v3 = r.read(); assert.deepStrictEqual(v1, { one: '1' }); assert.deepStrictEqual(v2, { two: '2' }); @@ -80,7 +80,7 @@ test('can read objects from stream', function(t) { }); test('can pipe objects into stream', function(t) { - var r = fromArray([{ one: '1'}, { two: '2' }]); + const r = fromArray([{ one: '1'}, { two: '2' }]); r.pipe(toArray(function(list) { assert.deepStrictEqual(list, [ @@ -93,9 +93,9 @@ test('can pipe objects into stream', function(t) { }); test('read(n) is ignored', function(t) { - var r = fromArray([{ one: '1'}, { two: '2' }]); + const r = fromArray([{ one: '1'}, { two: '2' }]); - var value = r.read(2); + const value = r.read(2); assert.deepStrictEqual(value, { one: '1' }); @@ -103,10 +103,10 @@ test('read(n) is ignored', function(t) { }); test('can read objects from _read (sync)', function(t) { - var r = new Readable({ objectMode: true }); - var list = [{ one: '1'}, { two: '2' }]; + const r = new Readable({ objectMode: true }); + const list = [{ one: '1'}, { two: '2' }]; r._read = function(n) { - var item = list.shift(); + const item = list.shift(); r.push(item || null); }; @@ -121,10 +121,10 @@ test('can read objects from _read (sync)', function(t) { }); test('can read objects from _read (async)', function(t) { - var r = new Readable({ objectMode: true }); - var list = [{ one: '1'}, { two: '2' }]; + const r = new Readable({ objectMode: true }); + const list = [{ one: '1'}, { two: '2' }]; r._read = function(n) { - var item = list.shift(); + const item = list.shift(); process.nextTick(function() { r.push(item || null); }); @@ -141,11 +141,11 @@ test('can read objects from _read (async)', function(t) { }); test('can read strings as objects', function(t) { - var r = new Readable({ + const r = new Readable({ objectMode: true }); r._read = noop; - var list = ['one', 'two', 'three']; + const list = ['one', 'two', 'three']; list.forEach(function(str) { r.push(str); }); @@ -159,7 +159,7 @@ test('can read strings as objects', function(t) { }); test('read(0) for object streams', function(t) { - var r = new Readable({ + const r = new Readable({ objectMode: true }); r._read = noop; @@ -175,7 +175,7 @@ test('read(0) for object streams', function(t) { }); test('falsey values', function(t) { - var r = new Readable({ + const r = new Readable({ objectMode: true }); r._read = noop; @@ -193,12 +193,12 @@ test('falsey values', function(t) { }); test('high watermark _read', function(t) { - var r = new Readable({ + const r = new Readable({ highWaterMark: 6, objectMode: true }); - var calls = 0; - var list = ['1', '2', '3', '4', '5', '6', '7', '8']; + let calls = 0; + const list = ['1', '2', '3', '4', '5', '6', '7', '8']; r._read = function(n) { calls++; @@ -208,15 +208,15 @@ test('high watermark _read', function(t) { r.push(c); }); - var v = r.read(); + const v = r.read(); assert.strictEqual(calls, 0); assert.strictEqual(v, '1'); - var v2 = r.read(); + const v2 = r.read(); assert.strictEqual(v2, '2'); - var v3 = r.read(); + const v3 = r.read(); assert.strictEqual(v3, '3'); assert.strictEqual(calls, 1); @@ -225,13 +225,13 @@ test('high watermark _read', function(t) { }); test('high watermark push', function(t) { - var r = new Readable({ + const r = new Readable({ highWaterMark: 6, objectMode: true }); r._read = function(n) {}; - for (var i = 0; i < 6; i++) { - var bool = r.push(i); + for (let i = 0; i < 6; i++) { + const bool = r.push(i); assert.strictEqual(bool, i !== 5); } @@ -239,7 +239,7 @@ test('high watermark push', function(t) { }); test('can write objects to stream', function(t) { - var w = new Writable({ objectMode: true }); + const w = new Writable({ objectMode: true }); w._write = function(chunk, encoding, cb) { assert.deepStrictEqual(chunk, { foo: 'bar' }); @@ -255,8 +255,8 @@ test('can write objects to stream', function(t) { }); test('can write multiple objects to stream', function(t) { - var w = new Writable({ objectMode: true }); - var list = []; + const w = new Writable({ objectMode: true }); + const list = []; w._write = function(chunk, encoding, cb) { list.push(chunk); @@ -278,10 +278,10 @@ test('can write multiple objects to stream', function(t) { }); test('can write strings as objects', function(t) { - var w = new Writable({ + const w = new Writable({ objectMode: true }); - var list = []; + const list = []; w._write = function(chunk, encoding, cb) { list.push(chunk); @@ -303,10 +303,10 @@ test('can write strings as objects', function(t) { }); test('buffers finish until cb is called', function(t) { - var w = new Writable({ + const w = new Writable({ objectMode: true }); - var called = false; + let called = false; w._write = function(chunk, encoding, cb) { assert.strictEqual(chunk, 'foo'); diff --git a/test/parallel/test-stream2-pipe-error-once-listener.js b/test/parallel/test-stream2-pipe-error-once-listener.js index a2ddb7f5d6e720..908ac1bdb8e4ab 100644 --- a/test/parallel/test-stream2-pipe-error-once-listener.js +++ b/test/parallel/test-stream2-pipe-error-once-listener.js @@ -5,7 +5,7 @@ const util = require('util'); const stream = require('stream'); -var Read = function() { +const Read = function() { stream.Readable.call(this); }; util.inherits(Read, stream.Readable); @@ -16,7 +16,7 @@ Read.prototype._read = function(size) { }; -var Write = function() { +const Write = function() { stream.Writable.call(this); }; util.inherits(Write, stream.Writable); @@ -26,8 +26,8 @@ Write.prototype._write = function(buffer, encoding, cb) { this.emit('alldone'); }; -var read = new Read(); -var write = new Write(); +const read = new Read(); +const write = new Write(); write.once('error', function(err) {}); write.once('alldone', function(err) { diff --git a/test/parallel/test-stream2-push.js b/test/parallel/test-stream2-push.js index 26f27529071cbf..95a98450a3034e 100644 --- a/test/parallel/test-stream2-push.js +++ b/test/parallel/test-stream2-push.js @@ -14,20 +14,20 @@ const stream = new Readable({ encoding: 'utf8' }); -var source = new EE(); +const source = new EE(); stream._read = function() { console.error('stream._read'); readStart(); }; -var ended = false; +let ended = false; stream.on('end', function() { ended = true; }); source.on('data', function(chunk) { - var ret = stream.push(chunk); + const ret = stream.push(chunk); console.error('data', stream._readableState.length); if (!ret) readStop(); @@ -37,7 +37,7 @@ source.on('end', function() { stream.push(null); }); -var reading = false; +let reading = false; function readStart() { console.error('readStart'); @@ -48,19 +48,19 @@ function readStop() { console.error('readStop'); reading = false; process.nextTick(function() { - var r = stream.read(); + const r = stream.read(); if (r !== null) writer.write(r); }); } -var writer = new Writable({ +const writer = new Writable({ decodeStrings: false }); -var written = []; +const written = []; -var expectWritten = +const expectWritten = [ 'asdfgasdfgasdfgasdfg', 'asdfgasdfgasdfgasdfg', 'asdfgasdfgasdfgasdfg', @@ -79,9 +79,9 @@ writer.on('finish', finish); // now emit some chunks. -var chunk = 'asdfg'; +const chunk = 'asdfg'; -var set = 0; +let set = 0; readStart(); data(); function data() { diff --git a/test/parallel/test-stream2-read-sync-stack.js b/test/parallel/test-stream2-read-sync-stack.js index 1ba31a4b31b725..d4e11af3b8f7c1 100644 --- a/test/parallel/test-stream2-read-sync-stack.js +++ b/test/parallel/test-stream2-read-sync-stack.js @@ -1,16 +1,16 @@ 'use strict'; const common = require('../common'); const Readable = require('stream').Readable; -var r = new Readable(); -var N = 256 * 1024; +const r = new Readable(); +const N = 256 * 1024; // Go ahead and allow the pathological case for this test. // Yes, it's an infinite loop, that's the point. process.maxTickDepth = N + 2; -var reads = 0; +let reads = 0; r._read = function(n) { - var chunk = reads++ === N ? null : Buffer.allocUnsafe(1); + const chunk = reads++ === N ? null : Buffer.allocUnsafe(1); r.push(chunk); }; diff --git a/test/parallel/test-stream2-readable-empty-buffer-no-eof.js b/test/parallel/test-stream2-readable-empty-buffer-no-eof.js index ccbf087df00bf5..71d6f1e7236db2 100644 --- a/test/parallel/test-stream2-readable-empty-buffer-no-eof.js +++ b/test/parallel/test-stream2-readable-empty-buffer-no-eof.js @@ -69,8 +69,8 @@ function test1() { } function test2() { - var r = new Readable({ encoding: 'base64' }); - var reads = 5; + const r = new Readable({ encoding: 'base64' }); + let reads = 5; r._read = function(n) { if (!reads--) return r.push(null); // EOF @@ -78,9 +78,9 @@ function test2() { return r.push(Buffer.from('x')); }; - var results = []; + const results = []; function flow() { - var chunk; + let chunk; while (null !== (chunk = r.read())) results.push(chunk + ''); } diff --git a/test/parallel/test-stream2-readable-from-list.js b/test/parallel/test-stream2-readable-from-list.js index e38200e9d6ab1f..f3f39507e89dab 100644 --- a/test/parallel/test-stream2-readable-from-list.js +++ b/test/parallel/test-stream2-readable-from-list.js @@ -6,8 +6,8 @@ const fromList = require('_stream_readable')._fromList; const BufferList = require('internal/streams/BufferList'); // tiny node-tap lookalike. -var tests = []; -var count = 0; +const tests = []; +let count = 0; function test(name, fn) { count++; @@ -15,12 +15,12 @@ function test(name, fn) { } function run() { - var next = tests.shift(); + const next = tests.shift(); if (!next) return console.error('ok'); - var name = next[0]; - var fn = next[1]; + const name = next[0]; + const fn = next[1]; console.log('# %s', name); fn({ same: assert.deepStrictEqual, @@ -34,7 +34,7 @@ function run() { function bufferListFromArray(arr) { const bl = new BufferList(); - for (var i = 0; i < arr.length; ++i) + for (let i = 0; i < arr.length; ++i) bl.push(arr[i]); return bl; } @@ -48,14 +48,14 @@ process.nextTick(run); test('buffers', function(t) { - var list = [ Buffer.from('foog'), + let list = [ Buffer.from('foog'), Buffer.from('bark'), Buffer.from('bazy'), Buffer.from('kuel') ]; list = bufferListFromArray(list); // read more than the first element. - var ret = fromList(6, { buffer: list, length: 16 }); + let ret = fromList(6, { buffer: list, length: 16 }); t.equal(ret.toString(), 'foogba'); // read exactly the first element. @@ -77,14 +77,14 @@ test('buffers', function(t) { }); test('strings', function(t) { - var list = [ 'foog', + let list = [ 'foog', 'bark', 'bazy', 'kuel' ]; list = bufferListFromArray(list); // read more than the first element. - var ret = fromList(6, { buffer: list, length: 16, decoder: true }); + let ret = fromList(6, { buffer: list, length: 16, decoder: true }); t.equal(ret, 'foogba'); // read exactly the first element. diff --git a/test/parallel/test-stream2-readable-legacy-drain.js b/test/parallel/test-stream2-readable-legacy-drain.js index 1b8a4ac1ffeca3..d6db6ba232c693 100644 --- a/test/parallel/test-stream2-readable-legacy-drain.js +++ b/test/parallel/test-stream2-readable-legacy-drain.js @@ -3,20 +3,20 @@ const common = require('../common'); const assert = require('assert'); const Stream = require('stream'); -var Readable = Stream.Readable; +const Readable = Stream.Readable; -var r = new Readable(); -var N = 256; -var reads = 0; +const r = new Readable(); +const N = 256; +let reads = 0; r._read = function(n) { return r.push(++reads === N ? null : Buffer.allocUnsafe(1)); }; r.on('end', common.mustCall(function() {})); -var w = new Stream(); +const w = new Stream(); w.writable = true; -var buffered = 0; +let buffered = 0; w.write = function(c) { buffered += c.length; process.nextTick(drain); diff --git a/test/parallel/test-stream2-readable-non-empty-end.js b/test/parallel/test-stream2-readable-non-empty-end.js index 0a4eb131c312ab..66fae8274ecf3c 100644 --- a/test/parallel/test-stream2-readable-non-empty-end.js +++ b/test/parallel/test-stream2-readable-non-empty-end.js @@ -3,17 +3,17 @@ const common = require('../common'); const assert = require('assert'); const Readable = require('_stream_readable'); -var len = 0; -var chunks = new Array(10); -for (var i = 1; i <= 10; i++) { +let len = 0; +const chunks = new Array(10); +for (let i = 1; i <= 10; i++) { chunks[i - 1] = Buffer.allocUnsafe(i); len += i; } -var test = new Readable(); -var n = 0; +const test = new Readable(); +let n = 0; test._read = function(size) { - var chunk = chunks[n++]; + const chunk = chunks[n++]; setTimeout(function() { test.push(chunk === undefined ? null : chunk); }, 1); @@ -24,10 +24,10 @@ function thrower() { throw new Error('this should not happen!'); } -var bytesread = 0; +let bytesread = 0; test.on('readable', function() { - var b = len - bytesread - 1; - var res = test.read(b); + const b = len - bytesread - 1; + const res = test.read(b); if (res) { bytesread += res.length; console.error('br=%d len=%d', bytesread, len); @@ -43,7 +43,7 @@ function next() { test.on('end', common.mustCall(function() {})); // one to get the last byte - var r = test.read(); + let r = test.read(); assert(r); assert.equal(r.length, 1); r = test.read(); diff --git a/test/parallel/test-stream2-readable-wrap-empty.js b/test/parallel/test-stream2-readable-wrap-empty.js index aa48c20bb83703..5b2dae3c5327fa 100644 --- a/test/parallel/test-stream2-readable-wrap-empty.js +++ b/test/parallel/test-stream2-readable-wrap-empty.js @@ -4,11 +4,11 @@ const common = require('../common'); const Readable = require('_stream_readable'); const EE = require('events').EventEmitter; -var oldStream = new EE(); +const oldStream = new EE(); oldStream.pause = function() {}; oldStream.resume = function() {}; -var newStream = new Readable().wrap(oldStream); +const newStream = new Readable().wrap(oldStream); newStream .on('readable', function() {}) diff --git a/test/parallel/test-stream2-set-encoding.js b/test/parallel/test-stream2-set-encoding.js index c7cc7c3c0bfb2f..fdbd81e61332b1 100644 --- a/test/parallel/test-stream2-set-encoding.js +++ b/test/parallel/test-stream2-set-encoding.js @@ -5,8 +5,8 @@ const R = require('_stream_readable'); const util = require('util'); // tiny node-tap lookalike. -var tests = []; -var count = 0; +const tests = []; +let count = 0; function test(name, fn) { count++; @@ -14,12 +14,12 @@ function test(name, fn) { } function run() { - var next = tests.shift(); + const next = tests.shift(); if (!next) return console.error('ok'); - var name = next[0]; - var fn = next[1]; + const name = next[0]; + const fn = next[1]; console.log('# %s', name); fn({ same: assert.deepStrictEqual, @@ -66,7 +66,7 @@ TestReader.prototype._read = function(n) { } this.pos += n; - var ret = Buffer.alloc(n, 'a'); + const ret = Buffer.alloc(n, 'a'); console.log('this.push(ret)', ret); @@ -75,10 +75,10 @@ TestReader.prototype._read = function(n) { }; test('setEncoding utf8', function(t) { - var tr = new TestReader(100); + const tr = new TestReader(100); tr.setEncoding('utf8'); - var out = []; - var expect = + const out = []; + const expect = [ 'aaaaaaaaaa', 'aaaaaaaaaa', 'aaaaaaaaaa', @@ -91,7 +91,7 @@ test('setEncoding utf8', function(t) { 'aaaaaaaaaa' ]; tr.on('readable', function flow() { - var chunk; + let chunk; while (null !== (chunk = tr.read(10))) out.push(chunk); }); @@ -104,10 +104,10 @@ test('setEncoding utf8', function(t) { test('setEncoding hex', function(t) { - var tr = new TestReader(100); + const tr = new TestReader(100); tr.setEncoding('hex'); - var out = []; - var expect = + const out = []; + const expect = [ '6161616161', '6161616161', '6161616161', @@ -130,7 +130,7 @@ test('setEncoding hex', function(t) { '6161616161' ]; tr.on('readable', function flow() { - var chunk; + let chunk; while (null !== (chunk = tr.read(10))) out.push(chunk); }); @@ -142,10 +142,10 @@ test('setEncoding hex', function(t) { }); test('setEncoding hex with read(13)', function(t) { - var tr = new TestReader(100); + const tr = new TestReader(100); tr.setEncoding('hex'); - var out = []; - var expect = + const out = []; + const expect = [ '6161616161616', '1616161616161', '6161616161616', @@ -165,7 +165,7 @@ test('setEncoding hex with read(13)', function(t) { tr.on('readable', function flow() { console.log('readable once'); - var chunk; + let chunk; while (null !== (chunk = tr.read(13))) out.push(chunk); }); @@ -178,10 +178,10 @@ test('setEncoding hex with read(13)', function(t) { }); test('setEncoding base64', function(t) { - var tr = new TestReader(100); + const tr = new TestReader(100); tr.setEncoding('base64'); - var out = []; - var expect = + const out = []; + const expect = [ 'YWFhYWFhYW', 'FhYWFhYWFh', 'YWFhYWFhYW', @@ -198,7 +198,7 @@ test('setEncoding base64', function(t) { 'FhYQ==' ]; tr.on('readable', function flow() { - var chunk; + let chunk; while (null !== (chunk = tr.read(10))) out.push(chunk); }); @@ -210,9 +210,9 @@ test('setEncoding base64', function(t) { }); test('encoding: utf8', function(t) { - var tr = new TestReader(100, { encoding: 'utf8' }); - var out = []; - var expect = + const tr = new TestReader(100, { encoding: 'utf8' }); + const out = []; + const expect = [ 'aaaaaaaaaa', 'aaaaaaaaaa', 'aaaaaaaaaa', @@ -225,7 +225,7 @@ test('encoding: utf8', function(t) { 'aaaaaaaaaa' ]; tr.on('readable', function flow() { - var chunk; + let chunk; while (null !== (chunk = tr.read(10))) out.push(chunk); }); @@ -238,9 +238,9 @@ test('encoding: utf8', function(t) { test('encoding: hex', function(t) { - var tr = new TestReader(100, { encoding: 'hex' }); - var out = []; - var expect = + const tr = new TestReader(100, { encoding: 'hex' }); + const out = []; + const expect = [ '6161616161', '6161616161', '6161616161', @@ -263,7 +263,7 @@ test('encoding: hex', function(t) { '6161616161' ]; tr.on('readable', function flow() { - var chunk; + let chunk; while (null !== (chunk = tr.read(10))) out.push(chunk); }); @@ -275,9 +275,9 @@ test('encoding: hex', function(t) { }); test('encoding: hex with read(13)', function(t) { - var tr = new TestReader(100, { encoding: 'hex' }); - var out = []; - var expect = + const tr = new TestReader(100, { encoding: 'hex' }); + const out = []; + const expect = [ '6161616161616', '1616161616161', '6161616161616', @@ -296,7 +296,7 @@ test('encoding: hex with read(13)', function(t) { '16161' ]; tr.on('readable', function flow() { - var chunk; + let chunk; while (null !== (chunk = tr.read(13))) out.push(chunk); }); @@ -308,9 +308,9 @@ test('encoding: hex with read(13)', function(t) { }); test('encoding: base64', function(t) { - var tr = new TestReader(100, { encoding: 'base64' }); - var out = []; - var expect = + const tr = new TestReader(100, { encoding: 'base64' }); + const out = []; + const expect = [ 'YWFhYWFhYW', 'FhYWFhYWFh', 'YWFhYWFhYW', @@ -327,7 +327,7 @@ test('encoding: base64', function(t) { 'FhYQ==' ]; tr.on('readable', function flow() { - var chunk; + let chunk; while (null !== (chunk = tr.read(10))) out.push(chunk); }); @@ -339,7 +339,7 @@ test('encoding: base64', function(t) { }); test('chainable', function(t) { - var tr = new TestReader(100); + const tr = new TestReader(100); t.equal(tr.setEncoding('utf8'), tr); t.end(); }); diff --git a/test/parallel/test-stream2-transform.js b/test/parallel/test-stream2-transform.js index 0777ada97fb376..d66f1f064375e4 100644 --- a/test/parallel/test-stream2-transform.js +++ b/test/parallel/test-stream2-transform.js @@ -5,8 +5,8 @@ const PassThrough = require('_stream_passthrough'); const Transform = require('_stream_transform'); // tiny node-tap lookalike. -var tests = []; -var count = 0; +const tests = []; +let count = 0; function test(name, fn) { count++; @@ -14,12 +14,12 @@ function test(name, fn) { } function run() { - var next = tests.shift(); + const next = tests.shift(); if (!next) return console.error('ok'); - var name = next[0]; - var fn = next[1]; + const name = next[0]; + const fn = next[1]; console.log('# %s', name); fn({ same: assert.deepStrictEqual, @@ -42,18 +42,18 @@ process.nextTick(run); ///// test('writable side consumption', function(t) { - var tx = new Transform({ + const tx = new Transform({ highWaterMark: 10 }); - var transformed = 0; + let transformed = 0; tx._transform = function(chunk, encoding, cb) { transformed += chunk.length; tx.push(chunk); cb(); }; - for (var i = 1; i <= 10; i++) { + for (let i = 1; i <= 10; i++) { tx.write(Buffer.allocUnsafe(i)); } tx.end(); @@ -69,7 +69,7 @@ test('writable side consumption', function(t) { }); test('passthrough', function(t) { - var pt = new PassThrough(); + const pt = new PassThrough(); pt.write(Buffer.from('foog')); pt.write(Buffer.from('bark')); @@ -85,7 +85,7 @@ test('passthrough', function(t) { }); test('object passthrough', function(t) { - var pt = new PassThrough({ objectMode: true }); + const pt = new PassThrough({ objectMode: true }); pt.write(1); pt.write(true); @@ -115,9 +115,9 @@ test('passthrough constructor', function(t) { }); test('simple transform', function(t) { - var pt = new Transform(); + const pt = new Transform(); pt._transform = function(c, e, cb) { - var ret = Buffer.alloc(c.length, 'x'); + const ret = Buffer.alloc(c.length, 'x'); pt.push(ret); cb(); }; @@ -136,7 +136,7 @@ test('simple transform', function(t) { }); test('simple object transform', function(t) { - var pt = new Transform({ objectMode: true }); + const pt = new Transform({ objectMode: true }); pt._transform = function(c, e, cb) { pt.push(JSON.stringify(c)); cb(); @@ -162,7 +162,7 @@ test('simple object transform', function(t) { }); test('async passthrough', function(t) { - var pt = new Transform(); + const pt = new Transform(); pt._transform = function(chunk, encoding, cb) { setTimeout(function() { pt.push(chunk); @@ -186,7 +186,7 @@ test('async passthrough', function(t) { }); test('assymetric transform (expand)', function(t) { - var pt = new Transform(); + const pt = new Transform(); // emit each chunk 2 times. pt._transform = function(chunk, encoding, cb) { @@ -218,7 +218,7 @@ test('assymetric transform (expand)', function(t) { }); test('assymetric transform (compress)', function(t) { - var pt = new Transform(); + const pt = new Transform(); // each output is the first char of 3 consecutive chunks, // or whatever's left. @@ -227,7 +227,7 @@ test('assymetric transform (compress)', function(t) { pt._transform = function(chunk, encoding, cb) { if (!chunk) chunk = ''; - var s = chunk.toString(); + const s = chunk.toString(); setTimeout(function() { this.state += s.charAt(0); if (this.state.length === 3) { @@ -273,9 +273,9 @@ test('assymetric transform (compress)', function(t) { // this tests for a stall when data is written to a full stream // that has empty transforms. test('complex transform', function(t) { - var count = 0; - var saved = null; - var pt = new Transform({highWaterMark: 3}); + let count = 0; + let saved = null; + const pt = new Transform({highWaterMark: 3}); pt._transform = function(c, e, cb) { if (count++ === 1) saved = c; @@ -307,8 +307,8 @@ test('complex transform', function(t) { test('passthrough event emission', function(t) { - var pt = new PassThrough(); - var emits = 0; + const pt = new PassThrough(); + let emits = 0; pt.on('readable', function() { console.error('>>> emit readable %d', emits); emits++; @@ -353,8 +353,8 @@ test('passthrough event emission', function(t) { }); test('passthrough event emission reordered', function(t) { - var pt = new PassThrough(); - var emits = 0; + const pt = new PassThrough(); + let emits = 0; pt.on('readable', function() { console.error('emit readable', emits); emits++; @@ -395,8 +395,8 @@ test('passthrough event emission reordered', function(t) { test('passthrough facaded', function(t) { console.error('passthrough facaded'); - var pt = new PassThrough(); - var datas = []; + const pt = new PassThrough(); + const datas = []; pt.on('data', function(chunk) { datas.push(chunk.toString()); }); @@ -423,7 +423,7 @@ test('passthrough facaded', function(t) { test('object transform (json parse)', function(t) { console.error('json parse stream'); - var jp = new Transform({ objectMode: true }); + const jp = new Transform({ objectMode: true }); jp._transform = function(data, encoding, cb) { try { jp.push(JSON.parse(data)); @@ -435,21 +435,21 @@ test('object transform (json parse)', function(t) { // anything except null/undefined is fine. // those are "magic" in the stream API, because they signal EOF. - var objects = [ + const objects = [ { foo: 'bar' }, 100, 'string', { nested: { things: [ { foo: 'bar' }, 100, 'string' ] } } ]; - var ended = false; + let ended = false; jp.on('end', function() { ended = true; }); objects.forEach(function(obj) { jp.write(JSON.stringify(obj)); - var res = jp.read(); + const res = jp.read(); t.same(res, obj); }); @@ -465,7 +465,7 @@ test('object transform (json parse)', function(t) { test('object transform (json stringify)', function(t) { console.error('json parse stream'); - var js = new Transform({ objectMode: true }); + const js = new Transform({ objectMode: true }); js._transform = function(data, encoding, cb) { try { js.push(JSON.stringify(data)); @@ -477,21 +477,21 @@ test('object transform (json stringify)', function(t) { // anything except null/undefined is fine. // those are "magic" in the stream API, because they signal EOF. - var objects = [ + const objects = [ { foo: 'bar' }, 100, 'string', { nested: { things: [ { foo: 'bar' }, 100, 'string' ] } } ]; - var ended = false; + let ended = false; js.on('end', function() { ended = true; }); objects.forEach(function(obj) { js.write(obj); - var res = js.read(); + const res = js.read(); t.equal(res, JSON.stringify(obj)); }); diff --git a/test/parallel/test-stream2-unpipe-leak.js b/test/parallel/test-stream2-unpipe-leak.js index 2004a8194c7803..1a1599ca32b4c7 100644 --- a/test/parallel/test-stream2-unpipe-leak.js +++ b/test/parallel/test-stream2-unpipe-leak.js @@ -3,7 +3,7 @@ require('../common'); const assert = require('assert'); const stream = require('stream'); -var chunk = Buffer.from('hallo'); +const chunk = Buffer.from('hallo'); const util = require('util'); @@ -16,7 +16,7 @@ TestWriter.prototype._write = function(buffer, encoding, callback) { callback(null); }; -var dest = new TestWriter(); +const dest = new TestWriter(); // Set this high so that we'd trigger a nextTick warning // and/or RangeError if we do maybeReadMore wrong. @@ -29,9 +29,9 @@ TestReader.prototype._read = function(size) { this.push(chunk); }; -var src = new TestReader(); +const src = new TestReader(); -for (var i = 0; i < 10; i++) { +for (let i = 0; i < 10; i++) { src.pipe(dest); src.unpipe(dest); } diff --git a/test/parallel/test-stream2-writable.js b/test/parallel/test-stream2-writable.js index 4d98457e7d6eaa..c377ce9a510caa 100644 --- a/test/parallel/test-stream2-writable.js +++ b/test/parallel/test-stream2-writable.js @@ -22,14 +22,14 @@ TestWriter.prototype._write = function(chunk, encoding, cb) { }.bind(this), Math.floor(Math.random() * 10)); }; -var chunks = new Array(50); -for (var i = 0; i < chunks.length; i++) { +const chunks = new Array(50); +for (let i = 0; i < chunks.length; i++) { chunks[i] = new Array(i + 1).join('x'); } // tiny node-tap lookalike. -var tests = []; -var count = 0; +const tests = []; +let count = 0; function test(name, fn) { count++; @@ -37,12 +37,12 @@ function test(name, fn) { } function run() { - var next = tests.shift(); + const next = tests.shift(); if (!next) return console.error('ok'); - var name = next[0]; - var fn = next[1]; + const name = next[0]; + const fn = next[1]; console.log('# %s', name); fn({ same: assert.deepStrictEqual, @@ -62,7 +62,7 @@ process.on('exit', function() { process.nextTick(run); test('write fast', function(t) { - var tw = new TestWriter({ + const tw = new TestWriter({ highWaterMark: 100 }); @@ -79,7 +79,7 @@ test('write fast', function(t) { }); test('write slow', function(t) { - var tw = new TestWriter({ + const tw = new TestWriter({ highWaterMark: 100 }); @@ -88,7 +88,7 @@ test('write slow', function(t) { t.end(); }); - var i = 0; + let i = 0; (function W() { tw.write(chunks[i++]); if (i < chunks.length) @@ -99,11 +99,11 @@ test('write slow', function(t) { }); test('write backpressure', function(t) { - var tw = new TestWriter({ + const tw = new TestWriter({ highWaterMark: 50 }); - var drains = 0; + let drains = 0; tw.on('finish', function() { t.same(tw.buffer, chunks, 'got chunks in the right order'); @@ -115,10 +115,11 @@ test('write backpressure', function(t) { drains++; }); - var i = 0; + let i = 0; (function W() { + let ret; do { - var ret = tw.write(chunks[i++]); + ret = tw.write(chunks[i++]); } while (ret !== false && i < chunks.length); if (i < chunks.length) { @@ -131,11 +132,11 @@ test('write backpressure', function(t) { }); test('write bufferize', function(t) { - var tw = new TestWriter({ + const tw = new TestWriter({ highWaterMark: 100 }); - var encodings = + const encodings = [ 'hex', 'utf8', 'utf-8', @@ -154,7 +155,7 @@ test('write bufferize', function(t) { }); chunks.forEach(function(chunk, i) { - var enc = encodings[i % encodings.length]; + const enc = encodings[i % encodings.length]; chunk = Buffer.from(chunk); tw.write(chunk.toString(enc), enc); }); @@ -162,7 +163,7 @@ test('write bufferize', function(t) { }); test('write no bufferize', function(t) { - var tw = new TestWriter({ + const tw = new TestWriter({ highWaterMark: 100, decodeStrings: false }); @@ -173,7 +174,7 @@ test('write no bufferize', function(t) { return TestWriter.prototype._write.call(this, chunk, encoding, cb); }; - var encodings = + const encodings = [ 'hex', 'utf8', 'utf-8', @@ -192,7 +193,7 @@ test('write no bufferize', function(t) { }); chunks.forEach(function(chunk, i) { - var enc = encodings[i % encodings.length]; + const enc = encodings[i % encodings.length]; chunk = Buffer.from(chunk); tw.write(chunk.toString(enc), enc); }); @@ -200,7 +201,7 @@ test('write no bufferize', function(t) { }); test('write callbacks', function(t) { - var callbacks = chunks.map(function(chunk, i) { + const callbacks = chunks.map(function(chunk, i) { return [i, function() { callbacks._called[i] = chunk; }]; @@ -210,7 +211,7 @@ test('write callbacks', function(t) { }, {}); callbacks._called = []; - var tw = new TestWriter({ + const tw = new TestWriter({ highWaterMark: 100 }); @@ -229,28 +230,28 @@ test('write callbacks', function(t) { }); test('end callback', function(t) { - var tw = new TestWriter(); + const tw = new TestWriter(); tw.end(function() { t.end(); }); }); test('end callback with chunk', function(t) { - var tw = new TestWriter(); + const tw = new TestWriter(); tw.end(Buffer.from('hello world'), function() { t.end(); }); }); test('end callback with chunk and encoding', function(t) { - var tw = new TestWriter(); + const tw = new TestWriter(); tw.end('hello world', 'ascii', function() { t.end(); }); }); test('end callback after .write() call', function(t) { - var tw = new TestWriter(); + const tw = new TestWriter(); tw.write(Buffer.from('hello world')); tw.end(function() { t.end(); @@ -258,8 +259,8 @@ test('end callback after .write() call', function(t) { }); test('end callback called after write callback', function(t) { - var tw = new TestWriter(); - var writeCalledback = false; + const tw = new TestWriter(); + let writeCalledback = false; tw.write(Buffer.from('hello world'), function() { writeCalledback = true; }); @@ -270,20 +271,20 @@ test('end callback called after write callback', function(t) { }); test('encoding should be ignored for buffers', function(t) { - var tw = new W(); - var hex = '018b5e9a8f6236ffe30e31baf80d2cf6eb'; + const tw = new W(); + const hex = '018b5e9a8f6236ffe30e31baf80d2cf6eb'; tw._write = function(chunk) { t.equal(chunk.toString('hex'), hex); t.end(); }; - var buf = Buffer.from(hex, 'hex'); + const buf = Buffer.from(hex, 'hex'); tw.write(buf, 'latin1'); }); test('writables are not pipable', function(t) { - var w = new W(); + const w = new W(); w._write = function() {}; - var gotError = false; + let gotError = false; w.on('error', function() { gotError = true; }); @@ -293,10 +294,10 @@ test('writables are not pipable', function(t) { }); test('duplexes are pipable', function(t) { - var d = new D(); + const d = new D(); d._read = function() {}; d._write = function() {}; - var gotError = false; + let gotError = false; d.on('error', function() { gotError = true; }); @@ -306,9 +307,9 @@ test('duplexes are pipable', function(t) { }); test('end(chunk) two times is an error', function(t) { - var w = new W(); + const w = new W(); w._write = function() {}; - var gotError = false; + let gotError = false; w.on('error', function(er) { gotError = true; t.equal(er.message, 'write after end'); @@ -322,8 +323,8 @@ test('end(chunk) two times is an error', function(t) { }); test('dont end while writing', function(t) { - var w = new W(); - var wrote = false; + const w = new W(); + let wrote = false; w._write = function(chunk, e, cb) { assert(!this.writing); wrote = true; @@ -342,8 +343,8 @@ test('dont end while writing', function(t) { }); test('finish does not come before write cb', function(t) { - var w = new W(); - var writeCb = false; + const w = new W(); + let writeCb = false; w._write = function(chunk, e, cb) { setTimeout(function() { writeCb = true; @@ -359,8 +360,8 @@ test('finish does not come before write cb', function(t) { }); test('finish does not come before sync _write cb', function(t) { - var w = new W(); - var writeCb = false; + const w = new W(); + let writeCb = false; w._write = function(chunk, e, cb) { cb(); }; @@ -375,7 +376,7 @@ test('finish does not come before sync _write cb', function(t) { }); test('finish is emitted if last chunk is empty', function(t) { - var w = new W(); + const w = new W(); w._write = function(chunk, e, cb) { process.nextTick(cb); }; diff --git a/test/parallel/test-stream3-cork-end.js b/test/parallel/test-stream3-cork-end.js index a0b611d0da1b66..230227e0b13ddb 100644 --- a/test/parallel/test-stream3-cork-end.js +++ b/test/parallel/test-stream3-cork-end.js @@ -12,11 +12,11 @@ const Writable = stream.Writable; // node version target: 0.12 const expectedChunks = ['please', 'buffer', 'me', 'kindly']; -var inputChunks = expectedChunks.slice(0); -var seenChunks = []; -var seenEnd = false; +const inputChunks = expectedChunks.slice(0); +let seenChunks = []; +let seenEnd = false; -var w = new Writable(); +const w = new Writable(); // lets arrange to store the chunks w._write = function(chunk, encoding, cb) { // stream end event is not seen before the last write @@ -33,8 +33,8 @@ w.on('finish', () => { }); function writeChunks(remainingChunks, callback) { - var writeChunk = remainingChunks.shift(); - var writeState; + const writeChunk = remainingChunks.shift(); + let writeState; if (writeChunk) { setImmediate(() => { @@ -74,12 +74,12 @@ writeChunks(inputChunks, () => { assert.equal(seenChunks.length, 4); // did the chunks match - for (var i = 0, l = expectedChunks.length; i < l; i++) { - var seen = seenChunks[i]; + for (let i = 0, l = expectedChunks.length; i < l; i++) { + const seen = seenChunks[i]; // there was a chunk assert.ok(seen); - var expected = new Buffer(expectedChunks[i]); + const expected = new Buffer(expectedChunks[i]); // it was what we expected assert.ok(seen.equals(expected)); } diff --git a/test/parallel/test-stream3-cork-uncork.js b/test/parallel/test-stream3-cork-uncork.js index cd86e8cf809bac..821fd22bf8b8a3 100644 --- a/test/parallel/test-stream3-cork-uncork.js +++ b/test/parallel/test-stream3-cork-uncork.js @@ -12,11 +12,11 @@ const Writable = stream.Writable; // node version target: 0.12 const expectedChunks = ['please', 'buffer', 'me', 'kindly']; -var inputChunks = expectedChunks.slice(0); -var seenChunks = []; -var seenEnd = false; +const inputChunks = expectedChunks.slice(0); +let seenChunks = []; +let seenEnd = false; -var w = new Writable(); +const w = new Writable(); // lets arrange to store the chunks w._write = function(chunk, encoding, cb) { // default encoding given none was specified @@ -31,8 +31,8 @@ w.on('finish', () => { }); function writeChunks(remainingChunks, callback) { - var writeChunk = remainingChunks.shift(); - var writeState; + const writeChunk = remainingChunks.shift(); + let writeState; if (writeChunk) { setImmediate(() => { @@ -69,12 +69,12 @@ writeChunks(inputChunks, () => { assert.equal(seenChunks.length, 4); // did the chunks match - for (var i = 0, l = expectedChunks.length; i < l; i++) { - var seen = seenChunks[i]; + for (let i = 0, l = expectedChunks.length; i < l; i++) { + const seen = seenChunks[i]; // there was a chunk assert.ok(seen); - var expected = new Buffer(expectedChunks[i]); + const expected = new Buffer(expectedChunks[i]); // it was what we expected assert.ok(seen.equals(expected)); } diff --git a/test/parallel/test-stream3-pause-then-read.js b/test/parallel/test-stream3-pause-then-read.js index 996f91cf79f9b4..5a9550bcd41d7f 100644 --- a/test/parallel/test-stream3-pause-then-read.js +++ b/test/parallel/test-stream3-pause-then-read.js @@ -3,16 +3,16 @@ require('../common'); const assert = require('assert'); const stream = require('stream'); -var Readable = stream.Readable; -var Writable = stream.Writable; +const Readable = stream.Readable; +const Writable = stream.Writable; -var totalChunks = 100; -var chunkSize = 99; -var expectTotalData = totalChunks * chunkSize; -var expectEndingData = expectTotalData; +const totalChunks = 100; +const chunkSize = 99; +const expectTotalData = totalChunks * chunkSize; +let expectEndingData = expectTotalData; -var r = new Readable({ highWaterMark: 1000 }); -var chunks = totalChunks; +const r = new Readable({ highWaterMark: 1000 }); +let chunks = totalChunks; r._read = function(n) { if (!(chunks % 2)) setImmediate(push); @@ -22,9 +22,9 @@ r._read = function(n) { push(); }; -var totalPushed = 0; +let totalPushed = 0; function push() { - var chunk = chunks-- > 0 ? Buffer.alloc(chunkSize, 'x') : null; + const chunk = chunks-- > 0 ? Buffer.alloc(chunkSize, 'x') : null; if (chunk) { totalPushed += chunk.length; } @@ -42,7 +42,7 @@ function readn(n, then) { console.error('read %d', n); expectEndingData -= n; (function read() { - var c = r.read(n); + const c = r.read(n); if (!c) r.once('readable', read); else { @@ -57,7 +57,7 @@ function readn(n, then) { function onData() { expectEndingData -= 100; console.error('onData'); - var seen = 0; + let seen = 0; r.on('data', function od(c) { seen += c.length; if (seen >= 100) { @@ -67,7 +67,7 @@ function onData() { if (seen > 100) { // oh no, seen too much! // put the extra back. - var diff = seen - 100; + const diff = seen - 100; r.unshift(c.slice(c.length - diff)); console.error('seen too much', seen, diff); } @@ -82,8 +82,8 @@ function onData() { function pipeLittle() { expectEndingData -= 200; console.error('pipe a little'); - var w = new Writable(); - var written = 0; + const w = new Writable(); + let written = 0; w.on('finish', function() { assert.equal(written, 200); setImmediate(read1234); @@ -95,7 +95,7 @@ function pipeLittle() { w.end(); cb(); if (written > 200) { - var diff = written - 200; + const diff = written - 200; written -= diff; r.unshift(chunk.slice(chunk.length - diff)); } @@ -130,8 +130,8 @@ function resumePause() { function pipe() { console.error('pipe the rest'); - var w = new Writable(); - var written = 0; + const w = new Writable(); + let written = 0; w._write = function(chunk, encoding, cb) { written += chunk.length; cb(); diff --git a/test/parallel/test-string-decoder-end.js b/test/parallel/test-string-decoder-end.js index 9b6696977c8267..2c187d60142bbf 100644 --- a/test/parallel/test-string-decoder-end.js +++ b/test/parallel/test-string-decoder-end.js @@ -6,15 +6,15 @@ require('../common'); const assert = require('assert'); const SD = require('string_decoder').StringDecoder; -var encodings = ['base64', 'hex', 'utf8', 'utf16le', 'ucs2']; +const encodings = ['base64', 'hex', 'utf8', 'utf16le', 'ucs2']; -var bufs = [ '☃💩', 'asdf' ].map(function(b) { +const bufs = [ '☃💩', 'asdf' ].map(function(b) { return Buffer.from(b); }); // also test just arbitrary bytes from 0-15. -for (var i = 1; i <= 16; i++) { - var bytes = new Array(i).join('.').split('.').map(function(_, j) { +for (let i = 1; i <= 16; i++) { + const bytes = new Array(i).join('.').split('.').map(function(_, j) { return j + 0x78; }); bufs.push(Buffer.from(bytes)); @@ -34,21 +34,21 @@ function testBuf(encoding, buf) { console.error('# %s', encoding, buf); // write one byte at a time. - var s = new SD(encoding); - var res1 = ''; - for (var i = 0; i < buf.length; i++) { + let s = new SD(encoding); + let res1 = ''; + for (let i = 0; i < buf.length; i++) { res1 += s.write(buf.slice(i, i + 1)); } res1 += s.end(); // write the whole buffer at once. - var res2 = ''; + let res2 = ''; s = new SD(encoding); res2 += s.write(buf); res2 += s.end(); // .toString() on the buffer - var res3 = buf.toString(encoding); + const res3 = buf.toString(encoding); console.log('expect=%j', res3); console.log('res1=%j', res1); diff --git a/test/parallel/test-string-decoder.js b/test/parallel/test-string-decoder.js index 97c0aafef237ed..77ffbfcc73b1e1 100644 --- a/test/parallel/test-string-decoder.js +++ b/test/parallel/test-string-decoder.js @@ -5,7 +5,7 @@ const inspect = require('util').inspect; const StringDecoder = require('string_decoder').StringDecoder; // Test default encoding -var decoder = new StringDecoder(); +let decoder = new StringDecoder(); assert.strictEqual(decoder.encoding, 'utf8'); process.stdout.write('scanning '); @@ -110,22 +110,22 @@ assert.strictEqual(decoder.end(), '\ud83d'); // singleSequence allows for easy debugging of a specific sequence which is // useful in case of test failures. function test(encoding, input, expected, singleSequence) { - var sequences; + let sequences; if (!singleSequence) { sequences = writeSequences(input.length); } else { sequences = [singleSequence]; } sequences.forEach(function(sequence) { - var decoder = new StringDecoder(encoding); - var output = ''; + const decoder = new StringDecoder(encoding); + let output = ''; sequence.forEach(function(write) { output += decoder.write(input.slice(write[0], write[1])); }); output += decoder.end(); process.stdout.write('.'); if (output !== expected) { - var message = + const message = 'Expected "' + unicodeEscape(expected) + '", ' + 'but got "' + unicodeEscape(output) + '"\n' + 'input: ' + input.toString('hex').match(/.{2}/g) + '\n' + @@ -138,8 +138,8 @@ function test(encoding, input, expected, singleSequence) { // unicodeEscape prints the str contents as unicode escape codes. function unicodeEscape(str) { - var r = ''; - for (var i = 0; i < str.length; i++) { + let r = ''; + for (let i = 0; i < str.length; i++) { r += '\\u' + str.charCodeAt(i).toString(16); } return r; @@ -162,10 +162,10 @@ function writeSequences(length, start, sequence) { } else if (start === length) { return [sequence]; } - var sequences = []; - for (var end = length; end > start; end--) { - var subSequence = sequence.concat([[start, end]]); - var subSequences = writeSequences(length, end, subSequence, sequences); + let sequences = []; + for (let end = length; end > start; end--) { + const subSequence = sequence.concat([[start, end]]); + const subSequences = writeSequences(length, end, subSequence, sequences); sequences = sequences.concat(subSequences); } return sequences; diff --git a/test/parallel/test-stringbytes-external.js b/test/parallel/test-stringbytes-external.js index e0d8c4552e02c7..a242b943c91a4d 100644 --- a/test/parallel/test-stringbytes-external.js +++ b/test/parallel/test-stringbytes-external.js @@ -2,17 +2,17 @@ require('../common'); const assert = require('assert'); // minimum string size to overflow into external string space -var EXTERN_APEX = 0xFBEE9; +const EXTERN_APEX = 0xFBEE9; // manually controlled string for checking binary output -var ucs2_control = 'a\u0000'; -var write_str = 'a'; +let ucs2_control = 'a\u0000'; +let write_str = 'a'; // first do basic checks -var b = Buffer.from(write_str, 'ucs2'); +let b = Buffer.from(write_str, 'ucs2'); // first check latin1 -var c = b.toString('latin1'); +let c = b.toString('latin1'); assert.equal(b[0], 0x61); assert.equal(b[1], 0); assert.equal(ucs2_control, c); @@ -23,7 +23,7 @@ assert.equal(b[1], 0); assert.equal(ucs2_control, c); // now create big strings -var size = 1 + (1 << 20); +const size = 1 + (1 << 20); write_str = Array(size).join(write_str); ucs2_control = Array(size).join(ucs2_control); @@ -36,19 +36,19 @@ for (let i = 0; i < b.length; i += 2) { } // create another string to create an external string -var b_ucs = b.toString('ucs2'); +const b_ucs = b.toString('ucs2'); // check control against external binary string -var l_bin = b.toString('latin1'); +const l_bin = b.toString('latin1'); assert.equal(ucs2_control, l_bin); // check control against external binary string -var b_bin = b.toString('binary'); +const b_bin = b.toString('binary'); assert.equal(ucs2_control, b_bin); // create buffer copy from external -var c_bin = Buffer.from(l_bin, 'latin1'); -var c_ucs = Buffer.from(b_ucs, 'ucs2'); +const c_bin = Buffer.from(l_bin, 'latin1'); +const c_ucs = Buffer.from(b_ucs, 'ucs2'); // make sure they're the same length assert.equal(c_bin.length, c_ucs.length); // make sure Buffers from externals are the same @@ -62,9 +62,9 @@ assert.equal(c_ucs.toString('latin1'), ucs2_control); // now let's test BASE64 and HEX ecoding/decoding -var RADIOS = 2; -var PRE_HALF_APEX = Math.ceil(EXTERN_APEX / 2) - RADIOS; -var PRE_3OF4_APEX = Math.ceil((EXTERN_APEX / 4) * 3) - RADIOS; +const RADIOS = 2; +const PRE_HALF_APEX = Math.ceil(EXTERN_APEX / 2) - RADIOS; +const PRE_3OF4_APEX = Math.ceil((EXTERN_APEX / 4) * 3) - RADIOS; { for (let j = 0; j < RADIOS * 2; j += 1) { diff --git a/test/parallel/test-sync-io-option.js b/test/parallel/test-sync-io-option.js index fec61ef62f370e..6166bffc0bd68c 100644 --- a/test/parallel/test-sync-io-option.js +++ b/test/parallel/test-sync-io-option.js @@ -12,9 +12,9 @@ if (process.argv[2] === 'child') { } else { (function runTest(flags) { - var execArgv = [flags.pop()]; - var args = [__filename, 'child']; - var cntr = 0; + const execArgv = [flags.pop()]; + let args = [__filename, 'child']; + let cntr = 0; args = execArgv.concat(args); if (!args[0]) args.shift(); execFile(process.execPath, args, function(err, stdout, stderr) { diff --git a/test/parallel/test-tcp-wrap-connect.js b/test/parallel/test-tcp-wrap-connect.js index 92114bad39dbcd..77f9814db2ebe5 100644 --- a/test/parallel/test-tcp-wrap-connect.js +++ b/test/parallel/test-tcp-wrap-connect.js @@ -1,15 +1,15 @@ 'use strict'; require('../common'); const assert = require('assert'); -var TCP = process.binding('tcp_wrap').TCP; -var TCPConnectWrap = process.binding('tcp_wrap').TCPConnectWrap; -var ShutdownWrap = process.binding('stream_wrap').ShutdownWrap; +const TCP = process.binding('tcp_wrap').TCP; +const TCPConnectWrap = process.binding('tcp_wrap').TCPConnectWrap; +const ShutdownWrap = process.binding('stream_wrap').ShutdownWrap; function makeConnection() { - var client = new TCP(); + const client = new TCP(); - var req = new TCPConnectWrap(); - var err = client.connect(req, '127.0.0.1', this.address().port); + const req = new TCPConnectWrap(); + const err = client.connect(req, '127.0.0.1', this.address().port); assert.strictEqual(err, 0); req.oncomplete = function(status, client_, req_, readable, writable) { @@ -19,8 +19,8 @@ function makeConnection() { assert.strictEqual(true, readable); assert.strictEqual(true, writable); - var shutdownReq = new ShutdownWrap(); - var err = client.shutdown(shutdownReq); + const shutdownReq = new ShutdownWrap(); + const err = client.shutdown(shutdownReq); assert.strictEqual(err, 0); shutdownReq.oncomplete = function(status, client_, req_) { @@ -35,9 +35,9 @@ function makeConnection() { ///// -var connectCount = 0; -var endCount = 0; -var shutdownCount = 0; +let connectCount = 0; +let endCount = 0; +let shutdownCount = 0; const server = require('net').Server(function(s) { connectCount++; diff --git a/test/parallel/test-tcp-wrap.js b/test/parallel/test-tcp-wrap.js index 0d023ebf8d6d0d..6b9dbd90a4c113 100644 --- a/test/parallel/test-tcp-wrap.js +++ b/test/parallel/test-tcp-wrap.js @@ -2,17 +2,17 @@ require('../common'); const assert = require('assert'); -var TCP = process.binding('tcp_wrap').TCP; -var uv = process.binding('uv'); +const TCP = process.binding('tcp_wrap').TCP; +const uv = process.binding('uv'); -var handle = new TCP(); +const handle = new TCP(); // Should be able to bind to the port -var err = handle.bind('0.0.0.0', 0); +let err = handle.bind('0.0.0.0', 0); assert.equal(err, 0); // Should not be able to bind to the same port again -var out = {}; +const out = {}; handle.getsockname(out); err = handle.bind('0.0.0.0', out.port); assert.equal(err, uv.UV_EINVAL); diff --git a/test/parallel/test-timers-active.js b/test/parallel/test-timers-active.js index 8677e43971ac89..62707cf18c0ab7 100644 --- a/test/parallel/test-timers-active.js +++ b/test/parallel/test-timers-active.js @@ -4,7 +4,7 @@ const assert = require('assert'); const active = require('timers').active; // active() should create timers for these -var legitTimers = [ +const legitTimers = [ { _idleTimeout: 0 }, { _idleTimeout: 1 } ]; @@ -21,7 +21,7 @@ legitTimers.forEach(function(legit) { // active() should not create a timer for these -var bogusTimers = [ +const bogusTimers = [ { _idleTimeout: -1 }, { _idleTimeout: undefined }, ]; diff --git a/test/parallel/test-timers-clearImmediate.js b/test/parallel/test-timers-clearImmediate.js index ab65b7bf1ce05d..c49fd7622f4ab6 100644 --- a/test/parallel/test-timers-clearImmediate.js +++ b/test/parallel/test-timers-clearImmediate.js @@ -3,14 +3,14 @@ require('../common'); const assert = require('assert'); const N = 3; -var count = 0; +let count = 0; function next() { const immediate = setImmediate(function() { clearImmediate(immediate); ++count; }); } -for (var i = 0; i < N; ++i) +for (let i = 0; i < N; ++i) next(); process.on('exit', () => { diff --git a/test/parallel/test-timers-immediate-queue.js b/test/parallel/test-timers-immediate-queue.js index f53f18140f46df..103cd964511a53 100644 --- a/test/parallel/test-timers-immediate-queue.js +++ b/test/parallel/test-timers-immediate-queue.js @@ -24,7 +24,7 @@ function run() { setImmediate(run); } -for (var i = 0; i < QUEUE; i++) +for (let i = 0; i < QUEUE; i++) setImmediate(run); process.on('exit', function() { diff --git a/test/parallel/test-timers-immediate.js b/test/parallel/test-timers-immediate.js index 9632022917f152..4afc642a334101 100644 --- a/test/parallel/test-timers-immediate.js +++ b/test/parallel/test-timers-immediate.js @@ -2,7 +2,6 @@ const common = require('../common'); const assert = require('assert'); -let immediateB; let immediateC; let immediateD; @@ -13,7 +12,7 @@ setImmediate(common.mustCall(function() { clearImmediate(immediateB); })); -immediateB = setImmediate(function() { +const immediateB = setImmediate(function() { common.fail('this immediate should not run'); }); diff --git a/test/parallel/test-timers-nested.js b/test/parallel/test-timers-nested.js index d5d272ed2eae11..0ff228abf50311 100644 --- a/test/parallel/test-timers-nested.js +++ b/test/parallel/test-timers-nested.js @@ -11,7 +11,7 @@ const assert = require('assert'); const scenarios = [0, 100]; scenarios.forEach(function(delay) { - var nestedCalled = false; + let nestedCalled = false; setTimeout(function A() { // Create the nested timer with the same delay as the outer timer so that it diff --git a/test/parallel/test-timers-socket-timeout-removes-other-socket-unref-timer.js b/test/parallel/test-timers-socket-timeout-removes-other-socket-unref-timer.js index 8670c3c2b6e8f3..f42144360b6941 100644 --- a/test/parallel/test-timers-socket-timeout-removes-other-socket-unref-timer.js +++ b/test/parallel/test-timers-socket-timeout-removes-other-socket-unref-timer.js @@ -32,7 +32,7 @@ const server = net.createServer(function onClient(client) { }); server.listen(0, common.localhostIPv4, function() { - var nbClientsEnded = 0; + let nbClientsEnded = 0; function addEndedClient(client) { ++nbClientsEnded; diff --git a/test/parallel/test-timers-unref-active.js b/test/parallel/test-timers-unref-active.js index 69027277ea0ff2..8b1c89673bc35f 100644 --- a/test/parallel/test-timers-unref-active.js +++ b/test/parallel/test-timers-unref-active.js @@ -19,8 +19,8 @@ require('../common'); const timers = require('timers'); const assert = require('assert'); -var someObject = {}; -var nbTimeouts = 0; +const someObject = {}; +let nbTimeouts = 0; /* * libuv 0.10.x uses GetTickCount on Windows to implement timers, which uses diff --git a/test/parallel/test-timers-unref-call.js b/test/parallel/test-timers-unref-call.js index edd5865e8f610b..5384441838763a 100644 --- a/test/parallel/test-timers-unref-call.js +++ b/test/parallel/test-timers-unref-call.js @@ -1,12 +1,12 @@ 'use strict'; require('../common'); -var Timer = process.binding('timer_wrap').Timer; +const Timer = process.binding('timer_wrap').Timer; Timer.now = function() { return ++Timer.now.ticks; }; Timer.now.ticks = 0; -var t = setInterval(function() {}, 1); -var o = { _idleStart: 0, _idleTimeout: 1 }; +const t = setInterval(function() {}, 1); +const o = { _idleStart: 0, _idleTimeout: 1 }; t.unref.call(o); setTimeout(clearInterval.bind(null, t), 2); diff --git a/test/parallel/test-timers-unref-leak.js b/test/parallel/test-timers-unref-leak.js index 6a1f275ae5dda3..d970910b24abe6 100644 --- a/test/parallel/test-timers-unref-leak.js +++ b/test/parallel/test-timers-unref-leak.js @@ -2,16 +2,16 @@ require('../common'); const assert = require('assert'); -var called = 0; -var closed = 0; +let called = 0; +let closed = 0; -var timeout = setTimeout(function() { +const timeout = setTimeout(function() { called++; }, 10); timeout.unref(); // Wrap `close` method to check if the handle was closed -var close = timeout._handle.close; +const close = timeout._handle.close; timeout._handle.close = function() { closed++; return close.apply(this, arguments); diff --git a/test/parallel/test-timers-unref-remove-other-unref-timers-only-one-fires.js b/test/parallel/test-timers-unref-remove-other-unref-timers-only-one-fires.js index 03c6cf7fd333a7..ce63ad8d2968e7 100644 --- a/test/parallel/test-timers-unref-remove-other-unref-timers-only-one-fires.js +++ b/test/parallel/test-timers-unref-remove-other-unref-timers-only-one-fires.js @@ -14,7 +14,7 @@ require('../common'); const timers = require('timers'); const assert = require('assert'); -var nbTimersFired = 0; +let nbTimersFired = 0; const foo = { _onTimeout: function() { diff --git a/test/parallel/test-timers-unref.js b/test/parallel/test-timers-unref.js index c47931b965fd09..2bde08f914d790 100644 --- a/test/parallel/test-timers-unref.js +++ b/test/parallel/test-timers-unref.js @@ -9,8 +9,8 @@ let unref_timer = false; let unref_callbacks = 0; let checks = 0; -var LONG_TIME = 10 * 1000; -var SHORT_TIME = 100; +const LONG_TIME = 10 * 1000; +const SHORT_TIME = 100; assert.doesNotThrow(function() { setTimeout(function() {}, 10).unref().ref().unref(); diff --git a/test/parallel/test-timers-unrefd-interval-still-fires.js b/test/parallel/test-timers-unrefd-interval-still-fires.js index 39bb2cdb138205..bf16013f004965 100644 --- a/test/parallel/test-timers-unrefd-interval-still-fires.js +++ b/test/parallel/test-timers-unrefd-interval-still-fires.js @@ -6,7 +6,7 @@ const common = require('../common'); const TEST_DURATION = common.platformTimeout(1000); const N = 3; -var nbIntervalFired = 0; +let nbIntervalFired = 0; const keepOpen = setTimeout(() => { console.error('[FAIL] Interval fired %d/%d times.', nbIntervalFired, N); diff --git a/test/parallel/test-timers-unrefed-in-beforeexit.js b/test/parallel/test-timers-unrefed-in-beforeexit.js index 0ac3311816fb4d..530d97674d8bf7 100644 --- a/test/parallel/test-timers-unrefed-in-beforeexit.js +++ b/test/parallel/test-timers-unrefed-in-beforeexit.js @@ -3,7 +3,7 @@ require('../common'); const assert = require('assert'); -var once = 0; +let once = 0; process.on('beforeExit', () => { if (once > 1) diff --git a/test/parallel/test-timers.js b/test/parallel/test-timers.js index 38d8fd86b17cce..33f1706e3d399a 100644 --- a/test/parallel/test-timers.js +++ b/test/parallel/test-timers.js @@ -2,7 +2,7 @@ require('../common'); const assert = require('assert'); -var inputs = [ +const inputs = [ undefined, null, true, @@ -29,15 +29,15 @@ var inputs = [ 12345678901234 // ditto ]; -var timeouts = []; -var intervals = []; +const timeouts = []; +const intervals = []; inputs.forEach(function(value, index) { setTimeout(function() { timeouts[index] = true; }, value); - var handle = setInterval(function() { + const handle = setInterval(function() { clearInterval(handle); // disarm timer or we'll never finish intervals[index] = true; }, value); diff --git a/test/parallel/test-tls-alert.js b/test/parallel/test-tls-alert.js index 59cd355f35a67a..a8c6016f6218b7 100644 --- a/test/parallel/test-tls-alert.js +++ b/test/parallel/test-tls-alert.js @@ -16,7 +16,7 @@ const tls = require('tls'); const fs = require('fs'); const spawn = require('child_process').spawn; -var success = false; +let success = false; function filenamePEM(n) { return require('path').join(common.fixturesDir, 'keys', n + '.pem'); @@ -26,20 +26,20 @@ function loadPEM(n) { return fs.readFileSync(filenamePEM(n)); } -var server = tls.Server({ +const server = tls.Server({ secureProtocol: 'TLSv1_2_server_method', key: loadPEM('agent2-key'), cert: loadPEM('agent2-cert') }, null).listen(0, function() { - var args = ['s_client', '-quiet', '-tls1_1', - '-connect', `127.0.0.1:${this.address().port}`]; + const args = ['s_client', '-quiet', '-tls1_1', + '-connect', `127.0.0.1:${this.address().port}`]; // for the performance and stability issue in s_client on Windows if (common.isWindows) args.push('-no_rand_screen'); - var client = spawn(common.opensslCli, args); - var out = ''; + const client = spawn(common.opensslCli, args); + let out = ''; client.stderr.setEncoding('utf8'); client.stderr.on('data', function(d) { out += d; diff --git a/test/parallel/test-tls-alpn-server-client.js b/test/parallel/test-tls-alpn-server-client.js index 0da2086f4de506..ca5785b09ac05a 100644 --- a/test/parallel/test-tls-alpn-server-client.js +++ b/test/parallel/test-tls-alpn-server-client.js @@ -24,7 +24,7 @@ function loadPEM(n) { return fs.readFileSync(filenamePEM(n)); } -var serverIP = common.localhostIPv4; +const serverIP = common.localhostIPv4; function checkResults(result, expected) { assert.strictEqual(result.server.ALPN, expected.server.ALPN); @@ -36,9 +36,9 @@ function checkResults(result, expected) { function runTest(clientsOptions, serverOptions, cb) { serverOptions.key = loadPEM('agent2-key'); serverOptions.cert = loadPEM('agent2-cert'); - var results = []; - var index = 0; - var server = tls.createServer(serverOptions, function(c) { + const results = []; + let index = 0; + const server = tls.createServer(serverOptions, function(c) { results[index].server = {ALPN: c.alpnProtocol, NPN: c.npnProtocol}; }); @@ -47,13 +47,13 @@ function runTest(clientsOptions, serverOptions, cb) { }); function connectClient(options) { - var opt = options.shift(); + const opt = options.shift(); opt.port = server.address().port; opt.host = serverIP; opt.rejectUnauthorized = false; results[index] = {}; - var client = tls.connect(opt, function() { + const client = tls.connect(opt, function() { results[index].client = {ALPN: client.alpnProtocol, NPN: client.npnProtocol}; client.destroy(); @@ -71,12 +71,12 @@ function runTest(clientsOptions, serverOptions, cb) { // Server: ALPN/NPN, Client: ALPN/NPN function Test1() { - var serverOptions = { + const serverOptions = { ALPNProtocols: ['a', 'b', 'c'], NPNProtocols: ['a', 'b', 'c'] }; - var clientsOptions = [{ + const clientsOptions = [{ ALPNProtocols: ['a', 'b', 'c'], NPNProtocols: ['a', 'b', 'c'] }, { @@ -107,12 +107,12 @@ function Test1() { // Server: ALPN/NPN, Client: ALPN function Test2() { - var serverOptions = { + const serverOptions = { ALPNProtocols: ['a', 'b', 'c'], NPNProtocols: ['a', 'b', 'c'] }; - var clientsOptions = [{ + const clientsOptions = [{ ALPNProtocols: ['a', 'b', 'c'] }, { ALPNProtocols: ['c', 'b', 'e'] @@ -140,12 +140,12 @@ function Test2() { // Server: ALPN/NPN, Client: NPN function Test3() { - var serverOptions = { + const serverOptions = { ALPNProtocols: ['a', 'b', 'c'], NPNProtocols: ['a', 'b', 'c'] }; - var clientsOptions = [{ + const clientsOptions = [{ NPNProtocols: ['a', 'b', 'c'] }, { NPPNProtocols: ['c', 'b', 'e'] @@ -173,12 +173,12 @@ function Test3() { // Server: ALPN/NPN, Client: Nothing function Test4() { - var serverOptions = { + const serverOptions = { ALPNProtocols: ['a', 'b', 'c'], NPNProtocols: ['a', 'b', 'c'] }; - var clientsOptions = [{}, {}, {}]; + const clientsOptions = [{}, {}, {}]; runTest(clientsOptions, serverOptions, function(results) { // nothing is selected by ALPN @@ -200,11 +200,11 @@ function Test4() { // Server: ALPN, Client: ALPN/NPN function Test5() { - var serverOptions = { + const serverOptions = { ALPNProtocols: ['a', 'b', 'c'] }; - var clientsOptions = [{ + const clientsOptions = [{ ALPNProtocols: ['a', 'b', 'c'], NPNProtocols: ['a', 'b', 'c'] }, { @@ -233,11 +233,11 @@ function Test5() { // Server: ALPN, Client: ALPN function Test6() { - var serverOptions = { + const serverOptions = { ALPNProtocols: ['a', 'b', 'c'] }; - var clientsOptions = [{ + const clientsOptions = [{ ALPNProtocols: ['a', 'b', 'c'] }, { ALPNProtocols: ['c', 'b', 'e'] @@ -262,11 +262,11 @@ function Test6() { // Server: ALPN, Client: NPN function Test7() { - var serverOptions = { + const serverOptions = { ALPNProtocols: ['a', 'b', 'c'] }; - var clientsOptions = [{ + const clientsOptions = [{ NPNProtocols: ['a', 'b', 'c'] }, { NPNProtocols: ['c', 'b', 'e'] @@ -292,11 +292,11 @@ function Test7() { // Server: ALPN, Client: Nothing function Test8() { - var serverOptions = { + const serverOptions = { ALPNProtocols: ['a', 'b', 'c'] }; - var clientsOptions = [{}, {}, {}]; + const clientsOptions = [{}, {}, {}]; runTest(clientsOptions, serverOptions, function(results) { // nothing is selected by ALPN @@ -316,11 +316,11 @@ function Test8() { // Server: NPN, Client: ALPN/NPN function Test9() { - var serverOptions = { + const serverOptions = { NPNProtocols: ['a', 'b', 'c'] }; - var clientsOptions = [{ + const clientsOptions = [{ ALPNrotocols: ['a', 'b', 'c'], NPNProtocols: ['a', 'b', 'c'] }, { @@ -349,11 +349,11 @@ function Test9() { // Server: NPN, Client: ALPN function Test10() { - var serverOptions = { + const serverOptions = { NPNProtocols: ['a', 'b', 'c'] }; - var clientsOptions = [{ + const clientsOptions = [{ ALPNProtocols: ['a', 'b', 'c'] }, { ALPNProtocols: ['c', 'b', 'e'] @@ -378,11 +378,11 @@ function Test10() { // Server: NPN, Client: NPN function Test11() { - var serverOptions = { + const serverOptions = { NPNProtocols: ['a', 'b', 'c'] }; - var clientsOptions = [{ + const clientsOptions = [{ NPNProtocols: ['a', 'b', 'c'] }, { NPNProtocols: ['c', 'b', 'e'] @@ -408,11 +408,11 @@ function Test11() { // Server: NPN, Client: Nothing function Test12() { - var serverOptions = { + const serverOptions = { NPNProtocols: ['a', 'b', 'c'] }; - var clientsOptions = [{}, {}, {}]; + const clientsOptions = [{}, {}, {}]; runTest(clientsOptions, serverOptions, function(results) { // nothing is selected @@ -432,9 +432,9 @@ function Test12() { // Server: Nothing, Client: ALPN/NPN function Test13() { - var serverOptions = {}; + const serverOptions = {}; - var clientsOptions = [{ + const clientsOptions = [{ ALPNrotocols: ['a', 'b', 'c'], NPNProtocols: ['a', 'b', 'c'] }, { @@ -463,9 +463,9 @@ function Test13() { // Server: Nothing, Client: ALPN function Test14() { - var serverOptions = {}; + const serverOptions = {}; - var clientsOptions = [{ + const clientsOptions = [{ ALPNrotocols: ['a', 'b', 'c'] }, { ALPNProtocols: ['c', 'b', 'e'] @@ -491,9 +491,9 @@ function Test14() { // Server: Nothing, Client: NPN function Test15() { - var serverOptions = {}; + const serverOptions = {}; - var clientsOptions = [{ + const clientsOptions = [{ NPNProtocols: ['a', 'b', 'c'] }, { NPNProtocols: ['c', 'b', 'e'] @@ -519,9 +519,9 @@ function Test15() { // Server: Nothing, Client: Nothing function Test16() { - var serverOptions = {}; + const serverOptions = {}; - var clientsOptions = [{}, {}, {}]; + const clientsOptions = [{}, {}, {}]; runTest(clientsOptions, serverOptions, function(results) { // nothing is selected diff --git a/test/parallel/test-tls-async-cb-after-socket-end.js b/test/parallel/test-tls-async-cb-after-socket-end.js index dc03e74c652ab3..be499b84503472 100644 --- a/test/parallel/test-tls-async-cb-after-socket-end.js +++ b/test/parallel/test-tls-async-cb-after-socket-end.js @@ -12,17 +12,17 @@ const SSL_OP_NO_TICKET = require('crypto').constants.SSL_OP_NO_TICKET; const tls = require('tls'); -var options = { +const options = { secureOptions: SSL_OP_NO_TICKET, key: fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')), cert: fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')) }; -var server = tls.createServer(options, function(c) { +const server = tls.createServer(options, function(c) { }); -var sessionCb = null; -var client = null; +let sessionCb = null; +let client = null; server.on('newSession', function(key, session, done) { done(); @@ -35,18 +35,18 @@ server.on('resumeSession', function(id, cb) { }); server.listen(0, function() { - var clientOpts = { + const clientOpts = { port: this.address().port, rejectUnauthorized: false, session: false }; - var s1 = tls.connect(clientOpts, function() { + const s1 = tls.connect(clientOpts, function() { clientOpts.session = s1.getSession(); console.log('1st secure'); s1.destroy(); - var s2 = tls.connect(clientOpts, function(s) { + const s2 = tls.connect(clientOpts, function(s) { console.log('2nd secure'); s2.destroy(); diff --git a/test/parallel/test-tls-cert-regression.js b/test/parallel/test-tls-cert-regression.js index e74201bc2e35e5..ff5827bcf844ee 100644 --- a/test/parallel/test-tls-cert-regression.js +++ b/test/parallel/test-tls-cert-regression.js @@ -8,7 +8,7 @@ if (!common.hasCrypto) { const tls = require('tls'); -var cert = +const cert = `-----BEGIN CERTIFICATE----- MIIBfjCCASgCCQDmmNjAojbDQjANBgkqhkiG9w0BAQUFADBFMQswCQYDVQQGEwJB VTETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50ZXJuZXQgV2lkZ2l0 @@ -21,7 +21,7 @@ uvCyndyeB4d24FlfqEUlkfaWCZlNKRaV9YhLDiEg3BcIreFo4brtKQfZzTRs0GVm KHg= -----END CERTIFICATE-----`; -var key = +const key = `-----BEGIN RSA PRIVATE KEY----- MIIBPQIBAAJBAPKwlfMX6HGZIt1xm7fna72eWcOYfUfSxSugghvqYgJt2Oi3lH+w sU1O9FzRIVmpeIjDXhbpMjsa1HtzSiccPXsCAwEAAQJBAM4uU9aJE0OfdE1p/X+K @@ -33,7 +33,7 @@ AOaJnkQrmurlRdePX6LvN/LgGAQoxwovfjcOYNnZsIVY -----END RSA PRIVATE KEY-----`; function test(cert, key, cb) { - var server = tls.createServer({ + const server = tls.createServer({ cert: cert, key: key }).listen(0, function() { diff --git a/test/parallel/test-tls-cipher-list.js b/test/parallel/test-tls-cipher-list.js index 44ebd3d2f824ad..4acb30bc1c74bf 100644 --- a/test/parallel/test-tls-cipher-list.js +++ b/test/parallel/test-tls-cipher-list.js @@ -11,7 +11,7 @@ const spawn = require('child_process').spawn; const defaultCoreList = require('crypto').constants.defaultCoreCipherList; function doCheck(arg, check) { - var out = ''; + let out = ''; arg = arg.concat([ '-pe', 'require("crypto").constants.defaultCipherList' diff --git a/test/parallel/test-tls-client-abort.js b/test/parallel/test-tls-client-abort.js index f48d22c4fc48cd..21ee41e927873b 100644 --- a/test/parallel/test-tls-client-abort.js +++ b/test/parallel/test-tls-client-abort.js @@ -11,10 +11,10 @@ const tls = require('tls'); const fs = require('fs'); const path = require('path'); -var cert = fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')); -var key = fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')); +const cert = fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')); +const key = fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')); -var conn = tls.connect({cert: cert, key: key, port: common.PORT}, function() { +const conn = tls.connect({cert: cert, key: key, port: common.PORT}, function() { assert.ok(false); // callback should never be executed }); conn.on('error', function() { diff --git a/test/parallel/test-tls-client-abort2.js b/test/parallel/test-tls-client-abort2.js index dd224be8741abd..3247a2899acdfb 100644 --- a/test/parallel/test-tls-client-abort2.js +++ b/test/parallel/test-tls-client-abort2.js @@ -8,7 +8,7 @@ if (!common.hasCrypto) { } const tls = require('tls'); -var conn = tls.connect(common.PORT, common.fail); +const conn = tls.connect(common.PORT, common.fail); conn.on('error', common.mustCall(function() { assert.doesNotThrow(function() { conn.destroy(); diff --git a/test/parallel/test-tls-client-default-ciphers.js b/test/parallel/test-tls-client-default-ciphers.js index f8fdab1102a795..618178d4a497ad 100644 --- a/test/parallel/test-tls-client-default-ciphers.js +++ b/test/parallel/test-tls-client-default-ciphers.js @@ -11,7 +11,7 @@ const tls = require('tls'); function Done() {} function test1() { - var ciphers = ''; + let ciphers = ''; tls.createSecureContext = function(options) { ciphers = options.ciphers; diff --git a/test/parallel/test-tls-client-destroy-soon.js b/test/parallel/test-tls-client-destroy-soon.js index 3e792305147de2..016fcfa4da6a95 100644 --- a/test/parallel/test-tls-client-destroy-soon.js +++ b/test/parallel/test-tls-client-destroy-soon.js @@ -14,29 +14,29 @@ const tls = require('tls'); const fs = require('fs'); -var options = { +const options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem') }; -var big = Buffer.alloc(2 * 1024 * 1024, 'Y'); +const big = Buffer.alloc(2 * 1024 * 1024, 'Y'); // create server -var server = tls.createServer(options, common.mustCall(function(socket) { +const server = tls.createServer(options, common.mustCall(function(socket) { socket.end(big); socket.destroySoon(); })); // start listening server.listen(0, common.mustCall(function() { - var client = tls.connect({ + const client = tls.connect({ port: this.address().port, rejectUnauthorized: false }, common.mustCall(function() { - var bytesRead = 0; + let bytesRead = 0; client.on('readable', function() { - var d = client.read(); + const d = client.read(); if (d) bytesRead += d.length; }); diff --git a/test/parallel/test-tls-client-getephemeralkeyinfo.js b/test/parallel/test-tls-client-getephemeralkeyinfo.js index fb42991e149548..b49d7131c47cf9 100644 --- a/test/parallel/test-tls-client-getephemeralkeyinfo.js +++ b/test/parallel/test-tls-client-getephemeralkeyinfo.js @@ -12,27 +12,27 @@ const fs = require('fs'); const key = fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'); const cert = fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem'); -var ntests = 0; -var nsuccess = 0; +let ntests = 0; +let nsuccess = 0; function loadDHParam(n) { - var path = common.fixturesDir; + let path = common.fixturesDir; if (n !== 'error') path += '/keys'; return fs.readFileSync(path + '/dh' + n + '.pem'); } -var cipherlist = { +const cipherlist = { 'NOT_PFS': 'AES128-SHA256', 'DH': 'DHE-RSA-AES128-GCM-SHA256', 'ECDH': 'ECDHE-RSA-AES128-GCM-SHA256' }; function test(size, type, name, next) { - var cipher = type ? cipherlist[type] : cipherlist['NOT_PFS']; + const cipher = type ? cipherlist[type] : cipherlist['NOT_PFS']; if (name) tls.DEFAULT_ECDH_CURVE = name; - var options = { + const options = { key: key, cert: cert, ciphers: cipher @@ -40,7 +40,7 @@ function test(size, type, name, next) { if (type === 'DH') options.dhparam = loadDHParam(size); - var server = tls.createServer(options, function(conn) { + const server = tls.createServer(options, function(conn) { assert.strictEqual(conn.getEphemeralKeyInfo(), null); conn.end(); }); @@ -51,11 +51,11 @@ function test(size, type, name, next) { })); server.listen(0, '127.0.0.1', common.mustCall(function() { - var client = tls.connect({ + const client = tls.connect({ port: this.address().port, rejectUnauthorized: false }, function() { - var ekeyinfo = client.getEphemeralKeyInfo(); + const ekeyinfo = client.getEphemeralKeyInfo(); assert.strictEqual(ekeyinfo.type, type); assert.strictEqual(ekeyinfo.size, size); assert.strictEqual(ekeyinfo.name, name); diff --git a/test/parallel/test-tls-client-mindhsize.js b/test/parallel/test-tls-client-mindhsize.js index 55a32ad6c2a469..76e1034621f031 100644 --- a/test/parallel/test-tls-client-mindhsize.js +++ b/test/parallel/test-tls-client-mindhsize.js @@ -9,27 +9,27 @@ if (!common.hasCrypto) { const tls = require('tls'); const fs = require('fs'); -var key = fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'); -var cert = fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem'); +const key = fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'); +const cert = fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem'); -var nsuccess = 0; -var nerror = 0; +let nsuccess = 0; +let nerror = 0; function loadDHParam(n) { - var path = common.fixturesDir; + let path = common.fixturesDir; if (n !== 'error') path += '/keys'; return fs.readFileSync(path + '/dh' + n + '.pem'); } function test(size, err, next) { - var options = { + const options = { key: key, cert: cert, dhparam: loadDHParam(size), ciphers: 'DHE-RSA-AES128-GCM-SHA256' }; - var server = tls.createServer(options, function(conn) { + const server = tls.createServer(options, function(conn) { conn.end(); }); @@ -42,7 +42,7 @@ function test(size, err, next) { // client set minimum DH parameter size to 2048 bits so that // it fails when it make a connection to the tls server where // dhparams is 1024 bits - var client = tls.connect({ + const client = tls.connect({ minDHSize: 2048, port: this.address().port, rejectUnauthorized: false diff --git a/test/parallel/test-tls-client-resume.js b/test/parallel/test-tls-client-resume.js index 029f10d449fe31..96109d7656dd19 100644 --- a/test/parallel/test-tls-client-resume.js +++ b/test/parallel/test-tls-client-resume.js @@ -14,21 +14,21 @@ const tls = require('tls'); const fs = require('fs'); -var options = { +const options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem') }; // create server -var server = tls.Server(options, common.mustCall(function(socket) { +const server = tls.Server(options, common.mustCall(function(socket) { socket.end('Goodbye'); }, 2)); // start listening server.listen(0, function() { - var session1 = null; - var client1 = tls.connect({ + let session1 = null; + const client1 = tls.connect({ port: this.address().port, rejectUnauthorized: false }, function() { @@ -40,13 +40,13 @@ server.listen(0, function() { client1.on('close', function() { console.log('close1'); - var opts = { + const opts = { port: server.address().port, rejectUnauthorized: false, session: session1 }; - var client2 = tls.connect(opts, function() { + const client2 = tls.connect(opts, function() { console.log('connect2'); assert.ok(client2.isSessionReused(), 'Session *should* be reused.'); }); diff --git a/test/parallel/test-tls-client-verify.js b/test/parallel/test-tls-client-verify.js index a1fa35acf3c124..70d96ef1545ede 100644 --- a/test/parallel/test-tls-client-verify.js +++ b/test/parallel/test-tls-client-verify.js @@ -106,7 +106,7 @@ function testServers(index, servers, clientOptions, cb) { function runTest(testIndex) { - var tcase = testCases[testIndex]; + const tcase = testCases[testIndex]; if (!tcase) return; const clientOptions = { diff --git a/test/parallel/test-tls-close-error.js b/test/parallel/test-tls-close-error.js index 6b37d5c1cef00e..6172be813e97ce 100644 --- a/test/parallel/test-tls-close-error.js +++ b/test/parallel/test-tls-close-error.js @@ -11,12 +11,12 @@ const tls = require('tls'); const fs = require('fs'); -var server = tls.createServer({ +const server = tls.createServer({ key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }, function(c) { }).listen(0, common.mustCall(function() { - var c = tls.connect(this.address().port, function() { + const c = tls.connect(this.address().port, function() { assert(false, 'should not be called'); }); diff --git a/test/parallel/test-tls-close-notify.js b/test/parallel/test-tls-close-notify.js index 3dd2afbd6e5545..5d5bc1007749a7 100644 --- a/test/parallel/test-tls-close-notify.js +++ b/test/parallel/test-tls-close-notify.js @@ -9,7 +9,7 @@ const tls = require('tls'); const fs = require('fs'); -var server = tls.createServer({ +const server = tls.createServer({ key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }, function(c) { @@ -17,7 +17,7 @@ var server = tls.createServer({ if (c._handle.shutdownSSL() !== 1) c._handle.shutdownSSL(); }).listen(0, common.mustCall(function() { - var c = tls.connect(this.address().port, { + const c = tls.connect(this.address().port, { rejectUnauthorized: false }, common.mustCall(function() { // Ensure that we receive 'end' event anyway diff --git a/test/parallel/test-tls-connect-no-host.js b/test/parallel/test-tls-connect-no-host.js index 2b81698664c4ab..2e4bcfbc6d4787 100644 --- a/test/parallel/test-tls-connect-no-host.js +++ b/test/parallel/test-tls-connect-no-host.js @@ -11,8 +11,8 @@ const assert = require('assert'); const fs = require('fs'); const path = require('path'); -var cert = fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')); -var key = fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')); +const cert = fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')); +const key = fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')); // https://github.com/nodejs/node/issues/1489 // tls.connect(options) with no options.host should accept a cert with @@ -21,7 +21,7 @@ tls.createServer({ key: key, cert: cert }).listen(0, function() { - var socket = tls.connect({ + const socket = tls.connect({ port: this.address().port, ca: cert, // No host set here. 'localhost' is the default, diff --git a/test/parallel/test-tls-connect-pipe.js b/test/parallel/test-tls-connect-pipe.js index 67a53c4ebf78a4..de60ae084624cf 100644 --- a/test/parallel/test-tls-connect-pipe.js +++ b/test/parallel/test-tls-connect-pipe.js @@ -9,19 +9,19 @@ const tls = require('tls'); const fs = require('fs'); -var options = { +const options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }; common.refreshTmpDir(); -var server = tls.Server(options, common.mustCall(function(socket) { +const server = tls.Server(options, common.mustCall(function(socket) { server.close(); })); server.listen(common.PIPE, common.mustCall(function() { - var options = { rejectUnauthorized: false }; - var client = tls.connect(common.PIPE, options, common.mustCall(function() { + const options = { rejectUnauthorized: false }; + const client = tls.connect(common.PIPE, options, common.mustCall(function() { client.end(); })); })); diff --git a/test/parallel/test-tls-connect-stream-writes.js b/test/parallel/test-tls-connect-stream-writes.js index 7070f63f497df6..2f4eebf22978a5 100644 --- a/test/parallel/test-tls-connect-stream-writes.js +++ b/test/parallel/test-tls-connect-stream-writes.js @@ -11,34 +11,33 @@ const tls = require('tls'); const stream = require('stream'); const net = require('net'); -var server; -var cert_dir = common.fixturesDir; -var options = { key: fs.readFileSync(cert_dir + '/test_key.pem'), - cert: fs.readFileSync(cert_dir + '/test_cert.pem'), - ca: [ fs.readFileSync(cert_dir + '/test_ca.pem') ], - ciphers: 'AES256-GCM-SHA384' }; -var content = 'hello world'; -var recv_bufs = []; -var send_data = ''; -server = tls.createServer(options, function(s) { +const cert_dir = common.fixturesDir; +const options = { key: fs.readFileSync(cert_dir + '/test_key.pem'), + cert: fs.readFileSync(cert_dir + '/test_cert.pem'), + ca: [ fs.readFileSync(cert_dir + '/test_ca.pem') ], + ciphers: 'AES256-GCM-SHA384' }; +const content = 'hello world'; +const recv_bufs = []; +let send_data = ''; +const server = tls.createServer(options, function(s) { s.on('data', function(c) { recv_bufs.push(c); }); }); server.listen(0, function() { - var raw = net.connect(this.address().port); + const raw = net.connect(this.address().port); - var pending = false; + let pending = false; raw.on('readable', function() { if (pending) p._read(); }); - var p = new stream.Duplex({ + const p = new stream.Duplex({ read: function read() { pending = false; - var chunk = raw.read(); + const chunk = raw.read(); if (chunk) { this.push(chunk); } else { @@ -50,11 +49,11 @@ server.listen(0, function() { } }); - var socket = tls.connect({ + const socket = tls.connect({ socket: p, rejectUnauthorized: false }, function() { - for (var i = 0; i < 50; ++i) { + for (let i = 0; i < 50; ++i) { socket.write(content); send_data += content; } @@ -64,6 +63,6 @@ server.listen(0, function() { }); process.on('exit', function() { - var recv_data = (Buffer.concat(recv_bufs)).toString(); + const recv_data = (Buffer.concat(recv_bufs)).toString(); assert.strictEqual(send_data, recv_data); }); diff --git a/test/parallel/test-tls-delayed-attach-error.js b/test/parallel/test-tls-delayed-attach-error.js index e7cfd4fa6ab557..47be3f201b463e 100644 --- a/test/parallel/test-tls-delayed-attach-error.js +++ b/test/parallel/test-tls-delayed-attach-error.js @@ -9,16 +9,16 @@ const tls = require('tls'); const fs = require('fs'); const net = require('net'); -var bonkers = Buffer.alloc(1024, 42); +const bonkers = Buffer.alloc(1024, 42); -var options = { +const options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }; -var server = net.createServer(common.mustCall(function(c) { +const server = net.createServer(common.mustCall(function(c) { setTimeout(common.mustCall(function() { - var s = new tls.TLSSocket(c, { + const s = new tls.TLSSocket(c, { isServer: true, secureContext: tls.createSecureContext(options) }); @@ -31,7 +31,7 @@ var server = net.createServer(common.mustCall(function(c) { }); }), 200); })).listen(0, function() { - var c = net.connect({port: this.address().port}, function() { + const c = net.connect({port: this.address().port}, function() { c.write(bonkers); }); }); diff --git a/test/parallel/test-tls-delayed-attach.js b/test/parallel/test-tls-delayed-attach.js index 867fc5edb88b03..d757ca756c3a09 100644 --- a/test/parallel/test-tls-delayed-attach.js +++ b/test/parallel/test-tls-delayed-attach.js @@ -11,17 +11,17 @@ const tls = require('tls'); const fs = require('fs'); const net = require('net'); -var sent = 'hello world'; -var received = ''; +const sent = 'hello world'; +let received = ''; -var options = { +const options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }; -var server = net.createServer(function(c) { +const server = net.createServer(function(c) { setTimeout(function() { - var s = new tls.TLSSocket(c, { + const s = new tls.TLSSocket(c, { isServer: true, secureContext: tls.createSecureContext(options) }); @@ -36,7 +36,7 @@ var server = net.createServer(function(c) { }); }, 200); }).listen(0, function() { - var c = tls.connect(this.address().port, { + const c = tls.connect(this.address().port, { rejectUnauthorized: false }, function() { c.end(sent); diff --git a/test/parallel/test-tls-dhe.js b/test/parallel/test-tls-dhe.js index 6340833765cd41..4bc81af6e1f8a2 100644 --- a/test/parallel/test-tls-dhe.js +++ b/test/parallel/test-tls-dhe.js @@ -10,28 +10,28 @@ const tls = require('tls'); const spawn = require('child_process').spawn; const fs = require('fs'); -var key = fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'); -var cert = fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem'); -var nsuccess = 0; -var ntests = 0; -var ciphers = 'DHE-RSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256'; +const key = fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'); +const cert = fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem'); +let nsuccess = 0; +let ntests = 0; +const ciphers = 'DHE-RSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256'; function loadDHParam(n) { - var path = common.fixturesDir; + let path = common.fixturesDir; if (n !== 'error') path += '/keys'; return fs.readFileSync(path + '/dh' + n + '.pem'); } function test(keylen, expectedCipher, cb) { - var options = { + const options = { key: key, cert: cert, ciphers: ciphers, dhparam: loadDHParam(keylen) }; - var server = tls.createServer(options, function(conn) { + const server = tls.createServer(options, function(conn) { conn.end(); }); @@ -41,15 +41,15 @@ function test(keylen, expectedCipher, cb) { }); server.listen(0, '127.0.0.1', function() { - var args = ['s_client', '-connect', `127.0.0.1:${this.address().port}`, - '-cipher', ciphers]; + const args = ['s_client', '-connect', `127.0.0.1:${this.address().port}`, + '-cipher', ciphers]; // for the performance and stability issue in s_client on Windows if (common.isWindows) args.push('-no_rand_screen'); - var client = spawn(common.opensslCli, args); - var out = ''; + const client = spawn(common.opensslCli, args); + let out = ''; client.stdout.setEncoding('utf8'); client.stdout.on('data', function(d) { out += d; @@ -57,7 +57,7 @@ function test(keylen, expectedCipher, cb) { client.stdout.on('end', function() { // DHE key length can be checked -brief option in s_client but it // is only supported in openssl 1.0.2 so we cannot check it. - var reg = new RegExp('Cipher : ' + expectedCipher); + const reg = new RegExp('Cipher : ' + expectedCipher); if (reg.test(out)) { nsuccess++; server.close(); diff --git a/test/parallel/test-tls-ecdh-disable.js b/test/parallel/test-tls-ecdh-disable.js index df51c5d0855d65..a0555e87781f59 100644 --- a/test/parallel/test-tls-ecdh-disable.js +++ b/test/parallel/test-tls-ecdh-disable.js @@ -11,17 +11,17 @@ const tls = require('tls'); const exec = require('child_process').exec; const fs = require('fs'); -var options = { +const options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem'), ciphers: 'ECDHE-RSA-RC4-SHA', ecdhCurve: false }; -var server = tls.createServer(options, common.fail); +const server = tls.createServer(options, common.fail); server.listen(0, '127.0.0.1', common.mustCall(function() { - var cmd = '"' + common.opensslCli + '" s_client -cipher ' + options.ciphers + + let cmd = '"' + common.opensslCli + '" s_client -cipher ' + options.ciphers + ` -connect 127.0.0.1:${this.address().port}`; // for the performance and stability issue in s_client on Windows diff --git a/test/parallel/test-tls-econnreset.js b/test/parallel/test-tls-econnreset.js index 51f178198f1a0a..c0df9948f489ea 100644 --- a/test/parallel/test-tls-econnreset.js +++ b/test/parallel/test-tls-econnreset.js @@ -8,7 +8,7 @@ if (!common.hasCrypto) { } const tls = require('tls'); -var cacert = +const cacert = `-----BEGIN CERTIFICATE----- MIIBxTCCAX8CAnXnMA0GCSqGSIb3DQEBBQUAMH0xCzAJBgNVBAYTAlVTMQswCQYD VQQIEwJDQTEWMBQGA1UEBxMNU2FuIEZyYW5jaXNjbzEZMBcGA1UEChMQU3Ryb25n @@ -22,7 +22,7 @@ AVkCAwEAATANBgkqhkiG9w0BAQUFAAMxALA1uS4CqQXRSAyYTfio5oyLGz71a+NM +0AFLBwh5AQjhGd0FcenU4OfHxyDEOJT/Q== -----END CERTIFICATE-----`; -var cert = +const cert = `-----BEGIN CERTIFICATE----- MIIBfDCCATYCAgQaMA0GCSqGSIb3DQEBBQUAMH0xCzAJBgNVBAYTAlVTMQswCQYD VQQIEwJDQTEWMBQGA1UEBxMNU2FuIEZyYW5jaXNjbzEZMBcGA1UEChMQU3Ryb25n @@ -34,7 +34,7 @@ AQABoxkwFzAVBgNVHREEDjAMhwQAAAAAhwR/AAABMA0GCSqGSIb3DQEBBQUAAzEA cGpYrhkrb7mIh9DNhV0qp7pGjqBzlHqB7KQXw2luLDp//6dyHBMexDCQznkhZKRU -----END CERTIFICATE-----`; -var key = +const key = `-----BEGIN RSA PRIVATE KEY----- MIH0AgEAAjEAx+QjQtZTXmk9TAhA0ydFWGE6JuLRNCYBq7wUG2DAR8YrTVal8ZRo mvVrjUrxSrvHAgMBAAECMBCGccvSwC2r8Z9Zh1JtirQVxaL1WWpAQfmVwLe0bAgg @@ -44,18 +44,18 @@ pQIZAMMwxuS3XiO7two2sQF6W+JTYyX1DPCwAQIZAOYg1TvEGT38k8e8jygv8E8w YqrWTeQFNQ== -----END RSA PRIVATE KEY-----`; -var ca = [ cert, cacert ]; +const ca = [ cert, cacert ]; -var clientError = null; -var connectError = null; +let clientError = null; +let connectError = null; -var server = tls.createServer({ ca: ca, cert: cert, key: key }, function(conn) { +const server = tls.createServer({ ca: ca, cert: cert, key: key }, (conn) => { throw 'unreachable'; }).on('tlsClientError', function(err, conn) { assert(!clientError && conn); clientError = err; }).listen(0, function() { - var options = { + const options = { ciphers: 'AES128-GCM-SHA256', port: this.address().port, ca: ca diff --git a/test/parallel/test-tls-env-bad-extra-ca.js b/test/parallel/test-tls-env-bad-extra-ca.js index 1862366e013af0..cb6c4ba489fcd6 100644 --- a/test/parallel/test-tls-env-bad-extra-ca.js +++ b/test/parallel/test-tls-env-bad-extra-ca.js @@ -22,11 +22,11 @@ const env = { NODE_EXTRA_CA_CERTS: common.fixturesDir + '/no-such-file-exists', }; -var opts = { +const opts = { env: env, silent: true, }; -var stderr = ''; +let stderr = ''; fork(__filename, opts) .on('exit', common.mustCall(function(status) { diff --git a/test/parallel/test-tls-fast-writing.js b/test/parallel/test-tls-fast-writing.js index 33665536ba5bd0..b2d6fe6eee88a3 100644 --- a/test/parallel/test-tls-fast-writing.js +++ b/test/parallel/test-tls-fast-writing.js @@ -10,14 +10,14 @@ const tls = require('tls'); const fs = require('fs'); -var dir = common.fixturesDir; -var options = { key: fs.readFileSync(dir + '/test_key.pem'), - cert: fs.readFileSync(dir + '/test_cert.pem'), - ca: [ fs.readFileSync(dir + '/test_ca.pem') ] }; +const dir = common.fixturesDir; +const options = { key: fs.readFileSync(dir + '/test_key.pem'), + cert: fs.readFileSync(dir + '/test_cert.pem'), + ca: [ fs.readFileSync(dir + '/test_ca.pem') ] }; -var server = tls.createServer(options, onconnection); -var gotChunk = false; -var gotDrain = false; +const server = tls.createServer(options, onconnection); +let gotChunk = false; +let gotDrain = false; setTimeout(function() { console.log('not ok - timed out'); @@ -41,9 +41,9 @@ function onconnection(conn) { } server.listen(0, function() { - var chunk = Buffer.alloc(1024, 'x'); - var opt = { port: this.address().port, rejectUnauthorized: false }; - var conn = tls.connect(opt, function() { + const chunk = Buffer.alloc(1024, 'x'); + const opt = { port: this.address().port, rejectUnauthorized: false }; + const conn = tls.connect(opt, function() { conn.on('drain', ondrain); write(); }); diff --git a/test/parallel/test-tls-friendly-error-message.js b/test/parallel/test-tls-friendly-error-message.js index 9ae69f4016e319..3f3bfe9133fcd6 100644 --- a/test/parallel/test-tls-friendly-error-message.js +++ b/test/parallel/test-tls-friendly-error-message.js @@ -17,7 +17,7 @@ tls.createServer({ key: key, cert: cert }, common.mustCall(function(conn) { conn.end(); this.close(); })).listen(0, common.mustCall(function() { - var options = { port: this.address().port, rejectUnauthorized: true }; + const options = { port: this.address().port, rejectUnauthorized: true }; tls.connect(options).on('error', common.mustCall(function(err) { assert.strictEqual(err.code, 'UNABLE_TO_VERIFY_LEAF_SIGNATURE'); assert.strictEqual(err.message, 'unable to verify the first certificate'); diff --git a/test/parallel/test-tls-handshake-error.js b/test/parallel/test-tls-handshake-error.js index 7623f816f3be07..4909fa45e160fb 100644 --- a/test/parallel/test-tls-handshake-error.js +++ b/test/parallel/test-tls-handshake-error.js @@ -11,13 +11,13 @@ const tls = require('tls'); const fs = require('fs'); -var server = tls.createServer({ +const server = tls.createServer({ key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem'), rejectUnauthorized: true }, function(c) { }).listen(0, common.mustCall(function() { - var c = tls.connect({ + const c = tls.connect({ port: this.address().port, ciphers: 'RC4' }, function() { diff --git a/test/parallel/test-tls-honorcipherorder.js b/test/parallel/test-tls-honorcipherorder.js index 883abc199ee321..f7894e46706da9 100644 --- a/test/parallel/test-tls-honorcipherorder.js +++ b/test/parallel/test-tls-honorcipherorder.js @@ -9,19 +9,19 @@ if (!common.hasCrypto) { const tls = require('tls'); const fs = require('fs'); -var nconns = 0; +let nconns = 0; // We explicitly set TLS version to 1.2 so as to be safe when the // default method is updated in the future -var SSL_Method = 'TLSv1_2_method'; -var localhost = '127.0.0.1'; +const SSL_Method = 'TLSv1_2_method'; +const localhost = '127.0.0.1'; process.on('exit', function() { assert.equal(nconns, 6); }); function test(honorCipherOrder, clientCipher, expectedCipher, cb) { - var soptions = { + const soptions = { secureProtocol: SSL_Method, key: fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem'), @@ -30,7 +30,7 @@ function test(honorCipherOrder, clientCipher, expectedCipher, cb) { honorCipherOrder: !!honorCipherOrder }; - var server = tls.createServer(soptions, function(cleartextStream) { + const server = tls.createServer(soptions, function(cleartextStream) { nconns++; // End socket to send CLOSE_NOTIFY and TCP FIN packet, otherwise @@ -38,7 +38,7 @@ function test(honorCipherOrder, clientCipher, expectedCipher, cb) { cleartextStream.end(); }); server.listen(0, localhost, function() { - var coptions = { + const coptions = { rejectUnauthorized: false, secureProtocol: SSL_Method }; @@ -46,8 +46,8 @@ function test(honorCipherOrder, clientCipher, expectedCipher, cb) { coptions.ciphers = clientCipher; } const port = this.address().port; - var client = tls.connect(port, localhost, coptions, function() { - var cipher = client.getCipher(); + const client = tls.connect(port, localhost, coptions, function() { + const cipher = client.getCipher(); client.end(); server.close(); assert.equal(cipher.name, expectedCipher); diff --git a/test/parallel/test-tls-inception.js b/test/parallel/test-tls-inception.js index 760887d9f25264..183fbe587b366c 100644 --- a/test/parallel/test-tls-inception.js +++ b/test/parallel/test-tls-inception.js @@ -54,7 +54,7 @@ a.listen(0, function() { rejectUnauthorized: false }); ssl.setEncoding('utf8'); - var buf = ''; + let buf = ''; ssl.on('data', function(data) { buf += data; }); diff --git a/test/parallel/test-tls-invoke-queued.js b/test/parallel/test-tls-invoke-queued.js index b37b900d77e300..bd3ad43fe653e5 100644 --- a/test/parallel/test-tls-invoke-queued.js +++ b/test/parallel/test-tls-invoke-queued.js @@ -11,9 +11,9 @@ const tls = require('tls'); const fs = require('fs'); -var received = ''; +let received = ''; -var server = tls.createServer({ +const server = tls.createServer({ key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }, function(c) { @@ -26,7 +26,7 @@ var server = tls.createServer({ server.close(); }).listen(0, common.mustCall(function() { - var c = tls.connect(this.address().port, { + const c = tls.connect(this.address().port, { rejectUnauthorized: false }, common.mustCall(function() { c.on('data', function(chunk) { diff --git a/test/parallel/test-tls-js-stream.js b/test/parallel/test-tls-js-stream.js index 2f69a306cfdcec..e1b580da303f8d 100644 --- a/test/parallel/test-tls-js-stream.js +++ b/test/parallel/test-tls-js-stream.js @@ -12,12 +12,12 @@ const stream = require('stream'); const fs = require('fs'); const net = require('net'); -var connected = { +const connected = { client: 0, server: 0 }; -var server = tls.createServer({ +const server = tls.createServer({ key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }, function(c) { @@ -25,19 +25,19 @@ var server = tls.createServer({ connected.server++; c.end('ohai'); }).listen(0, function() { - var raw = net.connect(this.address().port); + const raw = net.connect(this.address().port); - var pending = false; + let pending = false; raw.on('readable', function() { if (pending) p._read(); }); - var p = new stream.Duplex({ + const p = new stream.Duplex({ read: function read() { pending = false; - var chunk = raw.read(); + const chunk = raw.read(); if (chunk) { console.log('read', chunk); this.push(chunk); @@ -51,7 +51,7 @@ var server = tls.createServer({ } }); - var socket = tls.connect({ + const socket = tls.connect({ socket: p, rejectUnauthorized: false }, function() { diff --git a/test/parallel/test-tls-legacy-onselect.js b/test/parallel/test-tls-legacy-onselect.js index 392df2e71588aa..9af65c43a0661c 100644 --- a/test/parallel/test-tls-legacy-onselect.js +++ b/test/parallel/test-tls-legacy-onselect.js @@ -8,8 +8,8 @@ if (!common.hasCrypto) { const tls = require('tls'); const net = require('net'); -var server = net.Server(common.mustCall(function(raw) { - var pair = tls.createSecurePair(null, true, false, false); +const server = net.Server(common.mustCall(function(raw) { + const pair = tls.createSecurePair(null, true, false, false); pair.on('error', function() {}); pair.ssl.setSNICallback(common.mustCall(function() { raw.destroy(); diff --git a/test/parallel/test-tls-max-send-fragment.js b/test/parallel/test-tls-max-send-fragment.js index d96f42e6a2e82f..4b81be35e34522 100644 --- a/test/parallel/test-tls-max-send-fragment.js +++ b/test/parallel/test-tls-max-send-fragment.js @@ -10,11 +10,11 @@ const tls = require('tls'); const fs = require('fs'); -var buf = Buffer.allocUnsafe(10000); -var received = 0; -var maxChunk = 768; +const buf = Buffer.allocUnsafe(10000); +let received = 0; +const maxChunk = 768; -var server = tls.createServer({ +const server = tls.createServer({ key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }, function(c) { @@ -27,7 +27,7 @@ var server = tls.createServer({ c.end(buf); }).listen(0, common.mustCall(function() { - var c = tls.connect(this.address().port, { + const c = tls.connect(this.address().port, { rejectUnauthorized: false }, common.mustCall(function() { c.on('data', function(chunk) { diff --git a/test/parallel/test-tls-multi-key.js b/test/parallel/test-tls-multi-key.js index 840deb59d4bde6..e3d5d661a799a7 100644 --- a/test/parallel/test-tls-multi-key.js +++ b/test/parallel/test-tls-multi-key.js @@ -9,7 +9,7 @@ if (!common.hasCrypto) { const tls = require('tls'); const fs = require('fs'); -var options = { +const options = { key: [ fs.readFileSync(common.fixturesDir + '/keys/ec-key.pem'), fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), @@ -20,17 +20,17 @@ var options = { ] }; -var ciphers = []; +const ciphers = []; -var server = tls.createServer(options, function(conn) { +const server = tls.createServer(options, function(conn) { conn.end('ok'); }).listen(0, function() { - var ecdsa = tls.connect(this.address().port, { + const ecdsa = tls.connect(this.address().port, { ciphers: 'ECDHE-ECDSA-AES256-GCM-SHA384', rejectUnauthorized: false }, function() { ciphers.push(ecdsa.getCipher()); - var rsa = tls.connect(server.address().port, { + const rsa = tls.connect(server.address().port, { ciphers: 'ECDHE-RSA-AES256-GCM-SHA384', rejectUnauthorized: false }, function() { diff --git a/test/parallel/test-tls-no-rsa-key.js b/test/parallel/test-tls-no-rsa-key.js index 1e75b21eaba14c..233d8453db1318 100644 --- a/test/parallel/test-tls-no-rsa-key.js +++ b/test/parallel/test-tls-no-rsa-key.js @@ -10,15 +10,15 @@ const tls = require('tls'); const fs = require('fs'); -var options = { +const options = { key: fs.readFileSync(common.fixturesDir + '/keys/ec-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/ec-cert.pem') }; -var server = tls.createServer(options, function(conn) { +const server = tls.createServer(options, function(conn) { conn.end('ok'); }).listen(0, common.mustCall(function() { - var c = tls.connect(this.address().port, { + const c = tls.connect(this.address().port, { rejectUnauthorized: false }, common.mustCall(function() { c.on('end', common.mustCall(function() { diff --git a/test/parallel/test-tls-npn-server-client.js b/test/parallel/test-tls-npn-server-client.js index fdd9fcbb328cfb..1b622cc8f72c20 100644 --- a/test/parallel/test-tls-npn-server-client.js +++ b/test/parallel/test-tls-npn-server-client.js @@ -24,7 +24,7 @@ function loadPEM(n) { return fs.readFileSync(filenamePEM(n)); } -var serverOptions = { +const serverOptions = { key: loadPEM('agent2-key'), cert: loadPEM('agent2-cert'), crl: loadPEM('ca2-crl'), @@ -38,7 +38,7 @@ var serverOptions = { NPNProtocols: ['a', 'b', 'c'] }; -var clientsOptions = [{ +const clientsOptions = [{ port: undefined, key: serverOptions.key, cert: serverOptions.cert, @@ -70,7 +70,7 @@ var clientsOptions = [{ const serverResults = []; const clientsResults = []; -var server = tls.createServer(serverOptions, function(c) { +const server = tls.createServer(serverOptions, function(c) { serverResults.push(c.npnProtocol); }); server.listen(0, startTest); @@ -78,7 +78,7 @@ server.listen(0, startTest); function startTest() { function connectClient(options, callback) { options.port = server.address().port; - var client = tls.connect(options, function() { + const client = tls.connect(options, function() { clientsResults.push(client.npnProtocol); client.destroy(); diff --git a/test/parallel/test-tls-over-http-tunnel.js b/test/parallel/test-tls-over-http-tunnel.js index f55f1c0ac0c450..4e03bcaf537f26 100644 --- a/test/parallel/test-tls-over-http-tunnel.js +++ b/test/parallel/test-tls-over-http-tunnel.js @@ -12,17 +12,17 @@ const fs = require('fs'); const net = require('net'); const http = require('http'); -var gotRequest = false; +let gotRequest = false; -var key = fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'); -var cert = fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem'); +const key = fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'); +const cert = fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem'); -var options = { +const options = { key: key, cert: cert }; -var server = https.createServer(options, function(req, res) { +const server = https.createServer(options, function(req, res) { console.log('SERVER: got request'); res.writeHead(200, { 'content-type': 'text/plain' @@ -31,10 +31,10 @@ var server = https.createServer(options, function(req, res) { res.end('hello world\n'); }); -var proxy = net.createServer(function(clientSocket) { +const proxy = net.createServer(function(clientSocket) { console.log('PROXY: got a client connection'); - var serverSocket = null; + let serverSocket = null; clientSocket.on('data', function(chunk) { if (!serverSocket) { @@ -80,7 +80,7 @@ server.listen(0); proxy.listen(0, function() { console.log('CLIENT: Making CONNECT request'); - var req = http.request({ + const req = http.request({ port: this.address().port, method: 'CONNECT', path: `localhost:${server.address().port}`, diff --git a/test/parallel/test-tls-pause.js b/test/parallel/test-tls-pause.js index aa48c04866654a..911ea7097b1e70 100644 --- a/test/parallel/test-tls-pause.js +++ b/test/parallel/test-tls-pause.js @@ -11,16 +11,16 @@ const tls = require('tls'); const fs = require('fs'); const path = require('path'); -var options = { +const options = { key: fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')), cert: fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')) }; -var bufSize = 1024 * 1024; -var sent = 0; -var received = 0; +const bufSize = 1024 * 1024; +let sent = 0; +let received = 0; -var server = tls.Server(options, function(socket) { +const server = tls.Server(options, function(socket) { socket.pipe(socket); socket.on('data', function(c) { console.error('data', c.length); @@ -28,8 +28,8 @@ var server = tls.Server(options, function(socket) { }); server.listen(0, function() { - var resumed = false; - var client = tls.connect({ + let resumed = false; + const client = tls.connect({ port: this.address().port, rejectUnauthorized: false }, function() { @@ -39,7 +39,7 @@ server.listen(0, function() { send(); function send() { console.error('sending'); - var ret = client.write(Buffer.allocUnsafe(bufSize)); + const ret = client.write(Buffer.allocUnsafe(bufSize)); console.error('write => %j', ret); if (false !== ret) { console.error('write again'); diff --git a/test/parallel/test-tls-peer-certificate-encoding.js b/test/parallel/test-tls-peer-certificate-encoding.js index 1062dab2af1d2e..545caf403e103c 100644 --- a/test/parallel/test-tls-peer-certificate-encoding.js +++ b/test/parallel/test-tls-peer-certificate-encoding.js @@ -12,21 +12,21 @@ const fs = require('fs'); const util = require('util'); const join = require('path').join; -var options = { +const options = { key: fs.readFileSync(join(common.fixturesDir, 'keys', 'agent5-key.pem')), cert: fs.readFileSync(join(common.fixturesDir, 'keys', 'agent5-cert.pem')), ca: [ fs.readFileSync(join(common.fixturesDir, 'keys', 'ca2-cert.pem')) ] }; -var server = tls.createServer(options, function(cleartext) { +const server = tls.createServer(options, function(cleartext) { cleartext.end('World'); }); server.listen(0, common.mustCall(function() { - var socket = tls.connect({ + const socket = tls.connect({ port: this.address().port, rejectUnauthorized: false }, common.mustCall(function() { - var peerCert = socket.getPeerCertificate(); + const peerCert = socket.getPeerCertificate(); console.error(util.inspect(peerCert)); assert.equal(peerCert.subject.CN, 'Ádám Lippai'); diff --git a/test/parallel/test-tls-peer-certificate-multi-keys.js b/test/parallel/test-tls-peer-certificate-multi-keys.js index 6176a34a716096..693bb4cb3fa812 100644 --- a/test/parallel/test-tls-peer-certificate-multi-keys.js +++ b/test/parallel/test-tls-peer-certificate-multi-keys.js @@ -12,20 +12,20 @@ const fs = require('fs'); const util = require('util'); const join = require('path').join; -var options = { +const options = { key: fs.readFileSync(join(common.fixturesDir, 'agent.key')), cert: fs.readFileSync(join(common.fixturesDir, 'multi-alice.crt')) }; -var server = tls.createServer(options, function(cleartext) { +const server = tls.createServer(options, function(cleartext) { cleartext.end('World'); }); server.listen(0, common.mustCall(function() { - var socket = tls.connect({ + const socket = tls.connect({ port: this.address().port, rejectUnauthorized: false }, common.mustCall(function() { - var peerCert = socket.getPeerCertificate(); + const peerCert = socket.getPeerCertificate(); console.error(util.inspect(peerCert)); assert.deepStrictEqual( peerCert.subject.OU, diff --git a/test/parallel/test-tls-pfx-gh-5100-regr.js b/test/parallel/test-tls-pfx-gh-5100-regr.js index 4670d9ea3da740..142a7de10b841a 100644 --- a/test/parallel/test-tls-pfx-gh-5100-regr.js +++ b/test/parallel/test-tls-pfx-gh-5100-regr.js @@ -28,7 +28,7 @@ const server = tls.createServer({ ); c.end(); })).listen(0, function() { - var client = tls.connect({ + const client = tls.connect({ port: this.address().port, pfx: pfx, passphrase: 'sample', diff --git a/test/parallel/test-tls-request-timeout.js b/test/parallel/test-tls-request-timeout.js index 2d1ddf34b32032..4873a3c696458f 100644 --- a/test/parallel/test-tls-request-timeout.js +++ b/test/parallel/test-tls-request-timeout.js @@ -10,13 +10,13 @@ const tls = require('tls'); const fs = require('fs'); -var options = { +const options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }; -var server = tls.Server(options, common.mustCall(function(socket) { - var s = socket.setTimeout(100); +const server = tls.Server(options, common.mustCall(function(socket) { + const s = socket.setTimeout(100); assert.ok(s instanceof tls.TLSSocket); socket.on('timeout', common.mustCall(function(err) { diff --git a/test/parallel/test-tls-securepair-fiftharg.js b/test/parallel/test-tls-securepair-fiftharg.js index 99564055efb807..c79b5cbede8808 100644 --- a/test/parallel/test-tls-securepair-fiftharg.js +++ b/test/parallel/test-tls-securepair-fiftharg.js @@ -15,7 +15,7 @@ const sslcontext = tls.createSecureContext({ key: fs.readFileSync(common.fixturesDir + '/test_key.pem') }); -var catchedServername; +let catchedServername; const pair = tls.createSecurePair(sslcontext, true, false, false, { SNICallback: common.mustCall(function(servername, cb) { catchedServername = servername; diff --git a/test/parallel/test-tls-securepair-server.js b/test/parallel/test-tls-securepair-server.js index afe76a0139a59d..65a7d91a0ca606 100644 --- a/test/parallel/test-tls-securepair-server.js +++ b/test/parallel/test-tls-securepair-server.js @@ -13,19 +13,19 @@ const net = require('net'); const fs = require('fs'); const spawn = require('child_process').spawn; -var key = fs.readFileSync(join(common.fixturesDir, 'agent.key')).toString(); -var cert = fs.readFileSync(join(common.fixturesDir, 'agent.crt')).toString(); +const key = fs.readFileSync(join(common.fixturesDir, 'agent.key')).toString(); +const cert = fs.readFileSync(join(common.fixturesDir, 'agent.crt')).toString(); function log(a) { console.error('***server*** ' + a); } -var server = net.createServer(common.mustCall(function(socket) { +const server = net.createServer(common.mustCall(function(socket) { log('connection fd=' + socket.fd); - var sslcontext = tls.createSecureContext({key: key, cert: cert}); + const sslcontext = tls.createSecureContext({key: key, cert: cert}); sslcontext.context.setCiphers('RC4-SHA:AES128-SHA:AES256-SHA'); - var pair = tls.createSecurePair(sslcontext, true); + const pair = tls.createSecurePair(sslcontext, true); assert.ok(pair.encrypted.writable); assert.ok(pair.cleartext.writable); @@ -84,23 +84,23 @@ var server = net.createServer(common.mustCall(function(socket) { }); })); -var gotHello = false; -var sentWorld = false; -var gotWorld = false; +let gotHello = false; +let sentWorld = false; +let gotWorld = false; server.listen(0, common.mustCall(function() { // To test use: openssl s_client -connect localhost:8000 - var args = ['s_client', '-connect', `127.0.0.1:${this.address().port}`]; + const args = ['s_client', '-connect', `127.0.0.1:${this.address().port}`]; // for the performance and stability issue in s_client on Windows if (common.isWindows) args.push('-no_rand_screen'); - var client = spawn(common.opensslCli, args); + const client = spawn(common.opensslCli, args); - var out = ''; + let out = ''; client.stdout.setEncoding('utf8'); client.stdout.on('data', function(d) { diff --git a/test/parallel/test-tls-session-cache.js b/test/parallel/test-tls-session-cache.js index 60a85701796d72..5e3ae5128ecfaf 100644 --- a/test/parallel/test-tls-session-cache.js +++ b/test/parallel/test-tls-session-cache.js @@ -34,9 +34,9 @@ function doTest(testOptions, callback) { ca: [cert], requestCert: true }; - var requestCount = 0; - var resumeCount = 0; - var session; + let requestCount = 0; + let resumeCount = 0; + let session; const server = tls.createServer(options, function(cleartext) { cleartext.on('error', function(er) { @@ -90,7 +90,7 @@ function doTest(testOptions, callback) { const client = spawn(common.opensslCli, args, { stdio: [ 0, 1, 'pipe' ] }); - var err = ''; + let err = ''; client.stderr.setEncoding('utf8'); client.stderr.on('data', function(chunk) { err += chunk; diff --git a/test/parallel/test-tls-set-ciphers.js b/test/parallel/test-tls-set-ciphers.js index ef08c56460c10d..a1af1a917eb826 100644 --- a/test/parallel/test-tls-set-ciphers.js +++ b/test/parallel/test-tls-set-ciphers.js @@ -34,7 +34,7 @@ const server = tls.createServer(options, common.mustCall(function(conn) { })); server.listen(0, '127.0.0.1', function() { - var cmd = '"' + common.opensslCli + '" s_client -cipher ' + options.ciphers + + let cmd = '"' + common.opensslCli + '" s_client -cipher ' + options.ciphers + ` -connect 127.0.0.1:${this.address().port}`; // for the performance and stability issue in s_client on Windows diff --git a/test/parallel/test-tls-sni-option.js b/test/parallel/test-tls-sni-option.js index 436618379a78e9..2e7245336b8b98 100644 --- a/test/parallel/test-tls-sni-option.js +++ b/test/parallel/test-tls-sni-option.js @@ -23,13 +23,13 @@ function loadPEM(n) { return fs.readFileSync(filenamePEM(n)); } -var serverOptions = { +const serverOptions = { key: loadPEM('agent2-key'), cert: loadPEM('agent2-cert'), requestCert: true, rejectUnauthorized: false, SNICallback: function(servername, callback) { - var context = SNIContexts[servername]; + const context = SNIContexts[servername]; // Just to test asynchronous callback setTimeout(function() { @@ -45,7 +45,7 @@ var serverOptions = { } }; -var SNIContexts = { +const SNIContexts = { 'a.example.com': { key: loadPEM('agent1-key'), cert: loadPEM('agent1-cert'), @@ -60,7 +60,7 @@ var SNIContexts = { } }; -var clientsOptions = [{ +const clientsOptions = [{ port: undefined, key: loadPEM('agent1-key'), cert: loadPEM('agent1-cert'), @@ -104,7 +104,7 @@ const clientErrors = []; let serverError; let clientError; -var server = tls.createServer(serverOptions, function(c) { +const server = tls.createServer(serverOptions, function(c) { serverResults.push({ sni: c.servername, authorized: c.authorized }); }); @@ -117,12 +117,12 @@ server.listen(0, startTest); function startTest() { function connectClient(i, callback) { - var options = clientsOptions[i]; + const options = clientsOptions[i]; clientError = null; serverError = null; options.port = server.address().port; - var client = tls.connect(options, function() { + const client = tls.connect(options, function() { clientResults.push( /Hostname\/IP doesn't/.test(client.authorizationError || '')); client.destroy(); diff --git a/test/parallel/test-tls-sni-server-client.js b/test/parallel/test-tls-sni-server-client.js index a22b6a9726a857..93fffd3888ffd1 100644 --- a/test/parallel/test-tls-sni-server-client.js +++ b/test/parallel/test-tls-sni-server-client.js @@ -23,12 +23,12 @@ function loadPEM(n) { return fs.readFileSync(filenamePEM(n)); } -var serverOptions = { +const serverOptions = { key: loadPEM('agent2-key'), cert: loadPEM('agent2-cert') }; -var SNIContexts = { +const SNIContexts = { 'a.example.com': { key: loadPEM('agent1-key'), cert: loadPEM('agent1-cert') @@ -44,7 +44,7 @@ var SNIContexts = { } }; -var clientsOptions = [{ +const clientsOptions = [{ port: undefined, ca: [loadPEM('ca1-cert')], servername: 'a.example.com', @@ -74,7 +74,7 @@ var clientsOptions = [{ const serverResults = []; const clientResults = []; -var server = tls.createServer(serverOptions, function(c) { +const server = tls.createServer(serverOptions, function(c) { serverResults.push(c.servername); }); @@ -85,15 +85,15 @@ server.addContext('chain.example.com', SNIContexts['chain.example.com']); server.listen(0, startTest); function startTest() { - var i = 0; + let i = 0; function start() { // No options left if (i === clientsOptions.length) return server.close(); - var options = clientsOptions[i++]; + const options = clientsOptions[i++]; options.port = server.address().port; - var client = tls.connect(options, function() { + const client = tls.connect(options, function() { clientResults.push( client.authorizationError && /Hostname\/IP doesn't/.test(client.authorizationError)); diff --git a/test/parallel/test-tls-wrap-timeout.js b/test/parallel/test-tls-wrap-timeout.js index 0454242d92ecb6..d66e1f2d680f77 100644 --- a/test/parallel/test-tls-wrap-timeout.js +++ b/test/parallel/test-tls-wrap-timeout.js @@ -27,8 +27,8 @@ const server = tls.createServer(options, common.mustCall((c) => { }); })); -var socket; -var lastIdleStart; +let socket; +let lastIdleStart; server.listen(0, () => { socket = net.connect(server.address().port, function() { diff --git a/test/parallel/test-umask.js b/test/parallel/test-umask.js index 397f26ce9013a5..1c870893a3bced 100644 --- a/test/parallel/test-umask.js +++ b/test/parallel/test-umask.js @@ -3,14 +3,14 @@ const common = require('../common'); const assert = require('assert'); // Note in Windows one can only set the "user" bits. -var mask; +let mask; if (common.isWindows) { mask = '0600'; } else { mask = '0664'; } -var old = process.umask(mask); +const old = process.umask(mask); assert.equal(parseInt(mask, 8), process.umask(old)); diff --git a/test/parallel/test-url.js b/test/parallel/test-url.js index c97caa36429a9c..3a8c06c3ee4637 100644 --- a/test/parallel/test-url.js +++ b/test/parallel/test-url.js @@ -8,7 +8,7 @@ const url = require('url'); // URLs to parse, and expected data // { url : parsed } -var parseTests = { +const parseTests = { '//some_path': { href: '//some_path', pathname: '//some_path', @@ -942,7 +942,7 @@ function check(actual, expected) { }); } -var parseTestsWithQueryString = { +const parseTestsWithQueryString = { '/foo/bar?baz=quux#frag': { href: '/foo/bar?baz=quux#frag', hash: '#frag', @@ -1013,7 +1013,7 @@ for (const u in parseTestsWithQueryString) { // some extra formatting tests, just to verify // that it'll format slightly wonky content to a valid url. -var formatTests = { +const formatTests = { 'http://example.com?': { href: 'http://example.com/?', protocol: 'http:', @@ -1250,7 +1250,7 @@ for (const u in formatTests) { /* [from, path, expected] */ -var relativeTests = [ +const relativeTests = [ ['/foo/bar/baz', 'quux', '/foo/bar/quux'], ['/foo/bar/baz', 'quux/asdf', '/foo/bar/quux/asdf'], ['/foo/bar/baz', 'quux/baz', '/foo/bar/quux/baz'], @@ -1329,7 +1329,7 @@ relativeTests.forEach(function(relativeTest) { // // Changes marked with @isaacs -var bases = [ +const bases = [ 'http://a/b/c/d;p?q', 'http://a/b/c/d;p?q=1/2', 'http://a/b/c/d;p=1/2?q', @@ -1338,7 +1338,7 @@ var bases = [ ]; //[to, from, result] -var relativeTests2 = [ +const relativeTests2 = [ // http://lists.w3.org/Archives/Public/uri/2004Feb/0114.html ['../c', 'foo:a/b', 'foo:c'], ['foo:.', 'foo:a', 'foo:'], @@ -1641,8 +1641,8 @@ relativeTests2.forEach(function(relativeTest) { //format: [from, path, expected] relativeTests.forEach(function(relativeTest) { - var actual = url.resolveObject(url.parse(relativeTest[0]), relativeTest[1]); - var expected = url.parse(relativeTest[2]); + let actual = url.resolveObject(url.parse(relativeTest[0]), relativeTest[1]); + let expected = url.parse(relativeTest[2]); assert.deepStrictEqual(actual, expected); @@ -1669,8 +1669,8 @@ if (relativeTests2[181][0] === './/g' && relativeTests2.splice(181, 1); } relativeTests2.forEach(function(relativeTest) { - var actual = url.resolveObject(url.parse(relativeTest[1]), relativeTest[0]); - var expected = url.parse(relativeTest[2]); + let actual = url.resolveObject(url.parse(relativeTest[1]), relativeTest[0]); + let expected = url.parse(relativeTest[2]); assert.deepStrictEqual( actual, @@ -1688,7 +1688,7 @@ relativeTests2.forEach(function(relativeTest) { // https://github.com/nodejs/node/pull/1036 -var throws = [ +const throws = [ undefined, null, true, diff --git a/test/parallel/test-util-inspect.js b/test/parallel/test-util-inspect.js index 7df3574a5a5736..62743ebd19d16a 100644 --- a/test/parallel/test-util-inspect.js +++ b/test/parallel/test-util-inspect.js @@ -233,7 +233,7 @@ assert.strictEqual(util.inspect({get readwrite() {}, set readwrite(val) {}}), assert.strictEqual(util.inspect({set writeonly(val) {}}), '{ writeonly: [Setter] }'); -var value = {}; +let value = {}; value['a'] = value; assert.strictEqual(util.inspect(value), '{ a: [Circular] }'); @@ -272,10 +272,10 @@ assert.strictEqual(util.inspect(value), '{ 2010-02-14T11:48:40.000Z aprop: 42 }' // test the internal isDate implementation const Date2 = vm.runInNewContext('Date'); -var d = new Date2(); -var orig = util.inspect(d); +const d = new Date2(); +const orig = util.inspect(d); Date2.prototype.foo = 'bar'; -var after = util.inspect(d); +const after = util.inspect(d); assert.strictEqual(orig, after); // test positive/negative zero @@ -283,7 +283,7 @@ assert.strictEqual(util.inspect(0), '0'); assert.strictEqual(util.inspect(-0), '-0'); // test for sparse array -var a = ['foo', 'bar', 'baz']; +const a = ['foo', 'bar', 'baz']; assert.strictEqual(util.inspect(a), '[ \'foo\', \'bar\', \'baz\' ]'); delete a[1]; assert.strictEqual(util.inspect(a), '[ \'foo\', , \'baz\' ]'); @@ -319,17 +319,17 @@ obj = vm.runInNewContext('fn=function(){};new Promise(fn,fn)', {}); assert.strictEqual(util.inspect(obj), 'Promise { }'); // test for property descriptors -var getter = Object.create(null, { +const getter = Object.create(null, { a: { get: function() { return 'aaa'; } } }); -var setter = Object.create(null, { +const setter = Object.create(null, { b: { set: function() {} } }); -var getterAndSetter = Object.create(null, { +const getterAndSetter = Object.create(null, { c: { get: function() { return 'ccc'; }, set: function() {} @@ -356,7 +356,7 @@ try { } catch (e) { assert.strictEqual(util.inspect(e), e.stack); } -var ex = util.inspect(new Error('FAIL'), true); +const ex = util.inspect(new Error('FAIL'), true); assert(ex.includes('Error: FAIL')); assert(ex.includes('[stack]')); assert(ex.includes('[message]')); @@ -380,19 +380,19 @@ assert.strictEqual(util.inspect(Object.create(Date.prototype)), 'Date {}'); // GH-1944 assert.doesNotThrow(function() { - var d = new Date(); + const d = new Date(); d.toUTCString = null; util.inspect(d); }); assert.doesNotThrow(function() { - var d = new Date(); + const d = new Date(); d.toISOString = null; util.inspect(d); }); assert.doesNotThrow(function() { - var r = /regexp/; + const r = /regexp/; r.toString = null; util.inspect(r); }); @@ -411,14 +411,14 @@ assert.doesNotThrow(function() { } // util.inspect should not display the escaped value of a key. -var w = { +const w = { '\\': 1, '\\\\': 2, '\\\\\\': 3, '\\\\\\\\': 4, }; -var y = ['a', 'b', 'c']; +const y = ['a', 'b', 'c']; y['\\\\\\'] = 'd'; assert.strictEqual( @@ -432,15 +432,15 @@ assert.strictEqual( // util.inspect.styles and util.inspect.colors function test_color_style(style, input, implicit) { - var color_name = util.inspect.styles[style]; - var color = ['', '']; + const color_name = util.inspect.styles[style]; + let color = ['', '']; if (util.inspect.colors[color_name]) color = util.inspect.colors[color_name]; - var without_color = util.inspect(input, false, 0, false); - var with_color = util.inspect(input, false, 0, true); - var expect = '\u001b[' + color[0] + 'm' + without_color + - '\u001b[' + color[1] + 'm'; + const without_color = util.inspect(input, false, 0, false); + const with_color = util.inspect(input, false, 0, true); + const expect = '\u001b[' + color[0] + 'm' + without_color + + '\u001b[' + color[1] + 'm'; assert.strictEqual( with_color, expect, @@ -593,19 +593,19 @@ assert.doesNotThrow(function() { // util.inspect with "colors" option should produce as many lines as without it function test_lines(input) { - var count_lines = function(str) { + const count_lines = function(str) { return (str.match(/\n/g) || []).length; }; - var without_color = util.inspect(input); - var with_color = util.inspect(input, {colors: true}); + const without_color = util.inspect(input); + const with_color = util.inspect(input, {colors: true}); assert.strictEqual(count_lines(without_color), count_lines(with_color)); } test_lines([1, 2, 3, 4, 5, 6, 7]); test_lines(function() { - var big_array = []; - for (var i = 0; i < 100; i++) { + const big_array = []; + for (let i = 0; i < 100; i++) { big_array.push(i); } return big_array; @@ -633,15 +633,15 @@ assert.strictEqual(util.inspect(new Number(-1.1)), '[Number: -1.1]'); assert.strictEqual(util.inspect(new Number(13.37)), '[Number: 13.37]'); // test boxed primitives with own properties -var str = new String('baz'); +const str = new String('baz'); str.foo = 'bar'; assert.strictEqual(util.inspect(str), '{ [String: \'baz\'] foo: \'bar\' }'); -var bool = new Boolean(true); +const bool = new Boolean(true); bool.foo = 'bar'; assert.strictEqual(util.inspect(bool), '{ [Boolean: true] foo: \'bar\' }'); -var num = new Number(13.37); +const num = new Number(13.37); num.foo = 'bar'; assert.strictEqual(util.inspect(num), '{ [Number: 13.37] foo: \'bar\' }'); @@ -675,7 +675,7 @@ if (typeof Symbol !== 'undefined') { // test Set assert.strictEqual(util.inspect(new Set()), 'Set {}'); assert.strictEqual(util.inspect(new Set([1, 2, 3])), 'Set { 1, 2, 3 }'); -var set = new Set(['foo']); +const set = new Set(['foo']); set.bar = 42; assert.strictEqual( util.inspect(set, true), @@ -707,30 +707,30 @@ assert.strictEqual( util.inspect(new Promise(function() {})), 'Promise { }' ); -var promise = Promise.resolve('foo'); +const promise = Promise.resolve('foo'); promise.bar = 42; assert.strictEqual(util.inspect(promise), 'Promise { \'foo\', bar: 42 }'); // Make sure it doesn't choke on polyfills. Unlike Set/Map, there is no standard // interface to synchronously inspect a Promise, so our techniques only work on // a bonafide native Promise. -var oldPromise = Promise; +const oldPromise = Promise; global.Promise = function() { this.bar = 42; }; assert.strictEqual(util.inspect(new Promise()), '{ bar: 42 }'); global.Promise = oldPromise; // Map/Set Iterators -var m = new Map([['foo', 'bar']]); +const m = new Map([['foo', 'bar']]); assert.strictEqual(util.inspect(m.keys()), 'MapIterator { \'foo\' }'); assert.strictEqual(util.inspect(m.values()), 'MapIterator { \'bar\' }'); assert.strictEqual(util.inspect(m.entries()), 'MapIterator { [ \'foo\', \'bar\' ] }'); // make sure the iterator doesn't get consumed -var keys = m.keys(); +let keys = m.keys(); assert.strictEqual(util.inspect(keys), 'MapIterator { \'foo\' }'); assert.strictEqual(util.inspect(keys), 'MapIterator { \'foo\' }'); -var s = new Set([1, 3]); +const s = new Set([1, 3]); assert.strictEqual(util.inspect(s.keys()), 'SetIterator { 1, 3 }'); assert.strictEqual(util.inspect(s.values()), 'SetIterator { 1, 3 }'); assert.strictEqual(util.inspect(s.entries()), @@ -744,10 +744,10 @@ assert.strictEqual(util.inspect(keys), 'SetIterator { 1, 3 }'); // Assumes that the first numeric character is the start of an item. function checkAlignment(container) { - var lines = util.inspect(container).split('\n'); - var pos; + const lines = util.inspect(container).split('\n'); + let pos; lines.forEach(function(line) { - var npos = line.search(/\d/); + const npos = line.search(/\d/); if (npos !== -1) { if (pos !== undefined) assert.strictEqual(pos, npos, 'container items not aligned'); @@ -756,14 +756,14 @@ function checkAlignment(container) { }); } -var big_array = []; -for (var i = 0; i < 100; i++) { +const big_array = []; +for (let i = 0; i < 100; i++) { big_array.push(i); } checkAlignment(big_array); checkAlignment(function() { - var obj = {}; + const obj = {}; big_array.forEach(function(v) { obj[v] = null; }); diff --git a/test/parallel/test-util-log.js b/test/parallel/test-util-log.js index 8480bf83eaf18c..d45ebf2fc0b729 100644 --- a/test/parallel/test-util-log.js +++ b/test/parallel/test-util-log.js @@ -6,14 +6,14 @@ const util = require('util'); assert.ok(process.stdout.writable); assert.ok(process.stderr.writable); -var stdout_write = global.process.stdout.write; -var strings = []; +const stdout_write = global.process.stdout.write; +const strings = []; global.process.stdout.write = function(string) { strings.push(string); }; console._stderr = process.stdout; -var tests = [ +const tests = [ {input: 'foo', output: 'foo'}, {input: undefined, output: 'undefined'}, {input: null, output: 'null'}, diff --git a/test/parallel/test-v8-stats.js b/test/parallel/test-v8-stats.js index dc36beac131446..5b756f35962525 100644 --- a/test/parallel/test-v8-stats.js +++ b/test/parallel/test-v8-stats.js @@ -3,8 +3,8 @@ require('../common'); const assert = require('assert'); const v8 = require('v8'); -var s = v8.getHeapStatistics(); -var keys = [ +const s = v8.getHeapStatistics(); +const keys = [ 'does_zap_garbage', 'heap_size_limit', 'malloced_memory', diff --git a/test/parallel/test-vm-basic.js b/test/parallel/test-vm-basic.js index 75163d6cd3218a..2d57cc0d4ba328 100644 --- a/test/parallel/test-vm-basic.js +++ b/test/parallel/test-vm-basic.js @@ -4,8 +4,8 @@ const assert = require('assert'); const vm = require('vm'); // Test 1: vm.runInNewContext -var sandbox = {}; -var result = vm.runInNewContext( +const sandbox = {}; +let result = vm.runInNewContext( 'foo = "bar"; this.typeofProcess = typeof process; typeof Object;', sandbox ); @@ -16,8 +16,8 @@ assert.deepStrictEqual(sandbox, { assert.strictEqual(result, 'function'); // Test 2: vm.runInContext -var sandbox2 = { foo: 'bar' }; -var context = vm.createContext(sandbox2); +const sandbox2 = { foo: 'bar' }; +const context = vm.createContext(sandbox2); result = vm.runInContext( 'baz = foo; this.typeofProcess = typeof process; typeof Object;', context @@ -45,6 +45,6 @@ assert.strictEqual(global.vmResult, undefined); assert.strictEqual(result, 'undefined'); // Test 5: vm.createContext -var sandbox3 = {}; -var context2 = vm.createContext(sandbox3); +const sandbox3 = {}; +const context2 = vm.createContext(sandbox3); assert.strictEqual(sandbox3, context2); diff --git a/test/parallel/test-vm-context-async-script.js b/test/parallel/test-vm-context-async-script.js index b4045fbfd3c246..1e9ed629fb114f 100644 --- a/test/parallel/test-vm-context-async-script.js +++ b/test/parallel/test-vm-context-async-script.js @@ -3,9 +3,9 @@ require('../common'); const assert = require('assert'); const vm = require('vm'); -var sandbox = { setTimeout: setTimeout }; +const sandbox = { setTimeout: setTimeout }; -var ctx = vm.createContext(sandbox); +const ctx = vm.createContext(sandbox); vm.runInContext('setTimeout(function() { x = 3; }, 0);', ctx); setTimeout(function() { diff --git a/test/parallel/test-vm-context-property-forwarding.js b/test/parallel/test-vm-context-property-forwarding.js index 03faef596f2872..b77fc45217039f 100644 --- a/test/parallel/test-vm-context-property-forwarding.js +++ b/test/parallel/test-vm-context-property-forwarding.js @@ -3,9 +3,9 @@ require('../common'); const assert = require('assert'); const vm = require('vm'); -var sandbox = { x: 3 }; +const sandbox = { x: 3 }; -var ctx = vm.createContext(sandbox); +const ctx = vm.createContext(sandbox); assert.strictEqual(vm.runInContext('x;', ctx), 3); vm.runInContext('y = 4;', ctx); diff --git a/test/parallel/test-vm-context.js b/test/parallel/test-vm-context.js index 48319be3a9fc58..e4f6960259abe2 100644 --- a/test/parallel/test-vm-context.js +++ b/test/parallel/test-vm-context.js @@ -3,12 +3,12 @@ require('../common'); const assert = require('assert'); const vm = require('vm'); -var Script = vm.Script; -var script = new Script('"passed";'); +const Script = vm.Script; +let script = new Script('"passed";'); console.error('run in a new empty context'); -var context = vm.createContext(); -var result = script.runInContext(context); +let context = vm.createContext(); +let result = script.runInContext(context); assert.equal('passed', result); console.error('create a new pre-populated context'); @@ -29,7 +29,7 @@ assert.throws(function() { // Issue GH-1140: console.error('test runInContext signature'); -var gh1140Exception; +let gh1140Exception; try { vm.runInContext('throw new Error()', context, 'expected-filename.js'); } catch (e) { @@ -55,7 +55,7 @@ script.runInNewContext({ require: require }); // Issue GH-7529 script = vm.createScript('delete b'); -var ctx = {}; +let ctx = {}; Object.defineProperty(ctx, 'b', { configurable: false }); ctx = vm.createContext(ctx); assert.equal(script.runInContext(ctx), false); diff --git a/test/parallel/test-vm-create-and-run-in-context.js b/test/parallel/test-vm-create-and-run-in-context.js index b40491bb611260..a0026102b578f8 100644 --- a/test/parallel/test-vm-create-and-run-in-context.js +++ b/test/parallel/test-vm-create-and-run-in-context.js @@ -6,8 +6,8 @@ const assert = require('assert'); const vm = require('vm'); console.error('run in a new empty context'); -var context = vm.createContext(); -var result = vm.runInContext('"passed";', context); +let context = vm.createContext(); +let result = vm.runInContext('"passed";', context); assert.equal('passed', result); console.error('create a new pre-populated context'); @@ -22,7 +22,7 @@ assert.equal('lala', context.thing); // https://github.com/nodejs/node/issues/5768 console.error('run in contextified sandbox without referencing the context'); -var sandbox = {x: 1}; +const sandbox = {x: 1}; vm.createContext(sandbox); global.gc(); vm.runInContext('x = 2', sandbox); diff --git a/test/parallel/test-vm-create-context-accessors.js b/test/parallel/test-vm-create-context-accessors.js index 3870b68247d480..27d7e6d7fc0274 100644 --- a/test/parallel/test-vm-create-context-accessors.js +++ b/test/parallel/test-vm-create-context-accessors.js @@ -3,7 +3,7 @@ require('../common'); const assert = require('assert'); const vm = require('vm'); -var ctx = {}; +let ctx = {}; Object.defineProperty(ctx, 'getter', { get: function() { @@ -11,7 +11,7 @@ Object.defineProperty(ctx, 'getter', { } }); -var val; +let val; Object.defineProperty(ctx, 'setter', { set: function(_val) { val = _val; @@ -23,6 +23,6 @@ Object.defineProperty(ctx, 'setter', { ctx = vm.createContext(ctx); -var result = vm.runInContext('setter = "test";[getter,setter]', ctx); +const result = vm.runInContext('setter = "test";[getter,setter]', ctx); assert.strictEqual(result[0], 'ok'); assert.strictEqual(result[1], 'ok=test'); diff --git a/test/parallel/test-vm-create-context-arg.js b/test/parallel/test-vm-create-context-arg.js index 76634e5befc3cd..91bbbc3b7793bc 100644 --- a/test/parallel/test-vm-create-context-arg.js +++ b/test/parallel/test-vm-create-context-arg.js @@ -13,7 +13,7 @@ assert.doesNotThrow(function() { }); assert.doesNotThrow(function() { - var sandbox = {}; + const sandbox = {}; vm.createContext(sandbox); vm.createContext(sandbox); }); diff --git a/test/parallel/test-vm-create-context-circular-reference.js b/test/parallel/test-vm-create-context-circular-reference.js index e6c1ab8b8566f0..13680c4c4e11ef 100644 --- a/test/parallel/test-vm-create-context-circular-reference.js +++ b/test/parallel/test-vm-create-context-circular-reference.js @@ -3,7 +3,7 @@ require('../common'); const assert = require('assert'); const vm = require('vm'); -var sbx = {}; +let sbx = {}; sbx.window = sbx; sbx = vm.createContext(sbx); diff --git a/test/parallel/test-vm-cross-context.js b/test/parallel/test-vm-cross-context.js index c1d115b50beffa..bafb32accb6a0e 100644 --- a/test/parallel/test-vm-cross-context.js +++ b/test/parallel/test-vm-cross-context.js @@ -3,7 +3,7 @@ require('../common'); const assert = require('assert'); const vm = require('vm'); -var ctx = vm.createContext(global); +const ctx = vm.createContext(global); assert.doesNotThrow(function() { vm.runInContext('!function() { var x = console.log; }()', ctx); diff --git a/test/parallel/test-vm-function-declaration.js b/test/parallel/test-vm-function-declaration.js index 976313b5f66b9f..9f27723a0421a9 100644 --- a/test/parallel/test-vm-function-declaration.js +++ b/test/parallel/test-vm-function-declaration.js @@ -3,10 +3,10 @@ require('../common'); const assert = require('assert'); const vm = require('vm'); -var o = vm.createContext({ console: console }); +const o = vm.createContext({ console: console }); // This triggers the setter callback in node_contextify.cc -var code = 'var a = function() {};\n'; +let code = 'var a = function() {};\n'; // but this does not, since function decls are defineProperties, // not simple sets. @@ -16,7 +16,7 @@ code += 'function b(){}\n'; // we are getting the global function, and not some other thing code += '(function(){return this})().b;\n'; -var res = vm.runInContext(code, o, 'test'); +const res = vm.runInContext(code, o, 'test'); assert.equal(typeof res, 'function', 'result should be function'); assert.equal(res.name, 'b', 'res should be named b'); diff --git a/test/parallel/test-vm-global-define-property.js b/test/parallel/test-vm-global-define-property.js index 31842ced2ab19c..62a714615ddc31 100644 --- a/test/parallel/test-vm-global-define-property.js +++ b/test/parallel/test-vm-global-define-property.js @@ -4,7 +4,7 @@ const assert = require('assert'); const vm = require('vm'); -var code = +const code = 'Object.defineProperty(this, "f", {\n' + ' get: function() { return x; },\n' + ' set: function(k) { x = k; },\n' + @@ -14,10 +14,10 @@ var code = 'g = f;\n' + 'f;\n'; -var x = {}; -var o = vm.createContext({ console: console, x: x }); +const x = {}; +const o = vm.createContext({ console: console, x: x }); -var res = vm.runInContext(code, o, 'test'); +const res = vm.runInContext(code, o, 'test'); assert(res); assert.equal(typeof res, 'object'); diff --git a/test/parallel/test-vm-global-identity.js b/test/parallel/test-vm-global-identity.js index 876318aecec7d9..ae9fd71b3109ee 100644 --- a/test/parallel/test-vm-global-identity.js +++ b/test/parallel/test-vm-global-identity.js @@ -3,9 +3,9 @@ require('../common'); const assert = require('assert'); const vm = require('vm'); -var ctx = vm.createContext(); +const ctx = vm.createContext(); ctx.window = ctx; -var thisVal = vm.runInContext('this;', ctx); -var windowVal = vm.runInContext('window;', ctx); +const thisVal = vm.runInContext('this;', ctx); +const windowVal = vm.runInContext('window;', ctx); assert.strictEqual(thisVal, windowVal); diff --git a/test/parallel/test-vm-harmony-symbols.js b/test/parallel/test-vm-harmony-symbols.js index eeacdaed184562..80c1a2127f918c 100644 --- a/test/parallel/test-vm-harmony-symbols.js +++ b/test/parallel/test-vm-harmony-symbols.js @@ -4,7 +4,7 @@ const assert = require('assert'); const vm = require('vm'); // The sandbox should have its own Symbol constructor. -var sandbox = {}; +let sandbox = {}; vm.runInNewContext('this.Symbol = Symbol', sandbox); assert.strictEqual(typeof sandbox.Symbol, 'function'); assert.notStrictEqual(sandbox.Symbol, Symbol); diff --git a/test/parallel/test-vm-is-context.js b/test/parallel/test-vm-is-context.js index 474c0686a870eb..e58b896fccaa43 100644 --- a/test/parallel/test-vm-is-context.js +++ b/test/parallel/test-vm-is-context.js @@ -13,6 +13,6 @@ assert.strictEqual(vm.isContext([]), false); assert.strictEqual(vm.isContext(vm.createContext()), true); assert.strictEqual(vm.isContext(vm.createContext([])), true); -var sandbox = { foo: 'bar' }; +const sandbox = { foo: 'bar' }; vm.createContext(sandbox); assert.strictEqual(vm.isContext(sandbox), true); diff --git a/test/parallel/test-vm-new-script-new-context.js b/test/parallel/test-vm-new-script-new-context.js index 2af8f05f1c5236..a02627668f6db7 100644 --- a/test/parallel/test-vm-new-script-new-context.js +++ b/test/parallel/test-vm-new-script-new-context.js @@ -6,7 +6,7 @@ const Script = require('vm').Script; common.globalCheck = false; console.error('run a string'); -var script = new Script('\'passed\';'); +let script = new Script('\'passed\';'); console.error('script created'); const result1 = script.runInNewContext(); const result2 = script.runInNewContext(); @@ -41,7 +41,7 @@ global.foo = 2; global.obj = { foo: 0, baz: 3 }; script = new Script(global.code); /* eslint-disable no-unused-vars */ -var baz = script.runInNewContext(global.obj); +const baz = script.runInNewContext(global.obj); /* eslint-enable no-unused-vars */ assert.equal(1, global.obj.foo); assert.equal(2, global.obj.bar); @@ -55,7 +55,7 @@ assert.equal(global.foo, 100); console.error('modify an object by reference'); script = new Script('f.a = 2'); -var f = { a: 1 }; +const f = { a: 1 }; script.runInNewContext({ f: f }); assert.equal(f.a, 2); diff --git a/test/parallel/test-vm-new-script-this-context.js b/test/parallel/test-vm-new-script-this-context.js index d225fb0d4025d0..fb7e2719855174 100644 --- a/test/parallel/test-vm-new-script-this-context.js +++ b/test/parallel/test-vm-new-script-this-context.js @@ -6,7 +6,7 @@ const Script = require('vm').Script; common.globalCheck = false; console.error('run a string'); -var script = new Script('\'passed\';'); +let script = new Script('\'passed\';'); const result = script.runInThisContext(script); assert.equal('passed', result); diff --git a/test/parallel/test-vm-proxies.js b/test/parallel/test-vm-proxies.js index 6532345336fa19..25e16e8f5ccc55 100644 --- a/test/parallel/test-vm-proxies.js +++ b/test/parallel/test-vm-proxies.js @@ -6,7 +6,7 @@ const vm = require('vm'); // src/node_contextify.cc filters out the Proxy object from the parent // context. Make sure that the new context has a Proxy object of its own. -var sandbox = {}; +let sandbox = {}; vm.runInNewContext('this.Proxy = Proxy', sandbox); assert.strictEqual(typeof sandbox.Proxy, 'function'); assert.notStrictEqual(sandbox.Proxy, Proxy); diff --git a/test/parallel/test-vm-run-in-new-context.js b/test/parallel/test-vm-run-in-new-context.js index 956e02306d4fb8..b00e5a973e0d25 100644 --- a/test/parallel/test-vm-run-in-new-context.js +++ b/test/parallel/test-vm-run-in-new-context.js @@ -30,7 +30,7 @@ global.code = 'foo = 1;' + global.foo = 2; global.obj = { foo: 0, baz: 3 }; /* eslint-disable no-unused-vars */ -var baz = vm.runInNewContext(global.code, global.obj); +const baz = vm.runInNewContext(global.code, global.obj); /* eslint-enable no-unused-vars */ assert.equal(1, global.obj.foo); assert.equal(2, global.obj.bar); @@ -42,12 +42,12 @@ vm.runInNewContext('f()', { f: changeFoo }); assert.equal(global.foo, 100); console.error('modify an object by reference'); -var f = { a: 1 }; +const f = { a: 1 }; vm.runInNewContext('f.a = 2', { f: f }); assert.equal(f.a, 2); console.error('use function in context without referencing context'); -var fn = vm.runInNewContext('(function() { obj.p = {}; })', { obj: {} }); +const fn = vm.runInNewContext('(function() { obj.p = {}; })', { obj: {} }); global.gc(); fn(); // Should not crash diff --git a/test/parallel/test-vm-static-this.js b/test/parallel/test-vm-static-this.js index 0f578ac5f8046c..076f81dbf6ff15 100644 --- a/test/parallel/test-vm-static-this.js +++ b/test/parallel/test-vm-static-this.js @@ -6,7 +6,7 @@ const vm = require('vm'); common.globalCheck = false; // Run a string -var result = vm.runInThisContext('\'passed\';'); +const result = vm.runInThisContext('\'passed\';'); assert.strictEqual('passed', result); // thrown error @@ -20,13 +20,14 @@ assert.strictEqual(2, global.hello); // pass values -var code = 'foo = 1;' + - 'bar = 2;' + - 'if (typeof baz !== \'undefined\') throw new Error(\'test fail\');'; +const code = 'foo = 1;' + + 'bar = 2;' + + 'if (typeof baz !== \'undefined\')' + + 'throw new Error(\'test fail\');'; global.foo = 2; global.obj = { foo: 0, baz: 3 }; /* eslint-disable no-unused-vars */ -var baz = vm.runInThisContext(code); +const baz = vm.runInThisContext(code); /* eslint-enable no-unused-vars */ assert.strictEqual(0, global.obj.foo); assert.strictEqual(2, global.bar); diff --git a/test/parallel/test-vm-syntax-error-message.js b/test/parallel/test-vm-syntax-error-message.js index b4c101d580c4af..1a97393d6d97a7 100644 --- a/test/parallel/test-vm-syntax-error-message.js +++ b/test/parallel/test-vm-syntax-error-message.js @@ -3,7 +3,7 @@ require('../common'); const assert = require('assert'); const child_process = require('child_process'); -var p = child_process.spawn(process.execPath, [ +const p = child_process.spawn(process.execPath, [ '-e', 'vm = require("vm");' + 'context = vm.createContext({});' + @@ -15,7 +15,7 @@ p.stderr.on('data', function(data) { assert(false, 'Unexpected stderr data: ' + data); }); -var output = ''; +let output = ''; p.stdout.on('data', function(data) { output += data; diff --git a/test/parallel/test-vm-timeout.js b/test/parallel/test-vm-timeout.js index 5b78c891e876e1..5260ca7dc28572 100644 --- a/test/parallel/test-vm-timeout.js +++ b/test/parallel/test-vm-timeout.js @@ -23,7 +23,7 @@ vm.runInThisContext('', { timeout: 1000 }); // Test 5: Nested vm timeouts, inner timeout propagates out assert.throws(function() { - var context = { + const context = { log: console.log, runInVM: function(timeout) { vm.runInNewContext('while(true) {}', context, { timeout: timeout }); diff --git a/test/parallel/test-whatwg-url-searchparams.js b/test/parallel/test-whatwg-url-searchparams.js index 9a9fbb0452155d..8b9e65123d9506 100644 --- a/test/parallel/test-whatwg-url-searchparams.js +++ b/test/parallel/test-whatwg-url-searchparams.js @@ -31,7 +31,7 @@ assert.strictEqual(m.search, `?${serialized}`); assert.strictEqual(sp[Symbol.iterator], sp.entries); -var key, val, n = 0; +let key, val, n = 0; for ([key, val] of sp) { assert.strictEqual(key, 'a'); assert.strictEqual(val, String(values[n++])); diff --git a/test/parallel/test-whatwg-url-setters.js b/test/parallel/test-whatwg-url-setters.js index 236737e18177fe..dfaeb6e4ac2fd0 100644 --- a/test/parallel/test-whatwg-url-setters.js +++ b/test/parallel/test-whatwg-url-setters.js @@ -17,7 +17,7 @@ for (const attr in attrs) { if (attr === 'comment') continue; const tests = attrs[attr]; - var n = 0; + let n = 0; for (const test of tests) { if (test.skip) continue; n++; diff --git a/test/parallel/test-writedouble.js b/test/parallel/test-writedouble.js index 107bf521342ef3..935f9e7ae08ffd 100644 --- a/test/parallel/test-writedouble.js +++ b/test/parallel/test-writedouble.js @@ -6,7 +6,7 @@ require('../common'); const assert = require('assert'); function test(clazz) { - var buffer = new clazz(16); + const buffer = new clazz(16); buffer.writeDoubleBE(2.225073858507201e-308, 0); buffer.writeDoubleLE(2.225073858507201e-308, 8); diff --git a/test/parallel/test-writefloat.js b/test/parallel/test-writefloat.js index 2f76dd57c7b077..113e97c6d333b7 100644 --- a/test/parallel/test-writefloat.js +++ b/test/parallel/test-writefloat.js @@ -6,7 +6,7 @@ require('../common'); const assert = require('assert'); function test(clazz) { - var buffer = new clazz(8); + const buffer = new clazz(8); buffer.writeFloatBE(1, 0); buffer.writeFloatLE(1, 4); diff --git a/test/parallel/test-writeint.js b/test/parallel/test-writeint.js index 9fce2bc410e1be..838b1ce4798b75 100644 --- a/test/parallel/test-writeint.js +++ b/test/parallel/test-writeint.js @@ -7,7 +7,7 @@ const assert = require('assert'); const errorOutOfBounds = /^TypeError: "value" argument is out of bounds$/; function test8(clazz) { - var buffer = new clazz(2); + const buffer = new clazz(2); buffer.writeInt8(0x23, 0); buffer.writeInt8(-5, 1); @@ -39,7 +39,7 @@ function test8(clazz) { function test16(clazz) { - var buffer = new clazz(6); + const buffer = new clazz(6); buffer.writeInt16BE(0x0023, 0); buffer.writeInt16LE(0x0023, 2); @@ -92,7 +92,7 @@ function test16(clazz) { function test32(clazz) { - var buffer = new clazz(8); + const buffer = new clazz(8); buffer.writeInt32BE(0x23, 0); buffer.writeInt32LE(0x23, 4); diff --git a/test/parallel/test-writeuint.js b/test/parallel/test-writeuint.js index 0cccd4bc150436..bddb954d248633 100644 --- a/test/parallel/test-writeuint.js +++ b/test/parallel/test-writeuint.js @@ -13,7 +13,7 @@ const assert = require('assert'); * - Correctly interpreting values that are beyond the signed range as unsigned */ function test8(clazz) { - var data = new clazz(4); + const data = new clazz(4); data.writeUInt8(23, 0); data.writeUInt8(23, 1); @@ -42,8 +42,8 @@ function test8(clazz) { function test16(clazz) { - var value = 0x2343; - var data = new clazz(4); + let value = 0x2343; + const data = new clazz(4); data.writeUInt16BE(value, 0); assert.equal(0x23, data[0]); @@ -81,8 +81,8 @@ function test16(clazz) { function test32(clazz) { - var data = new clazz(6); - var value = 0xe7f90a6d; + const data = new clazz(6); + const value = 0xe7f90a6d; data.writeUInt32BE(value, 0); assert.equal(0xe7, data[0]); @@ -124,10 +124,10 @@ function test32(clazz) { function testUint(clazz) { const data = new clazz(8); - var val = 1; + let val = 1; // Test 0 to 5 bytes. - for (var i = 0; i <= 5; i++) { + for (let i = 0; i <= 5; i++) { const errmsg = `byteLength: ${i}`; assert.throws(function() { data.writeUIntBE(val, 0, i); diff --git a/test/parallel/test-zerolengthbufferbug.js b/test/parallel/test-zerolengthbufferbug.js index 07113d1e257f65..42e6994e1b6389 100644 --- a/test/parallel/test-zerolengthbufferbug.js +++ b/test/parallel/test-zerolengthbufferbug.js @@ -4,8 +4,8 @@ const common = require('../common'); const http = require('http'); -var server = http.createServer(function(req, res) { - var buffer = Buffer.alloc(0); +const server = http.createServer(function(req, res) { + const buffer = Buffer.alloc(0); // FIXME: WTF gjslint want this? res.writeHead(200, {'Content-Type': 'text/html', 'Content-Length': buffer.length}); diff --git a/test/parallel/test-zlib-convenience-methods.js b/test/parallel/test-zlib-convenience-methods.js index 3aac0142b55d66..b67b65d7d0b689 100644 --- a/test/parallel/test-zlib-convenience-methods.js +++ b/test/parallel/test-zlib-convenience-methods.js @@ -5,7 +5,7 @@ require('../common'); const assert = require('assert'); const zlib = require('zlib'); -var hadRun = 0; +let hadRun = 0; const expect = 'blahblahblahblahblahblah'; const opts = { @@ -38,7 +38,7 @@ const opts = { }); }); - var result = zlib[method[0] + 'Sync'](expect, opts); + let result = zlib[method[0] + 'Sync'](expect, opts); result = zlib[method[1] + 'Sync'](result, opts); assert.equal(result, expect, 'Should get original string after ' + diff --git a/test/parallel/test-zlib-flush-drain.js b/test/parallel/test-zlib-flush-drain.js index 45cca584858322..afa4194ac6d453 100644 --- a/test/parallel/test-zlib-flush-drain.js +++ b/test/parallel/test-zlib-flush-drain.js @@ -13,8 +13,8 @@ const opts = { const deflater = zlib.createDeflate(opts); // shim deflater.flush so we can count times executed -var flushCount = 0; -var drainCount = 0; +let flushCount = 0; +let drainCount = 0; const flush = deflater.flush; deflater.flush = function(kind, callback) { @@ -26,7 +26,7 @@ deflater.write(bigData); const ws = deflater._writableState; const beforeFlush = ws.needDrain; -var afterFlush = ws.needDrain; +let afterFlush = ws.needDrain; deflater.flush(function(err) { afterFlush = ws.needDrain; diff --git a/test/parallel/test-zlib-flush.js b/test/parallel/test-zlib-flush.js index 7f0021434f4c18..0eec5da7dd835e 100644 --- a/test/parallel/test-zlib-flush.js +++ b/test/parallel/test-zlib-flush.js @@ -22,7 +22,8 @@ deflater.write(chunk, function() { deflater.flush(zlib.constants.Z_NO_FLUSH, function() { actualNone = deflater.read(); deflater.flush(function() { - var bufs = [], buf; + const bufs = []; + let buf; while (buf = deflater.read()) bufs.push(buf); actualFull = Buffer.concat(bufs); diff --git a/test/parallel/test-zlib-from-gzip.js b/test/parallel/test-zlib-from-gzip.js index 3739d8f9b48b28..3c7e96cef92a0a 100644 --- a/test/parallel/test-zlib-from-gzip.js +++ b/test/parallel/test-zlib-from-gzip.js @@ -24,7 +24,7 @@ inp.pipe(gunzip).pipe(out); out.on('close', function() { const actual = fs.readFileSync(outputFile); assert.equal(actual.length, expect.length, 'length should match'); - for (var i = 0, l = actual.length; i < l; i++) { + for (let i = 0, l = actual.length; i < l; i++) { assert.equal(actual[i], expect[i], 'byte[' + i + ']'); } }); diff --git a/test/parallel/test-zlib-from-string.js b/test/parallel/test-zlib-from-string.js index f3b8426eb4d862..0f885ac80ecbe6 100644 --- a/test/parallel/test-zlib-from-string.js +++ b/test/parallel/test-zlib-from-string.js @@ -51,7 +51,7 @@ zlib.gzip(inputString, function(err, buffer) { }); }); -var buffer = Buffer.from(expectedBase64Deflate, 'base64'); +let buffer = Buffer.from(expectedBase64Deflate, 'base64'); zlib.unzip(buffer, function(err, buffer) { assert.equal(buffer.toString(), inputString, 'decoded inflated string should match'); diff --git a/test/parallel/test-zlib-invalid-input.js b/test/parallel/test-zlib-invalid-input.js index eb9cd334c11b84..7b0e1fcaae8ce6 100644 --- a/test/parallel/test-zlib-invalid-input.js +++ b/test/parallel/test-zlib-invalid-input.js @@ -24,7 +24,7 @@ const unzips = [ zlib.Unzip(), zlib.Gunzip(), zlib.Inflate(), zlib.InflateRaw() ]; -var hadError = []; +const hadError = []; unzips.forEach(function(uz, i) { console.error('Error for ' + uz.constructor.name); uz.on('error', function(er) { diff --git a/test/parallel/test-zlib-params.js b/test/parallel/test-zlib-params.js index 0dce05be4d40f6..40799637ecdac7 100644 --- a/test/parallel/test-zlib-params.js +++ b/test/parallel/test-zlib-params.js @@ -21,7 +21,7 @@ deflater.write(chunk1, function() { while (deflater.read()); deflater.end(chunk2, function() { const bufs = []; - var buf; + let buf; while (buf = deflater.read()) bufs.push(buf); actual = Buffer.concat(bufs); diff --git a/test/parallel/test-zlib-random-byte-pipes.js b/test/parallel/test-zlib-random-byte-pipes.js index 6037703f7bf2ca..83855ebd1f2c0a 100644 --- a/test/parallel/test-zlib-random-byte-pipes.js +++ b/test/parallel/test-zlib-random-byte-pipes.js @@ -72,14 +72,14 @@ RandomReadStream.prototype._process = function() { // figure out how many bytes to output // if finished, then just emit end. - var block = this._opt.block; + let block = this._opt.block; const jitter = this._opt.jitter; if (jitter) { block += Math.ceil(Math.random() * jitter - (jitter / 2)); } block = Math.min(block, this._remaining); const buf = Buffer.allocUnsafe(block); - for (var i = 0; i < block; i++) { + for (let i = 0; i < block; i++) { buf[i] = Math.random() * 256; } @@ -129,10 +129,10 @@ HashStream.prototype.end = function(c) { }; -var inp = new RandomReadStream({ total: 1024, block: 256, jitter: 16 }); -var out = new HashStream(); -var gzip = zlib.createGzip(); -var gunz = zlib.createGunzip(); +const inp = new RandomReadStream({ total: 1024, block: 256, jitter: 16 }); +const out = new HashStream(); +const gzip = zlib.createGzip(); +const gunz = zlib.createGunzip(); inp.pipe(gzip).pipe(gunz).pipe(out); diff --git a/test/parallel/test-zlib-write-after-flush.js b/test/parallel/test-zlib-write-after-flush.js index 89edaf93043d88..342c9143ba4643 100644 --- a/test/parallel/test-zlib-write-after-flush.js +++ b/test/parallel/test-zlib-write-after-flush.js @@ -8,7 +8,7 @@ const gunz = zlib.createUnzip(); gzip.pipe(gunz); -var output = ''; +let output = ''; const input = 'A line of data\n'; gunz.setEncoding('utf8'); gunz.on('data', function(c) { diff --git a/test/parallel/test-zlib-zero-byte.js b/test/parallel/test-zlib-zero-byte.js index ca58d06ff272ba..cd4cf41f98ac07 100644 --- a/test/parallel/test-zlib-zero-byte.js +++ b/test/parallel/test-zlib-zero-byte.js @@ -5,7 +5,7 @@ const assert = require('assert'); const zlib = require('zlib'); const gz = zlib.Gzip(); const emptyBuffer = Buffer.alloc(0); -var received = 0; +let received = 0; gz.on('data', function(c) { received += c.length; }); diff --git a/test/parallel/test-zlib.js b/test/parallel/test-zlib.js index 54a4bc473631a0..fdd5d0a9400f25 100644 --- a/test/parallel/test-zlib.js +++ b/test/parallel/test-zlib.js @@ -7,7 +7,7 @@ const fs = require('fs'); const util = require('util'); const stream = require('stream'); -var zlibPairs = [ +let zlibPairs = [ [zlib.Deflate, zlib.Inflate], [zlib.Gzip, zlib.Gunzip], [zlib.Deflate, zlib.Unzip], @@ -16,18 +16,18 @@ var zlibPairs = [ ]; // how fast to trickle through the slowstream -var trickle = [128, 1024, 1024 * 1024]; +let trickle = [128, 1024, 1024 * 1024]; // tunable options for zlib classes. // several different chunk sizes -var chunkSize = [128, 1024, 1024 * 16, 1024 * 1024]; +let chunkSize = [128, 1024, 1024 * 16, 1024 * 1024]; // this is every possible value. -var level = [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; -var windowBits = [8, 9, 10, 11, 12, 13, 14, 15]; -var memLevel = [1, 2, 3, 4, 5, 6, 7, 8, 9]; -var strategy = [0, 1, 2, 3, 4]; +let level = [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; +let windowBits = [8, 9, 10, 11, 12, 13, 14, 15]; +let memLevel = [1, 2, 3, 4, 5, 6, 7, 8, 9]; +let strategy = [0, 1, 2, 3, 4]; // it's nice in theory to test every combination, but it // takes WAY too long. Maybe a pummel test could do this? @@ -40,7 +40,7 @@ if (!process.env.PUMMEL) { strategy = [0]; } -var testFiles = ['person.jpg', 'elipses.txt', 'empty.txt']; +let testFiles = ['person.jpg', 'elipses.txt', 'empty.txt']; if (process.env.FAST) { zlibPairs = [[zlib.Gzip, zlib.Unzip]]; @@ -72,8 +72,8 @@ BufferStream.prototype.write = function(c) { BufferStream.prototype.end = function(c) { if (c) this.write(c); // flatten - var buf = Buffer.allocUnsafe(this.length); - var i = 0; + const buf = Buffer.allocUnsafe(this.length); + let i = 0; this.chunks.forEach(function(c) { c.copy(buf, i); i += c.length; @@ -108,8 +108,8 @@ SlowStream.prototype.resume = function() { this.ended = true; return this.emit('end'); } - var end = Math.min(this.offset + this.trickle, this.length); - var c = this.chunk.slice(this.offset, end); + const end = Math.min(this.offset + this.trickle, this.length); + const c = this.chunk.slice(this.offset, end); this.offset += c.length; this.emit('data', c); process.nextTick(emit); @@ -134,12 +134,12 @@ SlowStream.prototype.end = function(chunk) { // for each of the files, make sure that compressing and // decompressing results in the same data, for every combination // of the options set above. -var failures = 0; -var total = 0; -var done = 0; +let failures = 0; +let total = 0; +let done = 0; Object.keys(tests).forEach(function(file) { - var test = tests[file]; + const test = tests[file]; chunkSize.forEach(function(chunkSize) { trickle.forEach(function(trickle) { windowBits.forEach(function(windowBits) { @@ -147,29 +147,30 @@ Object.keys(tests).forEach(function(file) { memLevel.forEach(function(memLevel) { strategy.forEach(function(strategy) { zlibPairs.forEach(function(pair) { - var Def = pair[0]; - var Inf = pair[1]; - var opts = { level: level, - windowBits: windowBits, - memLevel: memLevel, - strategy: strategy }; + const Def = pair[0]; + const Inf = pair[1]; + const opts = { level: level, + windowBits: windowBits, + memLevel: memLevel, + strategy: strategy }; total++; - var def = new Def(opts); - var inf = new Inf(opts); - var ss = new SlowStream(trickle); - var buf = new BufferStream(); + const def = new Def(opts); + const inf = new Inf(opts); + const ss = new SlowStream(trickle); + const buf = new BufferStream(); // verify that the same exact buffer comes out the other end. buf.on('data', function(c) { - var msg = file + ' ' + - chunkSize + ' ' + - JSON.stringify(opts) + ' ' + - Def.name + ' -> ' + Inf.name; - var ok = true; - var testNum = ++done; - for (var i = 0; i < Math.max(c.length, test.length); i++) { + const msg = file + ' ' + + chunkSize + ' ' + + JSON.stringify(opts) + ' ' + + Def.name + ' -> ' + Inf.name; + let ok = true; + const testNum = ++done; + let i; + for (i = 0; i < Math.max(c.length, test.length); i++) { if (c[i] !== test[i]) { ok = false; failures++; diff --git a/test/pseudo-tty/no_dropped_stdio.js b/test/pseudo-tty/no_dropped_stdio.js index 1a20889073ce06..b24d234a38b2b7 100644 --- a/test/pseudo-tty/no_dropped_stdio.js +++ b/test/pseudo-tty/no_dropped_stdio.js @@ -6,7 +6,7 @@ require('../common'); // 1000 bytes wrapped at 50 columns // \n turns into a double-byte character // (48 + {2}) * 20 = 1000 -var out = ('o'.repeat(48) + '\n').repeat(20); +let out = ('o'.repeat(48) + '\n').repeat(20); // Add the remaining 24 bytes and terminate with an 'O'. // This results in 1025 bytes, just enough to overflow the 1kb OS X TTY buffer. out += 'o'.repeat(24) + 'O'; diff --git a/test/pseudo-tty/no_interleaved_stdio.js b/test/pseudo-tty/no_interleaved_stdio.js index 778b2c09583b90..ff3ed8594a0baa 100644 --- a/test/pseudo-tty/no_interleaved_stdio.js +++ b/test/pseudo-tty/no_interleaved_stdio.js @@ -6,7 +6,7 @@ require('../common'); // 1000 bytes wrapped at 50 columns // \n turns into a double-byte character // (48 + {2}) * 20 = 1000 -var out = ('o'.repeat(48) + '\n').repeat(20); +let out = ('o'.repeat(48) + '\n').repeat(20); // Add the remaining 24 bytes and terminate with an 'O'. // This results in 1025 bytes, just enough to overflow the 1kb OS X TTY buffer. out += 'o'.repeat(24) + 'O'; diff --git a/test/pummel/test-abort-fatal-error.js b/test/pummel/test-abort-fatal-error.js index 1fed91d54a6526..d1a8d3daa65e4c 100644 --- a/test/pummel/test-abort-fatal-error.js +++ b/test/pummel/test-abort-fatal-error.js @@ -9,7 +9,7 @@ if (common.isWindows) { const exec = require('child_process').exec; -var cmdline = 'ulimit -c 0; ' + process.execPath; +let cmdline = 'ulimit -c 0; ' + process.execPath; cmdline += ' --max-old-space-size=4 --max-semi-space-size=1'; cmdline += ' -e "a = []; for (i = 0; i < 1e9; i++) { a.push({}) }"'; diff --git a/test/pummel/test-crypto-dh.js b/test/pummel/test-crypto-dh.js index 7656d0ffa92e84..d441e80926df45 100644 --- a/test/pummel/test-crypto-dh.js +++ b/test/pummel/test-crypto-dh.js @@ -18,7 +18,7 @@ assert.throws(function() { crypto.getDiffieHellman('modp1').setPublicKey(''); }); -var hashes = { +const hashes = { modp1: '630e9acd2cc63f7e80d8507624ba60ac0757201a', modp2: '18f7aa964484137f57bca64b21917a385b6a0b60', modp5: 'c0a8eec0c2c8a5ec2f9c26f9661eb339a010ec61', @@ -30,10 +30,10 @@ var hashes = { }; for (const name in hashes) { - var group = crypto.getDiffieHellman(name); - var private_key = group.getPrime('hex'); - var hash1 = hashes[name]; - var hash2 = crypto.createHash('sha1') + const group = crypto.getDiffieHellman(name); + const private_key = group.getPrime('hex'); + const hash1 = hashes[name]; + const hash2 = crypto.createHash('sha1') .update(private_key.toUpperCase()).digest('hex'); assert.equal(hash1, hash2); assert.equal(group.getGenerator('hex'), '02'); @@ -43,11 +43,11 @@ for (const name in hashes) { // modp1 is 768 bits, FIPS requires >= 1024 if (name === 'modp1' && common.hasFipsCrypto) continue; - var group1 = crypto.getDiffieHellman(name); - var group2 = crypto.getDiffieHellman(name); + const group1 = crypto.getDiffieHellman(name); + const group2 = crypto.getDiffieHellman(name); group1.generateKeys(); group2.generateKeys(); - var key1 = group1.computeSecret(group2.getPublicKey()); - var key2 = group2.computeSecret(group1.getPublicKey()); + const key1 = group1.computeSecret(group2.getPublicKey()); + const key2 = group2.computeSecret(group1.getPublicKey()); assert.deepStrictEqual(key1, key2); } diff --git a/test/pummel/test-dh-regr.js b/test/pummel/test-dh-regr.js index 8228332e5dd8e9..5be6abb9a8b29c 100644 --- a/test/pummel/test-dh-regr.js +++ b/test/pummel/test-dh-regr.js @@ -8,9 +8,9 @@ if (!common.hasCrypto) { } const crypto = require('crypto'); -var p = crypto.createDiffieHellman(1024).getPrime(); +const p = crypto.createDiffieHellman(1024).getPrime(); -for (var i = 0; i < 2000; i++) { +for (let i = 0; i < 2000; i++) { const a = crypto.createDiffieHellman(p); const b = crypto.createDiffieHellman(p); diff --git a/test/pummel/test-dtrace-jsstack.js b/test/pummel/test-dtrace-jsstack.js index af9c83bb3ec3c4..d1615a3855af43 100644 --- a/test/pummel/test-dtrace-jsstack.js +++ b/test/pummel/test-dtrace-jsstack.js @@ -11,20 +11,20 @@ if (!common.isSunOS) { /* * Some functions to create a recognizable stack. */ -var frames = [ 'stalloogle', 'bagnoogle', 'doogle' ]; +const frames = [ 'stalloogle', 'bagnoogle', 'doogle' ]; -var stalloogle = function(str) { +const stalloogle = function(str) { global.expected = str; os.loadavg(); }; -var bagnoogle = function(arg0, arg1) { +const bagnoogle = function(arg0, arg1) { stalloogle(arg0 + ' is ' + arg1 + ' except that it is read-only'); }; -var done = false; +let done = false; -var doogle = function() { +const doogle = function() { if (!done) setTimeout(doogle, 10); @@ -38,10 +38,10 @@ const spawn = require('child_process').spawn; * when we call getloadavg() -- with the implicit assumption that our * deepest function is the only caller of os.loadavg(). */ -var dtrace = spawn('dtrace', [ '-qwn', 'syscall::getloadavg:entry/pid == ' + +const dtrace = spawn('dtrace', [ '-qwn', 'syscall::getloadavg:entry/pid == ' + process.pid + '/{ustack(100, 8192); exit(0); }' ]); -var output = ''; +let output = ''; dtrace.stderr.on('data', function(data) { console.log('dtrace: ' + data); @@ -59,17 +59,17 @@ dtrace.on('exit', function(code) { done = true; - var sentinel = '(anon) as '; - var lines = output.split('\n'); + const sentinel = '(anon) as '; + const lines = output.split('\n'); - for (var i = 0; i < lines.length; i++) { - var line = lines[i]; + for (let i = 0; i < lines.length; i++) { + const line = lines[i]; if (line.indexOf(sentinel) === -1 || frames.length === 0) continue; - var frame = line.substr(line.indexOf(sentinel) + sentinel.length); - var top = frames.shift(); + const frame = line.substr(line.indexOf(sentinel) + sentinel.length); + const top = frames.shift(); assert.equal(frame.indexOf(top), 0, 'unexpected frame where ' + top + ' was expected'); diff --git a/test/pummel/test-exec.js b/test/pummel/test-exec.js index eee3d9286832b2..131b214fc53f42 100644 --- a/test/pummel/test-exec.js +++ b/test/pummel/test-exec.js @@ -3,7 +3,7 @@ const common = require('../common'); const assert = require('assert'); const exec = require('child_process').exec; -var SLEEP3_COMMAND; +let SLEEP3_COMMAND; if (!common.isWindows) { // Unix. SLEEP3_COMMAND = 'sleep 3'; @@ -14,8 +14,8 @@ if (!common.isWindows) { } -var success_count = 0; -var error_count = 0; +let success_count = 0; +let error_count = 0; exec( @@ -55,9 +55,9 @@ exec('thisisnotavalidcommand', function(err, stdout, stderr) { }); -var sleeperStart = new Date(); +const sleeperStart = new Date(); exec(SLEEP3_COMMAND, { timeout: 50 }, function(err, stdout, stderr) { - var diff = (new Date()) - sleeperStart; + const diff = (new Date()) - sleeperStart; console.log('\'sleep 3\' with timeout 50 took %d ms', diff); assert.ok(diff < 500); assert.ok(err); @@ -68,8 +68,8 @@ exec(SLEEP3_COMMAND, { timeout: 50 }, function(err, stdout, stderr) { }); -var startSleep3 = new Date(); -var killMeTwice = exec(SLEEP3_COMMAND, {timeout: 1000}, killMeTwiceCallback); +const startSleep3 = new Date(); +const killMeTwice = exec(SLEEP3_COMMAND, {timeout: 1000}, killMeTwiceCallback); process.nextTick(function() { console.log('kill pid %d', killMeTwice.pid); @@ -81,7 +81,7 @@ process.nextTick(function() { }); function killMeTwiceCallback(err, stdout, stderr) { - var diff = (new Date()) - startSleep3; + const diff = (new Date()) - startSleep3; // We should have already killed this process. Assert that the timeout still // works and that we are getting the proper callback parameters. assert.ok(err); diff --git a/test/pummel/test-fs-watch-file-slow.js b/test/pummel/test-fs-watch-file-slow.js index e64e00b32fa602..78c36152ecd315 100644 --- a/test/pummel/test-fs-watch-file-slow.js +++ b/test/pummel/test-fs-watch-file-slow.js @@ -4,10 +4,10 @@ const assert = require('assert'); const path = require('path'); const fs = require('fs'); -var FILENAME = path.join(common.tmpDir, 'watch-me'); -var TIMEOUT = 1300; +const FILENAME = path.join(common.tmpDir, 'watch-me'); +const TIMEOUT = 1300; -var nevents = 0; +let nevents = 0; try { fs.unlinkSync(FILENAME); diff --git a/test/pummel/test-fs-watch-file.js b/test/pummel/test-fs-watch-file.js index 98199d1e841f4b..7713fe74ed99aa 100644 --- a/test/pummel/test-fs-watch-file.js +++ b/test/pummel/test-fs-watch-file.js @@ -4,23 +4,23 @@ const assert = require('assert'); const path = require('path'); const fs = require('fs'); -var watchSeenOne = 0; -var watchSeenTwo = 0; -var watchSeenThree = 0; -var watchSeenFour = 0; +let watchSeenOne = 0; +let watchSeenTwo = 0; +let watchSeenThree = 0; +let watchSeenFour = 0; -var testDir = common.tmpDir; +const testDir = common.tmpDir; -var filenameOne = 'watch.txt'; -var filepathOne = path.join(testDir, filenameOne); +const filenameOne = 'watch.txt'; +const filepathOne = path.join(testDir, filenameOne); -var filenameTwo = 'hasOwnProperty'; -var filepathTwo = filenameTwo; -var filepathTwoAbs = path.join(testDir, filenameTwo); +const filenameTwo = 'hasOwnProperty'; +const filepathTwo = filenameTwo; +const filepathTwoAbs = path.join(testDir, filenameTwo); -var filenameThree = 'charm'; // because the third time is +const filenameThree = 'charm'; // because the third time is -var filenameFour = 'get'; +const filenameFour = 'get'; process.on('exit', function() { fs.unlinkSync(filepathOne); diff --git a/test/pummel/test-fs-watch-non-recursive.js b/test/pummel/test-fs-watch-non-recursive.js index 7b40ef75accc43..b7c19b9c360818 100644 --- a/test/pummel/test-fs-watch-non-recursive.js +++ b/test/pummel/test-fs-watch-non-recursive.js @@ -3,9 +3,9 @@ const common = require('../common'); const path = require('path'); const fs = require('fs'); -var testDir = common.tmpDir; -var testsubdir = path.join(testDir, 'testsubdir'); -var filepath = path.join(testsubdir, 'watch.txt'); +const testDir = common.tmpDir; +const testsubdir = path.join(testDir, 'testsubdir'); +const filepath = path.join(testsubdir, 'watch.txt'); function cleanup() { try { fs.unlinkSync(filepath); } catch (e) { } @@ -18,7 +18,7 @@ try { fs.mkdirSync(testsubdir, 0o700); } catch (e) {} // Need a grace period, else the mkdirSync() above fires off an event. setTimeout(function() { - var watcher = fs.watch(testDir, { persistent: true }, common.fail); + const watcher = fs.watch(testDir, { persistent: true }, common.fail); setTimeout(function() { fs.writeFileSync(filepath, 'test'); }, 100); diff --git a/test/pummel/test-http-client-reconnect-bug.js b/test/pummel/test-http-client-reconnect-bug.js index 395a538178fe79..98d21c5cba7bc5 100644 --- a/test/pummel/test-http-client-reconnect-bug.js +++ b/test/pummel/test-http-client-reconnect-bug.js @@ -3,17 +3,17 @@ const common = require('../common'); const net = require('net'); const http = require('http'); -var server = net.createServer(function(socket) { +const server = net.createServer(function(socket) { socket.end(); }); server.on('listening', common.mustCall(function() { - var client = http.createClient(common.PORT); + const client = http.createClient(common.PORT); client.on('error', common.mustCall(function(err) {})); client.on('end', common.mustCall(function() {})); - var request = client.request('GET', '/', {'host': 'localhost'}); + const request = client.request('GET', '/', {'host': 'localhost'}); request.end(); request.on('response', function(response) { console.log('STATUS: ' + response.statusCode); diff --git a/test/pummel/test-http-many-keep-alive-connections.js b/test/pummel/test-http-many-keep-alive-connections.js index a7654f4524835c..e465c02a90161c 100644 --- a/test/pummel/test-http-many-keep-alive-connections.js +++ b/test/pummel/test-http-many-keep-alive-connections.js @@ -3,12 +3,12 @@ const common = require('../common'); const assert = require('assert'); const http = require('http'); -var expected = 10000; -var responses = 0; -var requests = 0; -var connection; +const expected = 10000; +let responses = 0; +let requests = 0; +let connection; -var server = http.Server(function(req, res) { +const server = http.Server(function(req, res) { requests++; assert.equal(req.connection, connection); res.writeHead(200); @@ -20,7 +20,7 @@ server.once('connection', function(c) { }); server.listen(common.PORT, function connect() { - var request = http.get({ + const request = http.get({ port: common.PORT, path: '/', headers: { diff --git a/test/pummel/test-http-upload-timeout.js b/test/pummel/test-http-upload-timeout.js index 15bc267ff61947..da91ab3f0909e7 100644 --- a/test/pummel/test-http-upload-timeout.js +++ b/test/pummel/test-http-upload-timeout.js @@ -24,18 +24,18 @@ server.on('request', function(req, res) { }); server.listen(common.PORT, '127.0.0.1', function() { - for (var i = 0; i < 10; i++) { + for (let i = 0; i < 10; i++) { connections++; setTimeout(function() { - var request = http.request({ + const request = http.request({ port: common.PORT, method: 'POST', path: '/' }); function ping() { - var nextPing = (Math.random() * 900).toFixed(); + const nextPing = (Math.random() * 900).toFixed(); if (nextPing > 600) { request.end(); return; diff --git a/test/pummel/test-https-ci-reneg-attack.js b/test/pummel/test-https-ci-reneg-attack.js index 61e60c2673ed60..850e0949c4a64a 100644 --- a/test/pummel/test-https-ci-reneg-attack.js +++ b/test/pummel/test-https-ci-reneg-attack.js @@ -18,7 +18,7 @@ if (!common.opensslCli) { } // renegotiation limits to test -var LIMITS = [0, 1, 2, 3, 5, 10, 16]; +const LIMITS = [0, 1, 2, 3, 5, 10, 16]; { let n = 0; @@ -31,15 +31,15 @@ var LIMITS = [0, 1, 2, 3, 5, 10, 16]; } function test(next) { - var options = { + const options = { cert: fs.readFileSync(common.fixturesDir + '/test_cert.pem'), key: fs.readFileSync(common.fixturesDir + '/test_key.pem') }; - var seenError = false; + let seenError = false; - var server = https.createServer(options, function(req, res) { - var conn = req.connection; + const server = https.createServer(options, function(req, res) { + const conn = req.connection; conn.on('error', function(err) { console.error('Caught exception: ' + err); assert(/TLS session renegotiation attack/.test(err)); @@ -50,8 +50,8 @@ function test(next) { }); server.listen(common.PORT, function() { - var args = ('s_client -connect 127.0.0.1:' + common.PORT).split(' '); - var child = spawn(common.opensslCli, args); + const args = ('s_client -connect 127.0.0.1:' + common.PORT).split(' '); + const child = spawn(common.opensslCli, args); //child.stdout.pipe(process.stdout); //child.stderr.pipe(process.stderr); @@ -60,8 +60,8 @@ function test(next) { child.stderr.resume(); // count handshakes, start the attack after the initial handshake is done - var handshakes = 0; - var renegs = 0; + let handshakes = 0; + let renegs = 0; child.stderr.on('data', function(data) { if (seenError) return; @@ -76,7 +76,7 @@ function test(next) { process.nextTick(next); }); - var closed = false; + let closed = false; child.stdin.on('error', function(err) { switch (err.code) { case 'ECONNRESET': diff --git a/test/pummel/test-https-large-response.js b/test/pummel/test-https-large-response.js index 8a3aa022ea2089..39256aa6304b74 100644 --- a/test/pummel/test-https-large-response.js +++ b/test/pummel/test-https-large-response.js @@ -10,16 +10,16 @@ if (!common.hasCrypto) { } const https = require('https'); -var options = { +const options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }; process.stdout.write('build body...'); -var body = 'hello world\n'.repeat(1024 * 1024); +const body = 'hello world\n'.repeat(1024 * 1024); process.stdout.write('done\n'); -var server = https.createServer(options, common.mustCall(function(req, res) { +const server = https.createServer(options, common.mustCall(function(req, res) { console.log('got request'); res.writeHead(200, { 'content-type': 'text/plain' }); res.end(body); @@ -32,7 +32,7 @@ server.listen(common.PORT, common.mustCall(function() { }, common.mustCall(function(res) { console.log('response!'); - var count = 0; + let count = 0; res.on('data', function(d) { process.stdout.write('.'); diff --git a/test/pummel/test-https-no-reader.js b/test/pummel/test-https-no-reader.js index b6cc32c999fa88..a08676277af6ce 100644 --- a/test/pummel/test-https-no-reader.js +++ b/test/pummel/test-https-no-reader.js @@ -12,23 +12,23 @@ const Buffer = require('buffer').Buffer; const fs = require('fs'); const path = require('path'); -var options = { +const options = { key: fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')), cert: fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')) }; -var buf = Buffer.allocUnsafe(1024 * 1024); +const buf = Buffer.allocUnsafe(1024 * 1024); -var server = https.createServer(options, function(req, res) { +const server = https.createServer(options, function(req, res) { res.writeHead(200); - for (var i = 0; i < 50; i++) { + for (let i = 0; i < 50; i++) { res.write(buf); } res.end(); }); server.listen(common.PORT, function() { - var req = https.request({ + const req = https.request({ method: 'POST', port: common.PORT, rejectUnauthorized: false diff --git a/test/pummel/test-net-connect-econnrefused.js b/test/pummel/test-net-connect-econnrefused.js index bd61dabc6bb6a7..30da36d983e4f7 100644 --- a/test/pummel/test-net-connect-econnrefused.js +++ b/test/pummel/test-net-connect-econnrefused.js @@ -5,17 +5,18 @@ const common = require('../common'); const assert = require('assert'); const net = require('net'); -var ROUNDS = 10; -var ATTEMPTS_PER_ROUND = 100; -var rounds = 1; -var reqs = 0; +const ROUNDS = 10; +const ATTEMPTS_PER_ROUND = 100; +let rounds = 1; +let reqs = 0; pummel(); function pummel() { console.log('Round', rounds, '/', ROUNDS); - for (var pending = 0; pending < ATTEMPTS_PER_ROUND; pending++) { + let pending; + for (pending = 0; pending < ATTEMPTS_PER_ROUND; pending++) { net.createConnection(common.PORT).on('error', function(err) { assert.equal(err.code, 'ECONNREFUSED'); if (--pending > 0) return; @@ -34,7 +35,7 @@ function check() { check_called = true; }, 0); } -var check_called = false; +let check_called = false; process.on('exit', function() { assert.equal(rounds, ROUNDS); diff --git a/test/pummel/test-net-connect-memleak.js b/test/pummel/test-net-connect-memleak.js index a5d8ff47eb7e16..f16034e4773510 100644 --- a/test/pummel/test-net-connect-memleak.js +++ b/test/pummel/test-net-connect-memleak.js @@ -12,7 +12,7 @@ assert.strictEqual( ); net.createServer(function() {}).listen(common.PORT); -var before = 0; +let before = 0; { // 2**26 == 64M entries global.gc(); @@ -29,8 +29,8 @@ var before = 0; function done() { global.gc(); - var after = process.memoryUsage().rss; - var reclaimed = (before - after) / 1024; + const after = process.memoryUsage().rss; + const reclaimed = (before - after) / 1024; console.log('%d kB reclaimed', reclaimed); assert(reclaimed > 128 * 1024); // It's around 256 MB on x64. process.exit(); diff --git a/test/pummel/test-net-many-clients.js b/test/pummel/test-net-many-clients.js index db98e55433753e..a92ae033a09a17 100644 --- a/test/pummel/test-net-many-clients.js +++ b/test/pummel/test-net-many-clients.js @@ -4,16 +4,16 @@ const assert = require('assert'); const net = require('net'); // settings -var bytes = 1024 * 40; -var concurrency = 100; -var connections_per_client = 5; +const bytes = 1024 * 40; +const concurrency = 100; +const connections_per_client = 5; // measured -var total_connections = 0; +let total_connections = 0; -var body = 'C'.repeat(bytes); +const body = 'C'.repeat(bytes); -var server = net.createServer(function(c) { +const server = net.createServer(function(c) { console.log('connected'); total_connections++; console.log('#'); @@ -22,7 +22,7 @@ var server = net.createServer(function(c) { }); function runClient(callback) { - var client = net.createConnection(common.PORT); + const client = net.createConnection(common.PORT); client.connections = 0; @@ -66,8 +66,8 @@ function runClient(callback) { } server.listen(common.PORT, function() { - var finished_clients = 0; - for (var i = 0; i < concurrency; i++) { + let finished_clients = 0; + for (let i = 0; i < concurrency; i++) { runClient(function() { if (++finished_clients === concurrency) server.close(); }); diff --git a/test/pummel/test-net-pause.js b/test/pummel/test-net-pause.js index 59749e75fa4307..db426edbe9c507 100644 --- a/test/pummel/test-net-pause.js +++ b/test/pummel/test-net-pause.js @@ -3,10 +3,10 @@ const common = require('../common'); const assert = require('assert'); const net = require('net'); -var N = 200; -var recv = '', chars_recved = 0; +const N = 200; +let recv = '', chars_recved = 0; -var server = net.createServer(function(connection) { +const server = net.createServer(function(connection) { function write(j) { if (j >= N) { connection.end(); @@ -21,7 +21,7 @@ var server = net.createServer(function(connection) { }); server.on('listening', function() { - var client = net.createConnection(common.PORT); + const client = net.createConnection(common.PORT); client.setEncoding('ascii'); client.on('data', function(d) { console.log(d); diff --git a/test/pummel/test-net-pingpong-delay.js b/test/pummel/test-net-pingpong-delay.js index 4e478c87a64132..9a598435d1bd28 100644 --- a/test/pummel/test-net-pingpong-delay.js +++ b/test/pummel/test-net-pingpong-delay.js @@ -4,12 +4,12 @@ const assert = require('assert'); const net = require('net'); function pingPongTest(port, host, on_complete) { - var N = 100; - var DELAY = 1; - var count = 0; - var client_ended = false; + const N = 100; + const DELAY = 1; + let count = 0; + let client_ended = false; - var server = net.createServer({ allowHalfOpen: true }, function(socket) { + const server = net.createServer({ allowHalfOpen: true }, function(socket) { socket.setEncoding('utf8'); socket.on('data', function(data) { @@ -43,7 +43,7 @@ function pingPongTest(port, host, on_complete) { }); server.listen(port, host, common.mustCall(function() { - var client = net.createConnection(port, host); + const client = net.createConnection(port, host); client.setEncoding('utf8'); diff --git a/test/pummel/test-net-pingpong.js b/test/pummel/test-net-pingpong.js index b65d5d4ff94224..6ede6f9fcb2763 100644 --- a/test/pummel/test-net-pingpong.js +++ b/test/pummel/test-net-pingpong.js @@ -3,17 +3,17 @@ const common = require('../common'); const assert = require('assert'); const net = require('net'); -var tests_run = 0; +let tests_run = 0; function pingPongTest(port, host, on_complete) { - var N = 1000; - var count = 0; - var sent_final_ping = false; + const N = 1000; + let count = 0; + let sent_final_ping = false; - var server = net.createServer({ allowHalfOpen: true }, function(socket) { + const server = net.createServer({ allowHalfOpen: true }, function(socket) { assert.equal(true, socket.remoteAddress !== null); assert.equal(true, socket.remoteAddress !== undefined); - var address = socket.remoteAddress; + const address = socket.remoteAddress; if (host === '127.0.0.1') { assert.equal(address, '127.0.0.1'); } else if (host == null || host === 'localhost') { @@ -49,7 +49,7 @@ function pingPongTest(port, host, on_complete) { }); server.listen(port, host, function() { - var client = net.createConnection(port, host); + const client = net.createConnection(port, host); client.setEncoding('utf8'); diff --git a/test/pummel/test-net-throttle.js b/test/pummel/test-net-throttle.js index d2f32ec25b6ff2..23f05f4d5eaeaa 100644 --- a/test/pummel/test-net-throttle.js +++ b/test/pummel/test-net-throttle.js @@ -5,15 +5,15 @@ const net = require('net'); const N = 1024 * 1024; const part_N = N / 3; -var chars_recved = 0; -var npauses = 0; +let chars_recved = 0; +let npauses = 0; console.log('build big string'); const body = 'C'.repeat(N); console.log('start server on port ' + common.PORT); -var server = net.createServer(function(connection) { +const server = net.createServer(function(connection) { connection.write(body.slice(0, part_N)); connection.write(body.slice(part_N, 2 * part_N)); assert.equal(false, connection.write(body.slice(2 * part_N, N))); @@ -24,8 +24,8 @@ var server = net.createServer(function(connection) { }); server.listen(common.PORT, function() { - var paused = false; - var client = net.createConnection(common.PORT); + let paused = false; + const client = net.createConnection(common.PORT); client.setEncoding('ascii'); client.on('data', function(d) { chars_recved += d.length; @@ -35,7 +35,7 @@ server.listen(common.PORT, function() { npauses += 1; paused = true; console.log('pause'); - var x = chars_recved; + const x = chars_recved; setTimeout(function() { assert.equal(chars_recved, x); client.resume(); diff --git a/test/pummel/test-net-timeout.js b/test/pummel/test-net-timeout.js index e4f8664657505e..d6dd8e489cc116 100644 --- a/test/pummel/test-net-timeout.js +++ b/test/pummel/test-net-timeout.js @@ -3,12 +3,12 @@ const common = require('../common'); const assert = require('assert'); const net = require('net'); -var exchanges = 0; -var starttime = null; -var timeouttime = null; -var timeout = 1000; +let exchanges = 0; +let starttime = null; +let timeouttime = null; +const timeout = 1000; -var echo_server = net.createServer(function(socket) { +const echo_server = net.createServer(function(socket) { socket.setTimeout(timeout); socket.on('timeout', function() { @@ -36,7 +36,7 @@ var echo_server = net.createServer(function(socket) { echo_server.listen(common.PORT, function() { console.log('server listening at ' + common.PORT); - var client = net.createConnection(common.PORT); + const client = net.createConnection(common.PORT); client.setEncoding('UTF8'); client.setTimeout(0); // disable the timeout for client client.on('connect', function() { @@ -79,7 +79,7 @@ process.on('exit', function() { assert.ok(starttime != null); assert.ok(timeouttime != null); - var diff = timeouttime - starttime; + const diff = timeouttime - starttime; console.log('diff = ' + diff); assert.ok(timeout < diff); diff --git a/test/pummel/test-net-timeout2.js b/test/pummel/test-net-timeout2.js index 5567b128c7697d..a3d0abceb6c765 100644 --- a/test/pummel/test-net-timeout2.js +++ b/test/pummel/test-net-timeout2.js @@ -5,13 +5,13 @@ const common = require('../common'); const net = require('net'); -var seconds = 5; -var counter = 0; +const seconds = 5; +let counter = 0; -var server = net.createServer(function(socket) { +const server = net.createServer(function(socket) { socket.setTimeout((seconds / 2) * 1000, common.fail); - var interval = setInterval(function() { + const interval = setInterval(function() { counter++; if (counter === seconds) { @@ -28,6 +28,6 @@ var server = net.createServer(function(socket) { server.listen(common.PORT, function() { - var s = net.connect(common.PORT); + const s = net.connect(common.PORT); s.pipe(process.stdout); }); diff --git a/test/pummel/test-net-write-callbacks.js b/test/pummel/test-net-write-callbacks.js index 54f8a67abee3c6..6c3c1f202a81c3 100644 --- a/test/pummel/test-net-write-callbacks.js +++ b/test/pummel/test-net-write-callbacks.js @@ -3,10 +3,10 @@ const common = require('../common'); const net = require('net'); const assert = require('assert'); -var cbcount = 0; -var N = 500000; +let cbcount = 0; +const N = 500000; -var server = net.Server(function(socket) { +const server = net.Server(function(socket) { socket.on('data', function(d) { console.error('got %d bytes', d.length); }); @@ -18,9 +18,9 @@ var server = net.Server(function(socket) { }); }); -var lastCalled = -1; +let lastCalled = -1; function makeCallback(c) { - var called = false; + let called = false; return function() { if (called) throw new Error('called callback #' + c + ' more than once'); @@ -34,10 +34,10 @@ function makeCallback(c) { } server.listen(common.PORT, function() { - var client = net.createConnection(common.PORT); + const client = net.createConnection(common.PORT); client.on('connect', function() { - for (var i = 0; i < N; i++) { + for (let i = 0; i < N; i++) { client.write('hello world', makeCallback(i)); } client.end(); diff --git a/test/pummel/test-next-tick-infinite-calls.js b/test/pummel/test-next-tick-infinite-calls.js index 18223885d6cc19..afce6ef846b10f 100644 --- a/test/pummel/test-next-tick-infinite-calls.js +++ b/test/pummel/test-next-tick-infinite-calls.js @@ -1,7 +1,7 @@ 'use strict'; require('../common'); -var complete = 0; +let complete = 0; // This will fail with: // FATAL ERROR: JS Allocation failed - process out of memory diff --git a/test/pummel/test-process-hrtime.js b/test/pummel/test-process-hrtime.js index 0149ef2bf501cc..d02b9c79822a88 100644 --- a/test/pummel/test-process-hrtime.js +++ b/test/pummel/test-process-hrtime.js @@ -2,17 +2,17 @@ require('../common'); const assert = require('assert'); -var start = process.hrtime(); +const start = process.hrtime(); // process.hrtime() should return an Array assert(Array.isArray(start)); // busy-loop for 2 seconds -var now = Date.now(); +const now = Date.now(); while (Date.now() - now < 2000); // get a diff reading -var diff = process.hrtime(start); +const diff = process.hrtime(start); // should be at least 1 second, at most 2 seconds later // (the while loop will usually exit a few nanoseconds before 2) diff --git a/test/pummel/test-process-uptime.js b/test/pummel/test-process-uptime.js index 90343e91a1e09a..5c09d59b06d55c 100644 --- a/test/pummel/test-process-uptime.js +++ b/test/pummel/test-process-uptime.js @@ -5,10 +5,10 @@ const assert = require('assert'); console.error(process.uptime()); assert.ok(process.uptime() <= 2); -var original = process.uptime(); +const original = process.uptime(); setTimeout(function() { - var uptime = process.uptime(); + const uptime = process.uptime(); // some wiggle room to account for timer // granularity, processor speed, and scheduling assert.ok(uptime >= original + 2); diff --git a/test/pummel/test-regress-GH-814.js b/test/pummel/test-regress-GH-814.js index 4c890e1705acc3..20323360debfe3 100644 --- a/test/pummel/test-regress-GH-814.js +++ b/test/pummel/test-regress-GH-814.js @@ -5,7 +5,7 @@ const common = require('../common'); const assert = require('assert'); function newBuffer(size, value) { - var buffer = Buffer.allocUnsafe(size); + const buffer = Buffer.allocUnsafe(size); while (size--) { buffer[size] = value; } @@ -16,14 +16,14 @@ function newBuffer(size, value) { const fs = require('fs'); const testFileName = require('path').join(common.tmpDir, 'GH-814_testFile.txt'); -var testFileFD = fs.openSync(testFileName, 'w'); +const testFileFD = fs.openSync(testFileName, 'w'); console.log(testFileName); -var kBufSize = 128 * 1024; -var PASS = true; -var neverWrittenBuffer = newBuffer(kBufSize, 0x2e); //0x2e === '.' -var bufPool = []; +const kBufSize = 128 * 1024; +let PASS = true; +const neverWrittenBuffer = newBuffer(kBufSize, 0x2e); //0x2e === '.' +const bufPool = []; const tail = require('child_process').spawn('tail', ['-f', testFileName]); @@ -34,13 +34,13 @@ function tailCB(data) { } -var timeToQuit = Date.now() + 8e3; //Test during no more than this seconds. +const timeToQuit = Date.now() + 8e3; //Test during no more than this seconds. (function main() { if (PASS) { fs.write(testFileFD, newBuffer(kBufSize, 0x61), 0, kBufSize, -1, cb); global.gc(); - var nuBuf = Buffer.allocUnsafe(kBufSize); + const nuBuf = Buffer.allocUnsafe(kBufSize); neverWrittenBuffer.copy(nuBuf); if (bufPool.push(nuBuf) > 100) { bufPool.length = 0; diff --git a/test/pummel/test-regress-GH-814_2.js b/test/pummel/test-regress-GH-814_2.js index afba742e60bb7d..233e8530459545 100644 --- a/test/pummel/test-regress-GH-814_2.js +++ b/test/pummel/test-regress-GH-814_2.js @@ -6,7 +6,7 @@ const assert = require('assert'); const fs = require('fs'); const testFileName = require('path').join(common.tmpDir, 'GH-814_test.txt'); -var testFD = fs.openSync(testFileName, 'w'); +const testFD = fs.openSync(testFileName, 'w'); console.error(testFileName + '\n'); @@ -27,12 +27,12 @@ function tailCB(data) { } -var PASS = true; -var bufPool = []; -var kBufSize = 16 * 1024 * 1024; -var neverWrittenBuffer = newBuffer(kBufSize, 0x2e); //0x2e === '.' +let PASS = true; +const bufPool = []; +const kBufSize = 16 * 1024 * 1024; +const neverWrittenBuffer = newBuffer(kBufSize, 0x2e); //0x2e === '.' -var timeToQuit = Date.now() + 5e3; //Test should last no more than this. +const timeToQuit = Date.now() + 5e3; //Test should last no more than this. writer(); function writer() { @@ -51,7 +51,7 @@ function writer() { global.gc(); global.gc(); global.gc(); - var nuBuf = Buffer.allocUnsafe(kBufSize); + const nuBuf = Buffer.allocUnsafe(kBufSize); neverWrittenBuffer.copy(nuBuf); if (bufPool.push(nuBuf) > 100) { bufPool.length = 0; @@ -73,7 +73,7 @@ function writerCB(err, written) { function newBuffer(size, value) { - var buffer = Buffer.allocUnsafe(size); + const buffer = Buffer.allocUnsafe(size); while (size--) { buffer[size] = value; } diff --git a/test/pummel/test-regress-GH-892.js b/test/pummel/test-regress-GH-892.js index 9a2fce08a7fe3b..0619fd84de3b5e 100644 --- a/test/pummel/test-regress-GH-892.js +++ b/test/pummel/test-regress-GH-892.js @@ -17,9 +17,9 @@ const https = require('https'); const fs = require('fs'); -var bytesExpected = 1024 * 1024 * 32; +const bytesExpected = 1024 * 1024 * 32; -var started = false; +let started = false; const childScript = require('path').join(common.fixturesDir, 'GH-892-request.js'); @@ -28,17 +28,17 @@ function makeRequest() { if (started) return; started = true; - var stderrBuffer = ''; + let stderrBuffer = ''; // Pass along --trace-deprecation/--throw-deprecation in // process.execArgv to track down nextTick recursion errors // more easily. Also, this is handy when using this test to // view V8 opt/deopt behavior. - var args = process.execArgv.concat([ childScript, - common.PORT, - bytesExpected ]); + const args = process.execArgv.concat([ childScript, + common.PORT, + bytesExpected ]); - var child = spawn(process.execPath, args); + const child = spawn(process.execPath, args); child.on('exit', function(code) { assert.ok(/DONE/.test(stderrBuffer)); @@ -59,14 +59,14 @@ function makeRequest() { } -var serverOptions = { +const serverOptions = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }; -var uploadCount = 0; +let uploadCount = 0; -var server = https.Server(serverOptions, function(req, res) { +const server = https.Server(serverOptions, function(req, res) { // Close the server immediately. This test is only doing a single upload. // We need to make sure the server isn't keeping the event loop alive // while the upload is in progress. diff --git a/test/pummel/test-stream-pipe-multi.js b/test/pummel/test-stream-pipe-multi.js index 3c62548e5b81bb..e1e5e011020fe2 100644 --- a/test/pummel/test-stream-pipe-multi.js +++ b/test/pummel/test-stream-pipe-multi.js @@ -5,14 +5,14 @@ require('../common'); const assert = require('assert'); const Stream = require('stream').Stream; -var rr = []; -var ww = []; -var cnt = 100; -var chunks = 1000; -var chunkSize = 250; -var data = Buffer.allocUnsafe(chunkSize); -var wclosed = 0; -var rclosed = 0; +const rr = []; +const ww = []; +const cnt = 100; +const chunks = 1000; +const chunkSize = 250; +const data = Buffer.allocUnsafe(chunkSize); +let wclosed = 0; +let rclosed = 0; function FakeStream() { Stream.apply(this); @@ -54,14 +54,14 @@ for (let i = 0; i < chunkSize; i++) { } for (let i = 0; i < cnt; i++) { - var r = new FakeStream(); + const r = new FakeStream(); r.on('close', function() { console.error(this.ID, 'read close'); rclosed++; }); rr.push(r); - var w = new FakeStream(); + const w = new FakeStream(); w.on('close', function() { console.error(this.ID, 'write close'); wclosed++; @@ -75,8 +75,8 @@ for (let i = 0; i < cnt; i++) { // now start passing through data // simulate a relatively fast async stream. rr.forEach(function(r) { - var cnt = chunks; - var paused = false; + let cnt = chunks; + let paused = false; r.on('pause', function() { paused = true; diff --git a/test/pummel/test-stream2-basic.js b/test/pummel/test-stream2-basic.js index 3659b267fad162..073c1d8e35ad36 100644 --- a/test/pummel/test-stream2-basic.js +++ b/test/pummel/test-stream2-basic.js @@ -16,9 +16,9 @@ function TestReader(n) { util.inherits(TestReader, R); TestReader.prototype._read = function(n) { - var max = this._buffer.length - this._pos; + const max = this._buffer.length - this._pos; n = Math.max(n, 0); - var toRead = Math.min(n, max); + const toRead = Math.min(n, max); if (toRead === 0) { // simulate the read buffer filling up with some more bytes some time // in the future. @@ -39,7 +39,7 @@ TestReader.prototype._read = function(n) { return; } - var ret = this._buffer.slice(this._pos, this._pos + toRead); + const ret = this._buffer.slice(this._pos, this._pos + toRead); this._pos += toRead; this.push(ret); }; @@ -68,8 +68,8 @@ TestWriter.prototype.end = function(c) { //////// // tiny node-tap lookalike. -var tests = []; -var count = 0; +const tests = []; +let count = 0; function test(name, fn) { count++; @@ -77,12 +77,12 @@ function test(name, fn) { } function run() { - var next = tests.shift(); + const next = tests.shift(); if (!next) return console.error('ok'); - var name = next[0]; - var fn = next[1]; + const name = next[0]; + const fn = next[1]; console.log('# %s', name); fn({ same: assert.deepStrictEqual, @@ -104,34 +104,34 @@ process.nextTick(run); test('a most basic test', function(t) { - var r = new TestReader(20); - - var reads = []; - var expect = [ 'x', - 'xx', - 'xxx', - 'xxxx', - 'xxxxx', - 'xxxxxxxxx', - 'xxxxxxxxxx', - 'xxxxxxxxxxxx', - 'xxxxxxxxxxxxx', - 'xxxxxxxxxxxxxxx', - 'xxxxxxxxxxxxxxxxx', - 'xxxxxxxxxxxxxxxxxxx', - 'xxxxxxxxxxxxxxxxxxxxx', - 'xxxxxxxxxxxxxxxxxxxxxxx', - 'xxxxxxxxxxxxxxxxxxxxxxxxx', - 'xxxxxxxxxxxxxxxxxxxxx' ]; + const r = new TestReader(20); + + const reads = []; + const expect = [ 'x', + 'xx', + 'xxx', + 'xxxx', + 'xxxxx', + 'xxxxxxxxx', + 'xxxxxxxxxx', + 'xxxxxxxxxxxx', + 'xxxxxxxxxxxxx', + 'xxxxxxxxxxxxxxx', + 'xxxxxxxxxxxxxxxxx', + 'xxxxxxxxxxxxxxxxxxx', + 'xxxxxxxxxxxxxxxxxxxxx', + 'xxxxxxxxxxxxxxxxxxxxxxx', + 'xxxxxxxxxxxxxxxxxxxxxxxxx', + 'xxxxxxxxxxxxxxxxxxxxx' ]; r.on('end', function() { t.same(reads, expect); t.end(); }); - var readSize = 1; + let readSize = 1; function flow() { - var res; + let res; while (null !== (res = r.read(readSize++))) { reads.push(res.toString()); } @@ -142,20 +142,20 @@ test('a most basic test', function(t) { }); test('pipe', function(t) { - var r = new TestReader(5); + const r = new TestReader(5); - var expect = [ 'xxxxx', - 'xxxxx', - 'xxxxx', - 'xxxxx', - 'xxxxx', - 'xxxxx', - 'xxxxx', - 'xxxxx', - 'xxxxx', - 'xxxxx' ]; + const expect = [ 'xxxxx', + 'xxxxx', + 'xxxxx', + 'xxxxx', + 'xxxxx', + 'xxxxx', + 'xxxxx', + 'xxxxx', + 'xxxxx', + 'xxxxx' ]; - var w = new TestWriter(); + const w = new TestWriter(); w.on('end', function(received) { t.same(received, expect); @@ -168,10 +168,10 @@ test('pipe', function(t) { [1, 2, 3, 4, 5, 6, 7, 8, 9].forEach(function(SPLIT) { test('unpipe', function(t) { - var r = new TestReader(5); + const r = new TestReader(5); // unpipe after 3 writes, then write to another stream instead. - var expect = [ 'xxxxx', + let expect = [ 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx', @@ -183,9 +183,9 @@ test('pipe', function(t) { 'xxxxx' ]; expect = [ expect.slice(0, SPLIT), expect.slice(SPLIT) ]; - var w = [ new TestWriter(), new TestWriter() ]; + const w = [ new TestWriter(), new TestWriter() ]; - var writes = SPLIT; + let writes = SPLIT; w[0].on('write', function() { if (--writes === 0) { r.unpipe(); @@ -196,10 +196,10 @@ test('pipe', function(t) { } }); - var ended = 0; + let ended = 0; - var ended0 = false; - var ended1 = false; + let ended0 = false; + let ended1 = false; w[0].on('end', function(results) { t.equal(ended0, false); ended0 = true; @@ -223,21 +223,21 @@ test('pipe', function(t) { // both writers should get the same exact data. test('multipipe', function(t) { - var r = new TestReader(5); - var w = [ new TestWriter(), new TestWriter() ]; - - var expect = [ 'xxxxx', - 'xxxxx', - 'xxxxx', - 'xxxxx', - 'xxxxx', - 'xxxxx', - 'xxxxx', - 'xxxxx', - 'xxxxx', - 'xxxxx' ]; - - var c = 2; + const r = new TestReader(5); + const w = [ new TestWriter(), new TestWriter() ]; + + const expect = [ 'xxxxx', + 'xxxxx', + 'xxxxx', + 'xxxxx', + 'xxxxx', + 'xxxxx', + 'xxxxx', + 'xxxxx', + 'xxxxx', + 'xxxxx' ]; + + let c = 2; w[0].on('end', function(received) { t.same(received, expect, 'first'); if (--c === 0) t.end(); @@ -254,10 +254,10 @@ test('multipipe', function(t) { [1, 2, 3, 4, 5, 6, 7, 8, 9].forEach(function(SPLIT) { test('multi-unpipe', function(t) { - var r = new TestReader(5); + const r = new TestReader(5); // unpipe after 3 writes, then write to another stream instead. - var expect = [ 'xxxxx', + let expect = [ 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx', @@ -269,9 +269,9 @@ test('multipipe', function(t) { 'xxxxx' ]; expect = [ expect.slice(0, SPLIT), expect.slice(SPLIT) ]; - var w = [ new TestWriter(), new TestWriter(), new TestWriter() ]; + const w = [ new TestWriter(), new TestWriter(), new TestWriter() ]; - var writes = SPLIT; + let writes = SPLIT; w[0].on('write', function() { if (--writes === 0) { r.unpipe(); @@ -280,7 +280,7 @@ test('multipipe', function(t) { } }); - var ended = 0; + let ended = 0; w[0].on('end', function(results) { ended++; @@ -302,16 +302,16 @@ test('multipipe', function(t) { test('back pressure respected', function(t) { function noop() {} - var r = new R({ objectMode: true }); + const r = new R({ objectMode: true }); r._read = noop; - var counter = 0; + let counter = 0; r.push(['one']); r.push(['two']); r.push(['three']); r.push(['four']); r.push(null); - var w1 = new R(); + const w1 = new R(); w1.write = function(chunk) { console.error('w1.emit("close")'); assert.equal(chunk[0], 'one'); @@ -325,9 +325,9 @@ test('back pressure respected', function(t) { r.pipe(w1); - var expected = ['two', 'two', 'three', 'three', 'four', 'four']; + const expected = ['two', 'two', 'three', 'three', 'four', 'four']; - var w2 = new R(); + const w2 = new R(); w2.write = function(chunk) { console.error('w2 write', chunk, counter); assert.equal(chunk[0], expected.shift()); @@ -349,7 +349,7 @@ test('back pressure respected', function(t) { }; w2.end = noop; - var w3 = new R(); + const w3 = new R(); w3.write = function(chunk) { console.error('w3 write', chunk, counter); assert.equal(chunk[0], expected.shift()); @@ -377,19 +377,19 @@ test('back pressure respected', function(t) { }); test('read(0) for ended streams', function(t) { - var r = new R(); - var written = false; - var ended = false; + const r = new R(); + let written = false; + let ended = false; r._read = function(n) {}; r.push(Buffer.from('foo')); r.push(null); - var v = r.read(0); + const v = r.read(0); assert.equal(v, null); - var w = new R(); + const w = new R(); w.write = function(buffer) { written = true; @@ -407,8 +407,8 @@ test('read(0) for ended streams', function(t) { }); test('sync _read ending', function(t) { - var r = new R(); - var called = false; + const r = new R(); + let called = false; r._read = function(n) { r.push(null); }; @@ -426,9 +426,9 @@ test('sync _read ending', function(t) { }); test('adding readable triggers data flow', function(t) { - var r = new R({ highWaterMark: 5 }); - var onReadable = false; - var readCalled = 0; + const r = new R({ highWaterMark: 5 }); + let onReadable = false; + let readCalled = 0; r._read = function(n) { if (readCalled++ === 2) @@ -450,9 +450,9 @@ test('adding readable triggers data flow', function(t) { }); test('chainable', function(t) { - var r = new R(); + const r = new R(); r._read = function() {}; - var r2 = r.setEncoding('utf8').pause().resume().pause(); + const r2 = r.setEncoding('utf8').pause().resume().pause(); t.equal(r, r2); t.end(); }); diff --git a/test/pummel/test-timer-wrap.js b/test/pummel/test-timer-wrap.js index 659912d1fc28ce..d30661716bd2b2 100644 --- a/test/pummel/test-timer-wrap.js +++ b/test/pummel/test-timer-wrap.js @@ -1,10 +1,10 @@ 'use strict'; const common = require('../common'); -var Timer = process.binding('timer_wrap').Timer; -var kOnTimeout = Timer.kOnTimeout; +const Timer = process.binding('timer_wrap').Timer; +const kOnTimeout = Timer.kOnTimeout; -var t = new Timer(); +const t = new Timer(); t.start(1000); diff --git a/test/pummel/test-timer-wrap2.js b/test/pummel/test-timer-wrap2.js index 87497b2685f5d3..4bae86f8cefb0c 100644 --- a/test/pummel/test-timer-wrap2.js +++ b/test/pummel/test-timer-wrap2.js @@ -4,5 +4,5 @@ require('../common'); // Test that allocating a timer does not increase the loop's reference // count. -var Timer = process.binding('timer_wrap').Timer; +const Timer = process.binding('timer_wrap').Timer; new Timer(); diff --git a/test/pummel/test-timers.js b/test/pummel/test-timers.js index 83a8eeffeb43c3..4555582371b9ff 100644 --- a/test/pummel/test-timers.js +++ b/test/pummel/test-timers.js @@ -2,20 +2,20 @@ const common = require('../common'); const assert = require('assert'); -var WINDOW = 200; // why is does this need to be so big? +const WINDOW = 200; // why is does this need to be so big? -var interval_count = 0; +let interval_count = 0; // check that these don't blow up. clearTimeout(null); clearInterval(null); assert.equal(true, setTimeout instanceof Function); -var starttime = new Date(); +const starttime = new Date(); setTimeout(common.mustCall(function() { - var endtime = new Date(); + const endtime = new Date(); - var diff = endtime - starttime; + const diff = endtime - starttime; assert.ok(diff > 0); console.error('diff: ' + diff); @@ -23,18 +23,18 @@ setTimeout(common.mustCall(function() { }), 1000); // this timer shouldn't execute -var id = setTimeout(function() { assert.equal(true, false); }, 500); +const id = setTimeout(function() { assert.equal(true, false); }, 500); clearTimeout(id); setInterval(function() { interval_count += 1; - var endtime = new Date(); + const endtime = new Date(); - var diff = endtime - starttime; + const diff = endtime - starttime; assert.ok(diff > 0); console.error('diff: ' + diff); - var t = interval_count * 1000; + const t = interval_count * 1000; assert.equal(true, t - WINDOW < diff && diff < t + WINDOW); @@ -49,7 +49,7 @@ setTimeout(function(param) { assert.equal('test param', param); }, 1000, 'test param'); -var interval_count2 = 0; +let interval_count2 = 0; setInterval(function(param) { ++interval_count2; assert.equal('test param', param); @@ -65,7 +65,7 @@ setTimeout(function(param1, param2) { assert.equal('param2', param2); }, 1000, 'param1', 'param2'); -var interval_count3 = 0; +let interval_count3 = 0; setInterval(function(param1, param2) { ++interval_count3; assert.equal('param1', param1); @@ -76,14 +76,14 @@ setInterval(function(param1, param2) { }, 1000, 'param1', 'param2'); // setInterval(cb, 0) should be called multiple times. -var count4 = 0; -var interval4 = setInterval(function() { +let count4 = 0; +const interval4 = setInterval(function() { if (++count4 > 10) clearInterval(interval4); }, 0); // we should be able to clearTimeout multiple times without breakage. -var expectedTimeouts = 3; +let expectedTimeouts = 3; function t() { expectedTimeouts--; @@ -91,7 +91,7 @@ function t() { setTimeout(t, 200); setTimeout(t, 200); -var y = setTimeout(t, 200); +const y = setTimeout(t, 200); clearTimeout(y); setTimeout(t, 200); diff --git a/test/pummel/test-tls-ci-reneg-attack.js b/test/pummel/test-tls-ci-reneg-attack.js index c8f78e0609acc6..dd2b43ed60278f 100644 --- a/test/pummel/test-tls-ci-reneg-attack.js +++ b/test/pummel/test-tls-ci-reneg-attack.js @@ -17,7 +17,7 @@ if (!common.opensslCli) { } // renegotiation limits to test -var LIMITS = [0, 1, 2, 3, 5, 10, 16]; +const LIMITS = [0, 1, 2, 3, 5, 10, 16]; { let n = 0; @@ -30,14 +30,14 @@ var LIMITS = [0, 1, 2, 3, 5, 10, 16]; } function test(next) { - var options = { + const options = { cert: fs.readFileSync(common.fixturesDir + '/test_cert.pem'), key: fs.readFileSync(common.fixturesDir + '/test_key.pem') }; - var seenError = false; + let seenError = false; - var server = tls.createServer(options, function(conn) { + const server = tls.createServer(options, function(conn) { conn.on('error', function(err) { console.error('Caught exception: ' + err); assert(/TLS session renegotiation attack/.test(err)); @@ -48,8 +48,8 @@ function test(next) { }); server.listen(common.PORT, function() { - var args = ('s_client -connect 127.0.0.1:' + common.PORT).split(' '); - var child = spawn(common.opensslCli, args); + const args = ('s_client -connect 127.0.0.1:' + common.PORT).split(' '); + const child = spawn(common.opensslCli, args); //child.stdout.pipe(process.stdout); //child.stderr.pipe(process.stderr); @@ -58,8 +58,8 @@ function test(next) { child.stderr.resume(); // count handshakes, start the attack after the initial handshake is done - var handshakes = 0; - var renegs = 0; + let handshakes = 0; + let renegs = 0; child.stderr.on('data', function(data) { if (seenError) return; @@ -74,7 +74,7 @@ function test(next) { process.nextTick(next); }); - var closed = false; + let closed = false; child.stdin.on('error', function(err) { switch (err.code) { case 'ECONNRESET': diff --git a/test/pummel/test-tls-connect-memleak.js b/test/pummel/test-tls-connect-memleak.js index 46e7f425df5aba..b1d1f05190c39d 100644 --- a/test/pummel/test-tls-connect-memleak.js +++ b/test/pummel/test-tls-connect-memleak.js @@ -38,10 +38,10 @@ tls.createServer({ } function done() { - var before = process.memoryUsage().rss; + const before = process.memoryUsage().rss; global.gc(); - var after = process.memoryUsage().rss; - var reclaimed = (before - after) / 1024; + const after = process.memoryUsage().rss; + const reclaimed = (before - after) / 1024; console.log('%d kB reclaimed', reclaimed); assert(reclaimed > 256 * 1024); // it's more like 512M on x64 process.exit(); diff --git a/test/pummel/test-tls-securepair-client.js b/test/pummel/test-tls-securepair-client.js index c47cc60301380f..75e7b400592191 100644 --- a/test/pummel/test-tls-securepair-client.js +++ b/test/pummel/test-tls-securepair-client.js @@ -40,22 +40,22 @@ function test2() { function test(keyfn, certfn, check, next) { keyfn = join(common.fixturesDir, keyfn); - var key = fs.readFileSync(keyfn).toString(); + const key = fs.readFileSync(keyfn).toString(); certfn = join(common.fixturesDir, certfn); - var cert = fs.readFileSync(certfn).toString(); + const cert = fs.readFileSync(certfn).toString(); - var server = spawn(common.opensslCli, ['s_server', - '-accept', common.PORT, - '-cert', certfn, - '-key', keyfn]); + const server = spawn(common.opensslCli, ['s_server', + '-accept', common.PORT, + '-cert', certfn, + '-key', keyfn]); server.stdout.pipe(process.stdout); server.stderr.pipe(process.stdout); - var state = 'WAIT-ACCEPT'; + let state = 'WAIT-ACCEPT'; - var serverStdoutBuffer = ''; + let serverStdoutBuffer = ''; server.stdout.setEncoding('utf8'); server.stdout.on('data', function(s) { serverStdoutBuffer += s; @@ -86,13 +86,13 @@ function test(keyfn, certfn, check, next) { }); - var timeout = setTimeout(function() { + const timeout = setTimeout(function() { server.kill(); process.exit(1); }, 5000); - var gotWriteCallback = false; - var serverExitCode = -1; + let gotWriteCallback = false; + let serverExitCode = -1; server.on('exit', function(code) { serverExitCode = code; @@ -102,12 +102,12 @@ function test(keyfn, certfn, check, next) { function startClient() { - var s = new net.Stream(); + const s = new net.Stream(); - var sslcontext = tls.createSecureContext({key: key, cert: cert}); + const sslcontext = tls.createSecureContext({key: key, cert: cert}); sslcontext.context.setCiphers('RC4-SHA:AES128-SHA:AES256-SHA'); - var pair = tls.createSecurePair(sslcontext, false); + const pair = tls.createSecurePair(sslcontext, false); assert.ok(pair.encrypted.writable); assert.ok(pair.cleartext.writable); diff --git a/test/pummel/test-tls-server-large-request.js b/test/pummel/test-tls-server-large-request.js index 1b43a558353c0f..f02eb51a2f6742 100644 --- a/test/pummel/test-tls-server-large-request.js +++ b/test/pummel/test-tls-server-large-request.js @@ -12,9 +12,9 @@ const fs = require('fs'); const stream = require('stream'); const util = require('util'); -var request = Buffer.from(new Array(1024 * 256).join('ABCD')); // 1mb +const request = Buffer.from(new Array(1024 * 256).join('ABCD')); // 1mb -var options = { +const options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }; @@ -35,14 +35,14 @@ Mediator.prototype._write = function _write(data, enc, cb) { } }; -var mediator = new Mediator(); +const mediator = new Mediator(); -var server = tls.Server(options, common.mustCall(function(socket) { +const server = tls.Server(options, common.mustCall(function(socket) { socket.pipe(mediator); })); server.listen(common.PORT, common.mustCall(function() { - var client1 = tls.connect({ + const client1 = tls.connect({ port: common.PORT, rejectUnauthorized: false }, common.mustCall(function() { diff --git a/test/pummel/test-tls-session-timeout.js b/test/pummel/test-tls-session-timeout.js index ffa44a97025002..c194188b3682a9 100644 --- a/test/pummel/test-tls-session-timeout.js +++ b/test/pummel/test-tls-session-timeout.js @@ -28,13 +28,13 @@ function doTest() { const join = require('path').join; const spawn = require('child_process').spawn; - var SESSION_TIMEOUT = 1; + const SESSION_TIMEOUT = 1; - var keyFile = join(common.fixturesDir, 'agent.key'); - var certFile = join(common.fixturesDir, 'agent.crt'); - var key = fs.readFileSync(keyFile); - var cert = fs.readFileSync(certFile); - var options = { + const keyFile = join(common.fixturesDir, 'agent.key'); + const certFile = join(common.fixturesDir, 'agent.crt'); + const key = fs.readFileSync(keyFile); + const cert = fs.readFileSync(certFile); + const options = { key: key, cert: cert, ca: [cert], @@ -47,41 +47,41 @@ function doTest() { // file containing a proper serialization of a session ticket. // To avoid a source control diff, we copy the ticket to a temporary file. - var sessionFileName = (function() { - var ticketFileName = 'tls-session-ticket.txt'; - var fixturesPath = join(common.fixturesDir, ticketFileName); - var tmpPath = join(common.tmpDir, ticketFileName); + const sessionFileName = (function() { + const ticketFileName = 'tls-session-ticket.txt'; + const fixturesPath = join(common.fixturesDir, ticketFileName); + const tmpPath = join(common.tmpDir, ticketFileName); fs.writeFileSync(tmpPath, fs.readFileSync(fixturesPath)); return tmpPath; }()); // Expects a callback -- cb(connectionType : enum ['New'|'Reused']) - var Client = function(cb) { - var flags = [ + const Client = function(cb) { + const flags = [ 's_client', '-connect', 'localhost:' + common.PORT, '-sess_in', sessionFileName, '-sess_out', sessionFileName ]; - var client = spawn(common.opensslCli, flags, { + const client = spawn(common.opensslCli, flags, { stdio: ['ignore', 'pipe', 'ignore'] }); - var clientOutput = ''; + let clientOutput = ''; client.stdout.on('data', function(data) { clientOutput += data.toString(); }); client.on('exit', function(code) { - var connectionType; - var grepConnectionType = function(line) { - var matches = line.match(/(New|Reused), /); + let connectionType; + const grepConnectionType = function(line) { + const matches = line.match(/(New|Reused), /); if (matches) { connectionType = matches[1]; return true; } }; - var lines = clientOutput.split('\n'); + const lines = clientOutput.split('\n'); if (!lines.some(grepConnectionType)) { throw new Error('unexpected output from openssl client'); } @@ -89,7 +89,7 @@ function doTest() { }); }; - var server = tls.createServer(options, function(cleartext) { + const server = tls.createServer(options, function(cleartext) { cleartext.on('error', function(er) { if (er.code !== 'ECONNRESET') throw er; diff --git a/test/pummel/test-tls-throttle.js b/test/pummel/test-tls-throttle.js index 581355d61b701a..574a83b18f2846 100644 --- a/test/pummel/test-tls-throttle.js +++ b/test/pummel/test-tls-throttle.js @@ -13,22 +13,22 @@ const tls = require('tls'); const fs = require('fs'); process.stdout.write('build body...'); -var body = 'hello world\n'.repeat(1024 * 1024); +const body = 'hello world\n'.repeat(1024 * 1024); process.stdout.write('done\n'); -var options = { +const options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem') }; -var server = tls.Server(options, common.mustCall(function(socket) { +const server = tls.Server(options, common.mustCall(function(socket) { socket.end(body); })); -var recvCount = 0; +let recvCount = 0; server.listen(common.PORT, function() { - var client = tls.connect({ + const client = tls.connect({ port: common.PORT, rejectUnauthorized: false }); @@ -58,7 +58,7 @@ function displayCounts() { } -var timeout = setTimeout(displayCounts, 10 * 1000); +const timeout = setTimeout(displayCounts, 10 * 1000); process.on('exit', function() { diff --git a/test/pummel/test-vm-memleak.js b/test/pummel/test-vm-memleak.js index 6f26c9a590c54d..8503e2389b44a7 100644 --- a/test/pummel/test-vm-memleak.js +++ b/test/pummel/test-vm-memleak.js @@ -4,21 +4,21 @@ require('../common'); const assert = require('assert'); -var start = Date.now(); -var maxMem = 0; +const start = Date.now(); +let maxMem = 0; -var ok = process.execArgv.some(function(arg) { +const ok = process.execArgv.some(function(arg) { return arg === '--max_old_space_size=32'; }); assert(ok, 'Run this test with --max_old_space_size=32.'); -var interval = setInterval(function() { +const interval = setInterval(function() { try { require('vm').runInNewContext('throw 1;'); } catch (e) { } - var rss = process.memoryUsage().rss; + const rss = process.memoryUsage().rss; maxMem = Math.max(rss, maxMem); if (Date.now() - start > 5 * 1000) { @@ -30,7 +30,7 @@ var interval = setInterval(function() { }, 1); function testContextLeak() { - for (var i = 0; i < 1000; i++) + for (let i = 0; i < 1000; i++) require('vm').createContext({}); } diff --git a/test/sequential/test-child-process-execsync.js b/test/sequential/test-child-process-execsync.js index 91529ff94de3da..20a35b98b36c6f 100644 --- a/test/sequential/test-child-process-execsync.js +++ b/test/sequential/test-child-process-execsync.js @@ -5,12 +5,12 @@ const assert = require('assert'); const execSync = require('child_process').execSync; const execFileSync = require('child_process').execFileSync; -var TIMER = 200; -var SLEEP = 2000; +const TIMER = 200; +const SLEEP = 2000; -var start = Date.now(); -var err; -var caught = false; +const start = Date.now(); +let err; +let caught = false; // Verify that stderr is not accessed when a bad shell is used assert.throws( @@ -24,9 +24,10 @@ assert.throws( 'execFileSync did not throw the expected exception!' ); +let cmd, ret; try { - var cmd = `"${process.execPath}" -e "setTimeout(function(){}, ${SLEEP});"`; - var ret = execSync(cmd, {timeout: TIMER}); + cmd = `"${process.execPath}" -e "setTimeout(function(){}, ${SLEEP});"`; + ret = execSync(cmd, {timeout: TIMER}); } catch (e) { caught = true; assert.strictEqual(e.errno, 'ETIMEDOUT'); @@ -34,7 +35,7 @@ try { } finally { assert.strictEqual(ret, undefined, 'we should not have a return value'); assert.strictEqual(caught, true, 'execSync should throw'); - var end = Date.now() - start; + const end = Date.now() - start; assert(end < SLEEP); assert(err.status > 128 || err.signal); } @@ -43,8 +44,8 @@ assert.throws(function() { execSync('iamabadcommand'); }, /Command failed: iamabadcommand/); -var msg = 'foobar'; -var msgBuf = Buffer.from(msg + '\n'); +const msg = 'foobar'; +const msgBuf = Buffer.from(msg + '\n'); // console.log ends every line with just '\n', even on Windows. @@ -59,7 +60,7 @@ ret = execSync(cmd, { encoding: 'utf8' }); assert.strictEqual(ret, msg + '\n', 'execSync encoding result should match'); -var args = [ +const args = [ '-e', `console.log("${msg}");` ]; diff --git a/test/sequential/test-debugger-debug-brk.js b/test/sequential/test-debugger-debug-brk.js index 85ebe2ad17b53d..26c3418171e8df 100644 --- a/test/sequential/test-debugger-debug-brk.js +++ b/test/sequential/test-debugger-debug-brk.js @@ -3,14 +3,14 @@ const common = require('../common'); const assert = require('assert'); const spawn = require('child_process').spawn; -var script = common.fixturesDir + '/empty.js'; +const script = common.fixturesDir + '/empty.js'; function fail() { assert(0); // `node --debug-brk script.js` should not quit } function test(arg) { - var child = spawn(process.execPath, [arg, script]); + const child = spawn(process.execPath, [arg, script]); child.on('exit', fail); // give node time to start up the debugger diff --git a/test/sequential/test-deprecation-flags.js b/test/sequential/test-deprecation-flags.js index e9f5ee673d23bd..eb5c1a3ae6261f 100644 --- a/test/sequential/test-deprecation-flags.js +++ b/test/sequential/test-deprecation-flags.js @@ -38,7 +38,7 @@ execFile(node, traceDep, function(er, stdout, stderr) { console.error('--trace-deprecation: show stack'); assert.equal(er, null); assert.equal(stdout, ''); - var stack = stderr.trim().split('\n'); + const stack = stderr.trim().split('\n'); // just check the top and bottom. assert(/util.debug is deprecated. Use console.error instead./.test(stack[1])); assert(/DEBUG: This is deprecated/.test(stack[0])); diff --git a/test/sequential/test-fs-readfile-tostring-fail.js b/test/sequential/test-fs-readfile-tostring-fail.js index 8ed9658a25889a..593b8da0fd8afa 100644 --- a/test/sequential/test-fs-readfile-tostring-fail.js +++ b/test/sequential/test-fs-readfile-tostring-fail.js @@ -23,7 +23,7 @@ const stream = fs.createWriteStream(file, { const size = kStringMaxLength / 200; const a = Buffer.alloc(size, 'a'); -for (var i = 0; i < 201; i++) { +for (let i = 0; i < 201; i++) { stream.write(a); } diff --git a/test/sequential/test-http-regr-gh-2928.js b/test/sequential/test-http-regr-gh-2928.js index b4ae7054d72bb9..190966083e3f97 100644 --- a/test/sequential/test-http-regr-gh-2928.js +++ b/test/sequential/test-http-regr-gh-2928.js @@ -11,11 +11,11 @@ const net = require('net'); const COUNT = httpCommon.parsers.max + 1; const parsers = new Array(COUNT); -for (var i = 0; i < parsers.length; i++) +for (let i = 0; i < parsers.length; i++) parsers[i] = httpCommon.parsers.alloc(); -var gotRequests = 0; -var gotResponses = 0; +let gotRequests = 0; +let gotResponses = 0; function execAndClose() { if (parsers.length === 0) @@ -50,7 +50,7 @@ function execAndClose() { }; } -var server = net.createServer(function(c) { +const server = net.createServer(function(c) { if (++gotRequests === COUNT) server.close(); c.end('HTTP/1.1 200 OK\r\n\r\n', function() { diff --git a/test/sequential/test-module-loading.js b/test/sequential/test-module-loading.js index 54fcc5c06a7ef4..dd4e7ba76b611f 100644 --- a/test/sequential/test-module-loading.js +++ b/test/sequential/test-module-loading.js @@ -101,7 +101,7 @@ assert.ok(my_path.path_func instanceof Function); // this one does not exist and should throw assert.throws(function() { require('./utils'); }); -var errorThrown = false; +let errorThrown = false; try { require('../fixtures/throws_error'); } catch (e) { @@ -113,7 +113,7 @@ assert.strictEqual(require('path').dirname(__filename), __dirname); console.error('load custom file types with extensions'); require.extensions['.test'] = function(module, filename) { - var content = fs.readFileSync(filename).toString(); + let content = fs.readFileSync(filename).toString(); assert.strictEqual('this is custom source\n', content); content = content.replace('this is custom source', 'exports.test = \'passed\''); @@ -193,8 +193,8 @@ assert.deepStrictEqual(json, { // modules that we've required, and that all of them contain // the appropriate children, and so on. -var children = module.children.reduce(function red(set, child) { - var id = path.relative(path.dirname(__dirname), child.id); +const children = module.children.reduce(function red(set, child) { + let id = path.relative(path.dirname(__dirname), child.id); id = id.replace(/\\/g, '/'); set[id] = child.children.reduce(red, {}); return set; diff --git a/test/sequential/test-net-GH-5504.js b/test/sequential/test-net-GH-5504.js index b40cfb400bf537..a7f64c2e73da10 100644 --- a/test/sequential/test-net-GH-5504.js +++ b/test/sequential/test-net-GH-5504.js @@ -19,7 +19,7 @@ switch (process.argv[2]) { function server() { const net = require('net'); - var content = Buffer.alloc(64 * 1024 * 1024, '#'); + const content = Buffer.alloc(64 * 1024 * 1024, '#'); net.createServer(function(socket) { this.close(); socket.on('end', function() { @@ -36,7 +36,7 @@ function server() { function client() { const net = require('net'); - var client = net.connect({ + const client = net.connect({ host: common.localhostIPv4, port: common.PORT }, function() { @@ -46,14 +46,14 @@ function client() { function parent() { const spawn = require('child_process').spawn; - var node = process.execPath; + const node = process.execPath; - var s = spawn(node, [__filename, 'server'], { + const s = spawn(node, [__filename, 'server'], { env: Object.assign(process.env, { NODE_DEBUG: 'net' }) }); - var c; + let c; wrap(s.stderr, process.stderr, 'SERVER 2>'); wrap(s.stdout, process.stdout, 'SERVER 1>'); diff --git a/test/sequential/test-regress-GH-1697.js b/test/sequential/test-regress-GH-1697.js index 1511cfd1cfcf6b..d99acf9e468bb3 100644 --- a/test/sequential/test-regress-GH-1697.js +++ b/test/sequential/test-regress-GH-1697.js @@ -6,7 +6,7 @@ const cp = require('child_process'); if (process.argv[2] === 'server') { // Server - var server = net.createServer(function(conn) { + const server = net.createServer(function(conn) { conn.on('data', function(data) { console.log('server received ' + data.length + ' bytes'); }); @@ -23,22 +23,22 @@ if (process.argv[2] === 'server') { } else { // Client - var serverProcess = cp.spawn(process.execPath, [process.argv[1], 'server']); + const serverProcess = cp.spawn(process.execPath, [process.argv[1], 'server']); serverProcess.stdout.pipe(process.stdout); serverProcess.stderr.pipe(process.stdout); serverProcess.stdout.once('data', function() { - var client = net.createConnection(common.PORT, '127.0.0.1'); + const client = net.createConnection(common.PORT, '127.0.0.1'); client.on('connect', function() { const alot = Buffer.allocUnsafe(1024); const alittle = Buffer.allocUnsafe(1); - for (var i = 0; i < 100; i++) { + for (let i = 0; i < 100; i++) { client.write(alot); } // Block the event loop for 1 second - var start = (new Date()).getTime(); + const start = (new Date()).getTime(); while ((new Date()).getTime() < start + 1000) {} client.write(alittle); diff --git a/test/sequential/test-regress-GH-1726.js b/test/sequential/test-regress-GH-1726.js index 0097ed913dbd09..c464193b23f3e4 100644 --- a/test/sequential/test-regress-GH-1726.js +++ b/test/sequential/test-regress-GH-1726.js @@ -8,8 +8,8 @@ require('../common'); const assert = require('assert'); const ch = require('child_process'); -var gen = +(process.argv[2] || 0); -var maxGen = 5; +const gen = +(process.argv[2] || 0); +const maxGen = 5; if (gen === maxGen) { @@ -17,7 +17,7 @@ if (gen === maxGen) { return; } -var child = ch.spawn(process.execPath, [__filename, gen + 1], { +const child = ch.spawn(process.execPath, [__filename, gen + 1], { stdio: [ 'ignore', 'pipe', 'ignore' ] }); assert.ok(!child.stdin); diff --git a/test/sequential/test-regress-GH-4015.js b/test/sequential/test-regress-GH-4015.js index 87b2b8561d9389..249817de1d2068 100644 --- a/test/sequential/test-regress-GH-4015.js +++ b/test/sequential/test-regress-GH-4015.js @@ -3,8 +3,8 @@ const common = require('../common'); const assert = require('assert'); const exec = require('child_process').exec; -var cmd = '"' + process.execPath + '" ' + - '"' + common.fixturesDir + '/test-regress-GH-4015.js"'; +const cmd = '"' + process.execPath + '" ' + + '"' + common.fixturesDir + '/test-regress-GH-4015.js"'; exec(cmd, function(err, stdout, stderr) { assert(/RangeError: Maximum call stack size exceeded/.test(stderr)); diff --git a/test/sequential/test-regress-GH-4027.js b/test/sequential/test-regress-GH-4027.js index 7653dda182fbe5..87a8861ac35477 100644 --- a/test/sequential/test-regress-GH-4027.js +++ b/test/sequential/test-regress-GH-4027.js @@ -6,7 +6,7 @@ const fs = require('fs'); common.refreshTmpDir(); -var filename = path.join(common.tmpDir, 'watched'); +const filename = path.join(common.tmpDir, 'watched'); fs.writeFileSync(filename, 'quis custodiet ipsos custodes'); setTimeout(fs.unlinkSync, 100, filename); diff --git a/test/sequential/test-regress-GH-784.js b/test/sequential/test-regress-GH-784.js index 645ffeb6501c37..c9b630b0c81755 100644 --- a/test/sequential/test-regress-GH-784.js +++ b/test/sequential/test-regress-GH-784.js @@ -12,8 +12,8 @@ const http = require('http'); const assert = require('assert'); -var server = http.createServer(function(req, res) { - var body = ''; +const server = http.createServer(function(req, res) { + let body = ''; req.setEncoding('utf8'); req.on('data', function(chunk) { @@ -43,7 +43,7 @@ function serverOff() { pingping(); } -var responses = []; +const responses = []; function afterPing(result) { @@ -81,14 +81,14 @@ function afterPing(result) { function ping() { console.error('making req'); - var opt = { + const opt = { port: common.PORT, path: '/ping', method: 'POST' }; - var req = http.request(opt, function(res) { - var body = ''; + const req = http.request(opt, function(res) { + let body = ''; res.setEncoding('utf8'); res.on('data', function(chunk) { @@ -105,8 +105,8 @@ function ping() { req.end('PING'); - var gotEnd = false; - var hadError = false; + let gotEnd = false; + let hadError = false; req.on('error', function(error) { console.log('Error making ping req: ' + error); diff --git a/test/sequential/test-regress-GH-877.js b/test/sequential/test-regress-GH-877.js index 82229524ceaa9d..06c839aa483fa8 100644 --- a/test/sequential/test-regress-GH-877.js +++ b/test/sequential/test-regress-GH-877.js @@ -3,28 +3,28 @@ const common = require('../common'); const http = require('http'); const assert = require('assert'); -var N = 20; -var responses = 0; -var maxQueued = 0; +const N = 20; +let responses = 0; +let maxQueued = 0; -var agent = http.globalAgent; +const agent = http.globalAgent; agent.maxSockets = 10; -var server = http.createServer(function(req, res) { +const server = http.createServer(function(req, res) { res.writeHead(200); res.end('Hello World\n'); }); -var addrString = agent.getName({ host: '127.0.0.1', port: common.PORT }); +const addrString = agent.getName({ host: '127.0.0.1', port: common.PORT }); server.listen(common.PORT, '127.0.0.1', function() { - for (var i = 0; i < N; i++) { - var options = { + for (let i = 0; i < N; i++) { + const options = { host: '127.0.0.1', port: common.PORT }; - var req = http.get(options, function(res) { + const req = http.get(options, function(res) { if (++responses === N) { server.close(); } @@ -37,7 +37,7 @@ server.listen(common.PORT, '127.0.0.1', function() { agent.maxSockets + ' queued: ' + (agent.requests[addrString] ? agent.requests[addrString].length : 0)); - var agentRequests = agent.requests[addrString] ? + const agentRequests = agent.requests[addrString] ? agent.requests[addrString].length : 0; if (maxQueued < agentRequests) { diff --git a/test/sequential/test-repl-timeout-throw.js b/test/sequential/test-repl-timeout-throw.js index 344845e0202f1a..69664195567882 100644 --- a/test/sequential/test-repl-timeout-throw.js +++ b/test/sequential/test-repl-timeout-throw.js @@ -8,7 +8,7 @@ const child = spawn(process.execPath, [ '-i' ], { stdio: [null, null, 2] }); -var stdout = ''; +let stdout = ''; child.stdout.setEncoding('utf8'); child.stdout.on('data', function(c) { process.stdout.write(c); @@ -30,7 +30,7 @@ child.stdout.once('data', function() { setTimeout(fsTest, 50); function fsTest() { - var f = JSON.stringify(__filename); + const f = JSON.stringify(__filename); child.stdin.write('fs.readFile(' + f + ', thrower);\n'); setTimeout(eeTest, 50); } @@ -54,6 +54,6 @@ child.stdout.once('data', function() { child.on('close', function(c) { assert.strictEqual(c, 0); // make sure we got 3 throws, in the end. - var lastLine = stdout.trim().split(/\r?\n/).pop(); + const lastLine = stdout.trim().split(/\r?\n/).pop(); assert.strictEqual(lastLine, '> 3'); }); diff --git a/test/sequential/test-require-cache-without-stat.js b/test/sequential/test-require-cache-without-stat.js index 0549e5f72ee0ba..b591f1746b62d4 100644 --- a/test/sequential/test-require-cache-without-stat.js +++ b/test/sequential/test-require-cache-without-stat.js @@ -6,13 +6,13 @@ const common = require('../common'); const fs = require('fs'); const assert = require('assert'); -var counter = 0; +let counter = 0; // Switch out the two stat implementations so that they increase a counter // each time they are called. -var _statSync = fs.statSync; -var _stat = fs.stat; +const _statSync = fs.statSync; +const _stat = fs.stat; fs.statSync = function() { counter++; @@ -31,7 +31,7 @@ require('./../fixtures/a.js'); require('http'); console.log('counterBefore = %d', counter); -var counterBefore = counter; +const counterBefore = counter; // Now load the module a bunch of times with equivalent paths. // stat should not be called. @@ -47,6 +47,6 @@ for (let i = 0; i < 100; i++) { } console.log('counterAfter = %d', counter); -var counterAfter = counter; +const counterAfter = counter; assert.equal(counterBefore, counterAfter); diff --git a/test/sequential/test-stream2-fs.js b/test/sequential/test-stream2-fs.js index 3640749179c539..2891335c813562 100644 --- a/test/sequential/test-stream2-fs.js +++ b/test/sequential/test-stream2-fs.js @@ -3,14 +3,14 @@ const common = require('../common'); const assert = require('assert'); const fs = require('fs'); -var FSReadable = fs.ReadStream; +const FSReadable = fs.ReadStream; const path = require('path'); -var file = path.resolve(common.fixturesDir, 'x1024.txt'); +const file = path.resolve(common.fixturesDir, 'x1024.txt'); -var size = fs.statSync(file).size; +const size = fs.statSync(file).size; -var expectLengths = [1024]; +const expectLengths = [1024]; const util = require('util'); const Stream = require('stream'); @@ -34,8 +34,8 @@ TestWriter.prototype.end = function(c) { this.emit('results', this.buffer); }; -var r = new FSReadable(file); -var w = new TestWriter(); +const r = new FSReadable(file); +const w = new TestWriter(); w.on('results', function(res) { console.error(res, w.length); diff --git a/test/sequential/test-stream2-stderr-sync.js b/test/sequential/test-stream2-stderr-sync.js index 2855a5f0970d41..e37a5f2cd1b38e 100644 --- a/test/sequential/test-stream2-stderr-sync.js +++ b/test/sequential/test-stream2-stderr-sync.js @@ -6,10 +6,10 @@ require('../common'); function parent() { const spawn = require('child_process').spawn; const assert = require('assert'); - var i = 0; + let i = 0; children.forEach(function(_, c) { - var child = spawn(process.execPath, [__filename, '' + c]); - var err = ''; + const child = spawn(process.execPath, [__filename, '' + c]); + let err = ''; child.stderr.on('data', function(c) { err += c; @@ -43,7 +43,7 @@ function child1() { // using a net socket function child2() { const net = require('net'); - var socket = new net.Socket({ + const socket = new net.Socket({ fd: 2, readable: false, writable: true}); @@ -62,7 +62,7 @@ function child4() { process.stderr.write('child 4\nfoo\nbar\nbaz\n'); } -var children = [ child0, child1, child2, child3, child4 ]; +const children = [ child0, child1, child2, child3, child4 ]; if (!process.argv[2]) { parent(); diff --git a/test/sequential/test-timers-blocking-callback.js b/test/sequential/test-timers-blocking-callback.js index e4e85cddc6302d..73b0f13997716d 100644 --- a/test/sequential/test-timers-blocking-callback.js +++ b/test/sequential/test-timers-blocking-callback.js @@ -28,9 +28,9 @@ const Timer = process.binding('timer_wrap').Timer; const TIMEOUT = 100; -var nbBlockingCallbackCalls = 0; -var latestDelay = 0; -var timeCallbackScheduled = 0; +let nbBlockingCallbackCalls = 0; +let latestDelay = 0; +let timeCallbackScheduled = 0; function initTest() { nbBlockingCallbackCalls = 0; diff --git a/test/sequential/test-vm-timeout-rethrow.js b/test/sequential/test-vm-timeout-rethrow.js index d55a9b310c15a4..a434e2ae3e6978 100644 --- a/test/sequential/test-vm-timeout-rethrow.js +++ b/test/sequential/test-vm-timeout-rethrow.js @@ -5,11 +5,11 @@ const vm = require('vm'); const spawn = require('child_process').spawn; if (process.argv[2] === 'child') { - var code = 'var j = 0;\n' + - 'for (var i = 0; i < 1000000; i++) j += add(i, i + 1);\n' + - 'j;'; + const code = 'let j = 0;\n' + + 'for (let i = 0; i < 1000000; i++) j += add(i, i + 1);\n' + + 'j;'; - var ctx = vm.createContext({ + const ctx = vm.createContext({ add: function(x, y) { return x + y; } @@ -17,8 +17,8 @@ if (process.argv[2] === 'child') { vm.runInContext(code, ctx, { timeout: 1 }); } else { - var proc = spawn(process.execPath, process.argv.slice(1).concat('child')); - var err = ''; + const proc = spawn(process.execPath, process.argv.slice(1).concat('child')); + let err = ''; proc.stderr.on('data', function(data) { err += data; }); diff --git a/test/timers/test-timers-reliability.js b/test/timers/test-timers-reliability.js index 11dd0a225d9e7f..9a9834aefecc7f 100644 --- a/test/timers/test-timers-reliability.js +++ b/test/timers/test-timers-reliability.js @@ -3,11 +3,11 @@ require('../common'); -var Timer = process.binding('timer_wrap').Timer; +const Timer = process.binding('timer_wrap').Timer; const assert = require('assert'); -var timerFired = false; -var intervalFired = false; +let timerFired = false; +let intervalFired = false; /* * This test case aims at making sure that timing utilities such @@ -31,7 +31,7 @@ var intervalFired = false; * is vulnerable to time drift or inconsistent time changes. */ -var monoTimer = new Timer(); +const monoTimer = new Timer(); monoTimer[Timer.kOnTimeout] = function() { /* * Make sure that setTimeout's and setInterval's callbacks have @@ -48,7 +48,7 @@ setTimeout(function() { timerFired = true; }, 200); -var interval = setInterval(function() { +const interval = setInterval(function() { intervalFired = true; clearInterval(interval); }, 200); From 31f8f6f7685672b7c41ad30752d1bc43d34f1b0e Mon Sep 17 00:00:00 2001 From: Gibson Fahnestock Date: Sun, 8 Jan 2017 15:23:00 +0000 Subject: [PATCH 195/291] tools, test: require const/let in test PR-URL: https://github.com/nodejs/node/pull/10685 Reviewed-By: Colin Ihrig Reviewed-By: James M Snell Reviewed-By: Roman Reiss --- test/.eslintrc.yaml | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/test/.eslintrc.yaml b/test/.eslintrc.yaml index 5e73630174e75e..e76bd632e6927c 100644 --- a/test/.eslintrc.yaml +++ b/test/.eslintrc.yaml @@ -1,7 +1,13 @@ ## Test-specific linter rules rules: - ## common module is mandatory in tests - required-modules: [2, common] + # ECMAScript 6 + # http://eslint.org/docs/rules/#ecmascript-6 + no-var: 2 + prefer-const: 2 + + # Custom rules in tools/eslint-rules prefer-assert-iferror: 2 prefer-assert-methods: 2 + ## common module is mandatory in tests + required-modules: [2, common] From 51f4c8bf5cd80d41071589ecafacbad7053f02d1 Mon Sep 17 00:00:00 2001 From: Gibson Fahnestock Date: Sun, 8 Jan 2017 15:36:25 +0000 Subject: [PATCH 196/291] test: s/assert.equal/assert.strictEqual/ MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Use assert.strictEqual instead of assert.equal in tests, manually convert types where necessary. PR-URL: https://github.com/nodejs/node/pull/10698 Reviewed-By: James M Snell Reviewed-By: Colin Ihrig Reviewed-By: Michael Dawson Reviewed-By: Sakthipriyan Vairamani Reviewed-By: Michaël Zasso Reviewed-By: Teddy Katz --- test/disabled/test-fs-largefile.js | 8 +- test/disabled/test-http-abort-stream-end.js | 2 +- test/disabled/test-readline.js | 14 +- test/disabled/test-sendfd.js | 10 +- test/disabled/test-setuidgid.js | 2 +- test/fixtures/GH-892-request.js | 2 +- test/fixtures/b/c.js | 2 +- test/fixtures/node_modules/baz/index.js | 4 +- test/fixtures/node_modules/foo.js | 2 +- test/internet/test-dns-txt-sigsegv.js | 4 +- test/message/error_exit.js | 2 +- test/message/error_exit.out | 2 +- test/parallel/test-assert.js | 38 +-- test/parallel/test-buffer-indexof.js | 250 +++++++++--------- test/parallel/test-child-process-fork-net.js | 2 +- test/parallel/test-child-process-fork-net2.js | 4 +- test/parallel/test-child-process-fork-ref.js | 2 +- test/parallel/test-child-process-ipc.js | 2 +- .../test-child-process-set-blocking.js | 2 +- .../test-child-process-spawnsync-env.js | 2 +- test/parallel/test-crypto-dh.js | 66 ++--- test/parallel/test-crypto-domains.js | 2 +- test/parallel/test-dh-padding.js | 2 +- test/parallel/test-domain-nested.js | 2 +- test/parallel/test-event-emitter-prepend.js | 7 +- test/parallel/test-event-emitter-subclass.js | 2 +- test/parallel/test-fs-error-messages.js | 6 +- test/parallel/test-fs-mkdir-rmdir.js | 4 +- test/parallel/test-fs-mkdir.js | 4 +- test/parallel/test-fs-mkdtemp.js | 4 +- test/parallel/test-fs-open-flags.js | 30 +-- .../test-fs-read-buffer-zero-length.js | 4 +- test/parallel/test-fs-read-stream.js | 2 +- test/parallel/test-fs-read-zero-length.js | 8 +- test/parallel/test-fs-readdir-ucs2.js | 2 +- test/parallel/test-fs-readdir.js | 2 +- test/parallel/test-fs-realpath.js | 4 +- test/parallel/test-fs-stat.js | 14 +- test/parallel/test-fs-sync-fd-leak.js | 8 +- test/parallel/test-fs-watch-enoent.js | 4 +- test/parallel/test-fs-watch-stop-async.js | 4 +- .../test-fs-write-stream-change-open.js | 2 +- test/parallel/test-fs-write-stream-err.js | 8 +- test/parallel/test-fs-write-string-coerce.js | 2 +- test/parallel/test-http-abort-queued.js | 22 +- .../parallel/test-http-agent-error-on-idle.js | 10 +- test/parallel/test-http-agent-keepalive.js | 50 ++-- test/parallel/test-http-agent-maxsockets.js | 8 +- test/parallel/test-http-agent.js | 2 +- test/parallel/test-http-automatic-headers.js | 12 +- test/parallel/test-http-blank-header.js | 4 +- test/parallel/test-http-buffer-sanity.js | 6 +- .../test-http-catch-uncaughtexception.js | 2 +- test/parallel/test-http-chunk-problem.js | 4 +- test/parallel/test-http-chunked.js | 4 +- test/parallel/test-http-client-abort.js | 2 +- test/parallel/test-http-client-agent.js | 4 +- test/parallel/test-http-client-get-url.js | 4 +- test/parallel/test-http-client-parse-error.js | 6 +- test/parallel/test-http-client-race-2.js | 6 +- test/parallel/test-http-client-race.js | 4 +- ...ient-reject-chunked-with-content-length.js | 2 +- .../test-http-client-reject-cr-no-lf.js | 2 +- .../test-http-client-response-domain.js | 2 +- test/parallel/test-http-client-upload-buf.js | 2 +- test/parallel/test-http-client-upload.js | 2 +- test/parallel/test-http-conn-reset.js | 2 +- test/parallel/test-http-connect-req-res.js | 12 +- test/parallel/test-http-createConnection.js | 2 +- test/parallel/test-http-default-encoding.js | 2 +- test/parallel/test-http-default-port.js | 8 +- .../test-http-destroyed-socket-write2.js | 4 +- .../test-http-double-content-length.js | 2 +- test/parallel/test-http-expect-continue.js | 13 +- test/parallel/test-http-expect-handling.js | 6 +- test/parallel/test-http-extra-response.js | 4 +- test/parallel/test-http-flush-headers.js | 2 +- .../test-http-flush-response-headers.js | 2 +- test/parallel/test-http-full-response.js | 4 +- .../test-http-get-pipeline-problem.js | 8 +- test/parallel/test-http-header-read.js | 2 +- test/parallel/test-http-host-headers.js | 6 +- .../test-http-keep-alive-close-on-header.js | 8 +- test/parallel/test-http-keepalive-client.js | 8 +- .../test-http-keepalive-maxsockets.js | 14 +- test/parallel/test-http-keepalive-request.js | 8 +- test/parallel/test-http-localaddress.js | 2 +- test/parallel/test-http-malformed-request.js | 2 +- test/parallel/test-http-max-headers-count.js | 8 +- test/parallel/test-http-multi-line-headers.js | 4 +- test/parallel/test-http-parser-bad-ref.js | 4 +- test/parallel/test-http-parser-free.js | 2 +- test/parallel/test-http-parser.js | 12 +- test/parallel/test-http-pause.js | 4 +- test/parallel/test-http-pipeline-regr-2639.js | 2 +- test/parallel/test-http-pipeline-regr-3332.js | 2 +- test/parallel/test-http-proxy.js | 12 +- .../test-http-remove-header-stays-removed.js | 4 +- ...test-http-request-dont-override-options.js | 2 +- .../parallel/test-http-res-write-after-end.js | 2 +- ...test-http-response-multi-content-length.js | 4 +- .../test-http-response-multiheaders.js | 4 +- .../parallel/test-http-response-no-headers.js | 2 +- test/parallel/test-http-response-readable.js | 5 +- .../test-http-response-status-message.js | 4 +- .../parallel/test-http-server-client-error.js | 4 +- .../parallel/test-http-server-multiheaders.js | 19 +- .../test-http-server-multiheaders2.js | 8 +- ...rver-reject-chunked-with-content-length.js | 2 +- .../test-http-server-reject-cr-no-lf.js | 2 +- test/parallel/test-http-server-unconsume.js | 2 +- test/parallel/test-http-set-cookies.js | 6 +- test/parallel/test-http-set-timeout-server.js | 2 +- test/parallel/test-http-should-keep-alive.js | 8 +- test/parallel/test-http-status-code.js | 6 +- test/parallel/test-http-status-message.js | 2 +- test/parallel/test-http-timeout-overflow.js | 4 +- test/parallel/test-http-upgrade-advertise.js | 2 +- test/parallel/test-http-upgrade-agent.js | 2 +- test/parallel/test-http-upgrade-server.js | 18 +- test/parallel/test-http-upgrade-server2.js | 2 +- test/parallel/test-http-write-callbacks.js | 6 +- test/parallel/test-http-write-empty-string.js | 2 +- test/parallel/test-http-write-head.js | 5 +- test/parallel/test-http-zero-length-write.js | 4 +- test/parallel/test-http.js | 2 +- .../test-https-agent-disable-session-reuse.js | 4 +- test/parallel/test-https-agent-sni.js | 2 +- test/parallel/test-https-client-get-url.js | 4 +- test/parallel/test-https-drain.js | 2 +- test/parallel/test-https-eof-for-eom.js | 2 +- test/parallel/test-https-foafssl.js | 2 +- test/parallel/test-https-host-headers.js | 6 +- test/parallel/test-https-localaddress.js | 2 +- test/parallel/test-https-pfx.js | 5 +- .../parallel/test-https-set-timeout-server.js | 2 +- test/parallel/test-https-simple.js | 6 +- test/parallel/test-internal-modules-expose.js | 2 +- test/parallel/test-listen-fd-cluster.js | 4 +- .../test-listen-fd-detached-inherit.js | 4 +- test/parallel/test-listen-fd-detached.js | 4 +- test/parallel/test-listen-fd-server.js | 4 +- test/parallel/test-memory-usage-emfile.js | 2 +- ...test-microtask-queue-integration-domain.js | 2 +- .../test-microtask-queue-integration.js | 2 +- .../test-microtask-queue-run-domain.js | 2 +- ...st-microtask-queue-run-immediate-domain.js | 2 +- .../test-microtask-queue-run-immediate.js | 2 +- test/parallel/test-microtask-queue-run.js | 2 +- .../test-net-better-error-messages-path.js | 4 +- test/parallel/test-net-binary.js | 2 +- test/parallel/test-net-bind-twice.js | 2 +- test/parallel/test-net-bytes-read.js | 8 +- test/parallel/test-net-bytes-stats.js | 4 +- test/parallel/test-net-connect-buffer.js | 12 +- test/parallel/test-net-connect-local-error.js | 4 +- test/parallel/test-net-create-connection.js | 2 +- test/parallel/test-net-dns-error.js | 8 +- test/parallel/test-net-dns-lookup.js | 8 +- test/parallel/test-net-eaddrinuse.js | 2 +- test/parallel/test-net-error-twice.js | 2 +- test/parallel/test-net-isip.js | 120 ++++----- .../test-net-listen-exclusive-random-ports.js | 4 +- test/parallel/test-net-listen-shared-ports.js | 4 +- .../parallel/test-net-persistent-keepalive.js | 6 +- test/parallel/test-net-persistent-nodelay.js | 2 +- .../parallel/test-net-persistent-ref-unref.js | 6 +- test/parallel/test-net-reconnect.js | 12 +- test/parallel/test-net-server-bind.js | 10 +- test/parallel/test-net-server-close.js | 8 +- test/parallel/test-net-server-connections.js | 2 +- .../test-net-server-listen-remove-callback.js | 2 +- ...-connections-close-makes-more-available.js | 2 +- .../test-net-server-pause-on-connect.js | 9 +- test/parallel/test-net-stream.js | 8 +- test/parallel/test-net-sync-cork.js | 4 +- test/parallel/test-next-tick-ordering.js | 4 +- test/parallel/test-next-tick.js | 4 +- test/parallel/test-npm-install.js | 2 +- test/parallel/test-os-homedir-no-envvar.js | 2 +- test/parallel/test-path-makelong.js | 27 +- test/parallel/test-path-parse-format.js | 2 +- .../parallel/test-path-zero-length-strings.js | 32 +-- test/parallel/test-path.js | 2 +- test/parallel/test-pipe-stream.js | 4 +- test/parallel/test-process-argv-0.js | 2 +- test/parallel/test-process-env.js | 4 +- test/parallel/test-process-exit-code.js | 10 +- test/parallel/test-process-exit-recursive.js | 4 +- test/parallel/test-process-exit.js | 4 +- .../test-process-getactiverequests.js | 2 +- test/parallel/test-process-getgroups.js | 2 +- test/parallel/test-process-kill-pid.js | 4 +- test/parallel/test-process-raw-debug.js | 2 +- ...est-process-remove-all-signal-listeners.js | 2 +- test/parallel/test-process-wrap.js | 4 +- .../test-promises-unhandled-rejections.js | 2 +- .../test-querystring-maxKeys-non-finite.js | 8 +- test/parallel/test-querystring.js | 56 ++-- test/parallel/test-readdouble.js | 56 ++-- test/parallel/test-readfloat.js | 34 +-- test/parallel/test-readint.js | 60 ++--- test/parallel/test-readline-interface.js | 101 +++---- test/parallel/test-readline-set-raw-mode.js | 4 +- test/parallel/test-readuint.js | 38 +-- test/parallel/test-regress-GH-1899.js | 4 +- test/parallel/test-regress-GH-5051.js | 8 +- test/parallel/test-regress-GH-5727.js | 2 +- test/parallel/test-repl-.save.load.js | 10 +- test/parallel/test-repl-autolibs.js | 9 +- test/parallel/test-repl-end-emits-exit.js | 4 +- test/parallel/test-repl-envvars.js | 8 +- test/parallel/test-repl-options.js | 66 ++--- test/parallel/test-repl-require-cache.js | 4 +- .../test-repl-syntax-error-handling.js | 2 +- test/parallel/test-repl-tab.js | 2 +- ...ons-same-filename-as-dir-trailing-slash.js | 2 +- test/parallel/test-require-unicode.js | 4 +- .../test-socket-write-after-fin-error.js | 6 +- test/parallel/test-stdin-child-proc.js | 2 +- test/parallel/test-stdin-pipe-resume.js | 2 +- ...out-cannot-be-closed-child-process-pipe.js | 2 +- test/parallel/test-stdout-stderr-reading.js | 4 +- test/parallel/test-stream-base-no-abort.js | 8 +- test/parallel/test-stream-push-strings.js | 2 +- ...stream-readable-constructor-set-methods.js | 2 +- .../test-stream-readable-flow-recursion.js | 8 +- ...tream-transform-constructor-set-methods.js | 4 +- ...stream-writable-change-default-encoding.js | 6 +- ...stream-writable-constructor-set-methods.js | 6 +- ...ableState-uncorked-bufferedRequestCount.js | 2 +- test/parallel/test-stream-writev.js | 2 +- ...est-stream2-base64-single-char-read-end.js | 2 +- test/parallel/test-stream2-compatibility.js | 2 +- .../parallel/test-stream2-large-read-stall.js | 2 +- test/parallel/test-stream2-objects.js | 2 +- .../test-stream2-readable-from-list.js | 4 +- .../test-stream2-readable-non-empty-end.js | 4 +- test/parallel/test-stream2-set-encoding.js | 4 +- test/parallel/test-stream2-transform.js | 4 +- test/parallel/test-stream2-unpipe-leak.js | 16 +- test/parallel/test-stream3-cork-end.js | 8 +- test/parallel/test-stream3-cork-uncork.js | 8 +- test/parallel/test-stream3-pause-then-read.js | 8 +- test/parallel/test-string-decoder-end.js | 4 +- test/parallel/test-stringbytes-external.js | 30 +-- test/parallel/test-sync-io-option.js | 8 +- test/parallel/test-tcp-wrap.js | 4 +- ...st-timers-reset-process-domain-on-throw.js | 2 +- test/parallel/test-timers-unref-active.js | 2 +- test/parallel/test-timers-unref-leak.js | 4 +- test/parallel/test-timers.js | 4 +- test/parallel/test-tls-cipher-list.js | 2 +- .../test-tls-client-default-ciphers.js | 2 +- .../test-tls-client-getephemeralkeyinfo.js | 4 +- test/parallel/test-tls-client-mindhsize.js | 4 +- test/parallel/test-tls-client-verify.js | 2 +- test/parallel/test-tls-delayed-attach.js | 2 +- test/parallel/test-tls-dhe.js | 4 +- test/parallel/test-tls-env-bad-extra-ca.js | 2 +- test/parallel/test-tls-env-extra-ca.js | 2 +- test/parallel/test-tls-honorcipherorder.js | 4 +- test/parallel/test-tls-js-stream.js | 4 +- test/parallel/test-tls-no-rsa-key.js | 2 +- test/parallel/test-tls-npn-server-client.js | 12 +- test/parallel/test-tls-over-http-tunnel.js | 17 +- test/parallel/test-tls-pause.js | 2 +- .../test-tls-peer-certificate-encoding.js | 2 +- test/parallel/test-tls-server-verify.js | 2 +- test/parallel/test-tls-session-cache.js | 12 +- .../test-tls-socket-default-options.js | 2 +- test/parallel/test-umask.js | 6 +- test/parallel/test-url.js | 20 +- test/parallel/test-utf8-scripts.js | 2 +- test/parallel/test-util-log.js | 2 +- test/parallel/test-util.js | 112 ++++---- test/parallel/test-v8-stats.js | 2 +- test/parallel/test-vm-cached-data.js | 6 +- test/parallel/test-vm-context.js | 12 +- .../test-vm-create-and-run-in-context.js | 10 +- ...st-vm-create-context-circular-reference.js | 2 +- test/parallel/test-vm-function-declaration.js | 10 +- .../test-vm-global-define-property.js | 6 +- .../test-vm-new-script-new-context.js | 16 +- .../test-vm-new-script-this-context.js | 12 +- test/parallel/test-vm-run-in-new-context.js | 17 +- test/parallel/test-vm-syntax-error-message.js | 2 +- test/parallel/test-whatwg-url-setters.js | 5 +- test/parallel/test-writedouble.js | 232 ++++++++-------- test/parallel/test-writefloat.js | 118 ++++----- test/parallel/test-writeint.js | 128 ++++----- test/parallel/test-writeuint.js | 100 +++---- test/parallel/test-zlib-const.js | 10 +- .../parallel/test-zlib-convenience-methods.js | 18 +- test/parallel/test-zlib-flush-drain.js | 16 +- .../test-zlib-from-concatenated-gzip.js | 11 +- test/parallel/test-zlib-from-gzip.js | 4 +- test/parallel/test-zlib-from-string.js | 16 +- test/parallel/test-zlib-random-byte-pipes.js | 2 +- test/parallel/test-zlib-write-after-flush.js | 4 +- test/pummel/test-crypto-dh.js | 4 +- test/pummel/test-dtrace-jsstack.js | 5 +- test/pummel/test-fs-watch-file-slow.js | 8 +- test/pummel/test-fs-watch-file.js | 10 +- .../test-http-many-keep-alive-connections.js | 6 +- test/pummel/test-https-ci-reneg-attack.js | 4 +- test/pummel/test-net-connect-econnrefused.js | 10 +- test/pummel/test-net-many-clients.js | 6 +- test/pummel/test-net-pause.js | 8 +- test/pummel/test-net-pingpong-delay.js | 28 +- test/pummel/test-net-pingpong.js | 32 +-- test/pummel/test-net-throttle.js | 8 +- test/pummel/test-net-timeout.js | 2 +- test/pummel/test-net-write-callbacks.js | 2 +- test/pummel/test-regress-GH-892.js | 6 +- test/pummel/test-stream-pipe-multi.js | 4 +- test/pummel/test-stream2-basic.js | 28 +- test/pummel/test-timers.js | 29 +- test/pummel/test-tls-ci-reneg-attack.js | 4 +- test/pummel/test-tls-securepair-client.js | 11 +- test/pummel/test-tls-server-large-request.js | 2 +- test/pummel/test-tls-throttle.js | 2 +- .../test-child-process-fork-getconnections.js | 6 +- test/sequential/test-deprecation-flags.js | 18 +- test/sequential/test-http-regr-gh-2928.js | 2 +- test/sequential/test-process-warnings.js | 12 +- test/sequential/test-regress-GH-4027.js | 4 +- test/sequential/test-regress-GH-784.js | 6 +- test/sequential/test-regress-GH-877.js | 2 +- .../test-require-cache-without-stat.js | 2 +- test/sequential/test-stream2-fs.js | 2 +- test/sequential/test-stream2-stderr-sync.js | 2 +- 332 files changed, 1710 insertions(+), 1671 deletions(-) diff --git a/test/disabled/test-fs-largefile.js b/test/disabled/test-fs-largefile.js index b78378548413b7..365cdec188d5c7 100644 --- a/test/disabled/test-fs-largefile.js +++ b/test/disabled/test-fs-largefile.js @@ -9,14 +9,14 @@ const path = require('path'), message = 'Large File'; fs.truncateSync(fd, offset); -assert.equal(fs.statSync(filepath).size, offset); +assert.strictEqual(fs.statSync(filepath).size, offset); var writeBuf = Buffer.from(message); fs.writeSync(fd, writeBuf, 0, writeBuf.length, offset); var readBuf = Buffer.allocUnsafe(writeBuf.length); fs.readSync(fd, readBuf, 0, readBuf.length, offset); -assert.equal(readBuf.toString(), message); +assert.strictEqual(readBuf.toString(), message); fs.readSync(fd, readBuf, 0, 1, 0); -assert.equal(readBuf[0], 0); +assert.strictEqual(readBuf[0], 0); var exceptionRaised = false; try { @@ -24,7 +24,7 @@ try { } catch (err) { console.log(err); exceptionRaised = true; - assert.equal(err.message, 'Not an integer'); + assert.strictEqual(err.message, 'Not an integer'); } assert.ok(exceptionRaised); fs.close(fd); diff --git a/test/disabled/test-http-abort-stream-end.js b/test/disabled/test-http-abort-stream-end.js index 3e8bff21248ca2..5dc51d9eee911f 100644 --- a/test/disabled/test-http-abort-stream-end.js +++ b/test/disabled/test-http-abort-stream-end.js @@ -36,6 +36,6 @@ s.listen(common.PORT, function() { process.on('exit', function() { assert(aborted); - assert.equal(size, maxSize); + assert.strictEqual(size, maxSize); console.log('ok'); }); diff --git a/test/disabled/test-readline.js b/test/disabled/test-readline.js index 7896833b93d186..4273f1013415e4 100644 --- a/test/disabled/test-readline.js +++ b/test/disabled/test-readline.js @@ -49,12 +49,12 @@ var rl = readlineFakeStream(); var written_bytes_length, refreshed; rl.write('foo'); -assert.equal(3, rl.cursor); +assert.strictEqual(3, rl.cursor); [key.xterm, key.rxvt, key.gnome, key.putty].forEach(function(key) { rl.write.apply(rl, key.home); - assert.equal(0, rl.cursor); + assert.strictEqual(0, rl.cursor); rl.write.apply(rl, key.end); - assert.equal(3, rl.cursor); + assert.strictEqual(3, rl.cursor); }); rl = readlineFakeStream(); @@ -76,9 +76,9 @@ rl.write.apply(rl, key.xterm.home); ].forEach(function(action) { written_bytes_length = rl.written_bytes.length; rl.write.apply(rl, action.key); - assert.equal(action.cursor, rl.cursor); + assert.strictEqual(action.cursor, rl.cursor); refreshed = written_bytes_length !== rl.written_bytes.length; - assert.equal(true, refreshed); + assert.strictEqual(true, refreshed); }); rl = readlineFakeStream(); @@ -93,7 +93,7 @@ rl.write.apply(rl, key.xterm.home); '' ].forEach(function(expectedLine) { rl.write.apply(rl, key.xterm.metad); - assert.equal(0, rl.cursor); - assert.equal(expectedLine, rl.line); + assert.strictEqual(0, rl.cursor); + assert.strictEqual(expectedLine, rl.line); }); rl.close(); diff --git a/test/disabled/test-sendfd.js b/test/disabled/test-sendfd.js index 969e8b5850dfe2..9f1159e30a401c 100644 --- a/test/disabled/test-sendfd.js +++ b/test/disabled/test-sendfd.js @@ -63,7 +63,7 @@ var logChild = function(d) { // validate any data sent back by the child. We send the write end of the // pipe to the child and close it off in our process. var pipeFDs = netBinding.pipe(); -assert.equal(pipeFDs.length, 2); +assert.strictEqual(pipeFDs.length, 2); var seenOrdinals = []; @@ -72,8 +72,8 @@ pipeReadStream.on('data', function(data) { data.toString('utf8').trim().split('\n').forEach(function(d) { var rd = JSON.parse(d); - assert.equal(rd.pid, cpp); - assert.equal(seenOrdinals.indexOf(rd.ord), -1); + assert.strictEqual(rd.pid, cpp); + assert.strictEqual(seenOrdinals.indexOf(rd.ord), -1); seenOrdinals.unshift(rd.ord); }); @@ -119,8 +119,8 @@ cp.on('exit', function(code, signal) { srv.close(); // fs.unlinkSync(SOCK_PATH); - assert.equal(code, 0); - assert.equal(seenOrdinals.length, 2); + assert.strictEqual(code, 0); + assert.strictEqual(seenOrdinals.length, 2); }); // vim:ts=2 sw=2 et diff --git a/test/disabled/test-setuidgid.js b/test/disabled/test-setuidgid.js index 3603e9bb421a26..14a480fd958923 100644 --- a/test/disabled/test-setuidgid.js +++ b/test/disabled/test-setuidgid.js @@ -16,7 +16,7 @@ assert.notStrictEqual(newuid, olduid, 'uids expected to be different'); try { process.setuid('nobody1234'); } catch (e) { - assert.equal(e.message, + assert.strictEqual(e.message, 'failed to resolve group', 'unexpected error message' ); diff --git a/test/fixtures/GH-892-request.js b/test/fixtures/GH-892-request.js index eccbafcf4399c2..d0db3e29ff5023 100644 --- a/test/fixtures/GH-892-request.js +++ b/test/fixtures/GH-892-request.js @@ -16,7 +16,7 @@ var options = { }; var req = https.request(options, function(res) { - assert.equal(200, res.statusCode); + assert.strictEqual(200, res.statusCode); gotResponse = true; console.error('DONE'); res.resume(); diff --git a/test/fixtures/b/c.js b/test/fixtures/b/c.js index a27baeb658ae50..2305e5b28635bc 100644 --- a/test/fixtures/b/c.js +++ b/test/fixtures/b/c.js @@ -4,7 +4,7 @@ const assert = require('assert'); const package = require('./package'); -assert.equal('world', package.hello); +assert.strictEqual('world', package.hello); console.error('load fixtures/b/c.js'); diff --git a/test/fixtures/node_modules/baz/index.js b/test/fixtures/node_modules/baz/index.js index 59fc9fe79bcb61..939f0351699195 100644 --- a/test/fixtures/node_modules/baz/index.js +++ b/test/fixtures/node_modules/baz/index.js @@ -2,9 +2,9 @@ console.error(__filename); console.error(module.paths.join('\n') + '\n'); // this should work, and get the one that doesn't throw const assert = require('assert'); -assert.equal(require('bar'), require('../bar.js')); +assert.strictEqual(require('bar'), require('../bar.js')); // this should work, and get the one in ./node_modules/asdf.js -assert.equal(require('asdf'), require('./node_modules/asdf.js')); +assert.strictEqual(require('asdf'), require('./node_modules/asdf.js')); module.exports = 'eye catcher'; diff --git a/test/fixtures/node_modules/foo.js b/test/fixtures/node_modules/foo.js index 56a98f76a86ddf..4d4cc9fe12fbc8 100644 --- a/test/fixtures/node_modules/foo.js +++ b/test/fixtures/node_modules/foo.js @@ -1,4 +1,4 @@ console.error(__filename); console.error(module.paths.join('\n') + '\n'); const assert = require('assert'); -assert.equal(require('baz'), require('./baz/index.js')); +assert.strictEqual(require('baz'), require('./baz/index.js')); diff --git a/test/internet/test-dns-txt-sigsegv.js b/test/internet/test-dns-txt-sigsegv.js index 3c85d546cfcddd..54cc4648510ed7 100644 --- a/test/internet/test-dns-txt-sigsegv.js +++ b/test/internet/test-dns-txt-sigsegv.js @@ -4,6 +4,6 @@ const assert = require('assert'); const dns = require('dns'); dns.resolveTxt('www.microsoft.com', function(err, records) { - assert.equal(err, null); - assert.equal(records.length, 0); + assert.strictEqual(err, null); + assert.strictEqual(records.length, 0); }); diff --git a/test/message/error_exit.js b/test/message/error_exit.js index 7235801514dd45..1cb785a1b543a6 100644 --- a/test/message/error_exit.js +++ b/test/message/error_exit.js @@ -6,4 +6,4 @@ process.on('exit', function(code) { console.error('Exiting with code=%d', code); }); -assert.equal(1, 2); +assert.strictEqual(1, 2); diff --git a/test/message/error_exit.out b/test/message/error_exit.out index e25af05861b5ce..e2a29ab42dbbd2 100644 --- a/test/message/error_exit.out +++ b/test/message/error_exit.out @@ -3,7 +3,7 @@ Exiting with code=1 assert.js:* throw new assert.AssertionError({ ^ -AssertionError: 1 == 2 +AssertionError: 1 === 2 at Object. (*test*message*error_exit.js:*:*) at Module._compile (module.js:*:*) at Object.Module._extensions..js (module.js:*:*) diff --git a/test/parallel/test-assert.js b/test/parallel/test-assert.js index 346776ef5ed483..8cba5ed517aa16 100644 --- a/test/parallel/test-assert.js +++ b/test/parallel/test-assert.js @@ -353,9 +353,9 @@ try { threw = true; assert.ok(e instanceof TypeError, 'type'); } -assert.equal(true, threw, - 'a.throws with an explicit error is eating extra errors', - a.AssertionError); +assert.strictEqual(true, threw, + 'a.throws with an explicit error is eating extra errors', + a.AssertionError); threw = false; // doesNotThrow should pass through all errors @@ -365,8 +365,8 @@ try { threw = true; assert.ok(e instanceof TypeError); } -assert.equal(true, threw, - 'a.doesNotThrow with an explicit error is eating extra errors'); +assert.strictEqual(true, threw, 'a.doesNotThrow with an explicit error is ' + + 'eating extra errors'); // key difference is that throwing our correct error makes an assertion error try { @@ -375,8 +375,8 @@ try { threw = true; assert.ok(e instanceof a.AssertionError); } -assert.equal(true, threw, - 'a.doesNotThrow is not catching type matching errors'); +assert.strictEqual(true, threw, + 'a.doesNotThrow is not catching type matching errors'); assert.throws(function() { assert.ifError(new Error('test error')); }); assert.doesNotThrow(function() { assert.ifError(null); }); @@ -481,10 +481,10 @@ circular.x = circular; function testAssertionMessage(actual, expected) { try { - assert.equal(actual, ''); + assert.strictEqual(actual, ''); } catch (e) { - assert.equal(e.toString(), - ['AssertionError:', expected, '==', '\'\''].join(' ')); + assert.strictEqual(e.toString(), + ['AssertionError:', expected, '===', '\'\''].join(' ')); assert.ok(e.generatedMessage, 'Message not marked as generated'); } } @@ -519,24 +519,24 @@ try { }); } catch (e) { threw = true; - assert.equal(e.message, 'Missing expected exception..'); + assert.strictEqual(e.message, 'Missing expected exception..'); } assert.ok(threw); // #5292 try { - assert.equal(1, 2); + assert.strictEqual(1, 2); } catch (e) { - assert.equal(e.toString().split('\n')[0], 'AssertionError: 1 == 2'); + assert.strictEqual(e.toString().split('\n')[0], 'AssertionError: 1 === 2'); assert.ok(e.generatedMessage, 'Message not marked as generated'); } try { - assert.equal(1, 2, 'oh no'); + assert.strictEqual(1, 2, 'oh no'); } catch (e) { - assert.equal(e.toString().split('\n')[0], 'AssertionError: oh no'); - assert.equal(e.generatedMessage, false, - 'Message incorrectly marked as generated'); + assert.strictEqual(e.toString().split('\n')[0], 'AssertionError: oh no'); + assert.strictEqual(e.generatedMessage, false, + 'Message incorrectly marked as generated'); } // Verify that throws() and doesNotThrow() throw on non-function block @@ -547,8 +547,8 @@ function testBlockTypeError(method, block) { method(block); threw = false; } catch (e) { - assert.equal(e.toString(), - 'TypeError: "block" argument must be a function'); + assert.strictEqual(e.toString(), + 'TypeError: "block" argument must be a function'); } assert.ok(threw); diff --git a/test/parallel/test-buffer-indexof.js b/test/parallel/test-buffer-indexof.js index 503add948826ab..8efd318762684c 100644 --- a/test/parallel/test-buffer-indexof.js +++ b/test/parallel/test-buffer-indexof.js @@ -71,12 +71,12 @@ assert.strictEqual(b.indexOf('f', 5), 5); assert.strictEqual(b.indexOf('f', -1), 5); assert.strictEqual(b.indexOf('f', 6), -1); -assert.equal(b.indexOf(Buffer.from('d'), 2), 3); -assert.equal(b.indexOf(Buffer.from('f'), 5), 5); -assert.equal(b.indexOf(Buffer.from('f'), -1), 5); -assert.equal(b.indexOf(Buffer.from('f'), 6), -1); +assert.strictEqual(b.indexOf(Buffer.from('d'), 2), 3); +assert.strictEqual(b.indexOf(Buffer.from('f'), 5), 5); +assert.strictEqual(b.indexOf(Buffer.from('f'), -1), 5); +assert.strictEqual(b.indexOf(Buffer.from('f'), 6), -1); -assert.equal(Buffer.from('ff').indexOf(Buffer.from('f'), 1, 'ucs2'), -1); +assert.strictEqual(Buffer.from('ff').indexOf(Buffer.from('f'), 1, 'ucs2'), -1); // test invalid and uppercase encoding assert.strictEqual(b.indexOf('b', 'utf8'), 1); @@ -176,62 +176,67 @@ assert.strictEqual( // test optional offset with passed encoding -assert.equal(Buffer.from('aaaa0').indexOf('30', 'hex'), 4); -assert.equal(Buffer.from('aaaa00a').indexOf('3030', 'hex'), 4); +assert.strictEqual(Buffer.from('aaaa0').indexOf('30', 'hex'), 4); +assert.strictEqual(Buffer.from('aaaa00a').indexOf('3030', 'hex'), 4); { // test usc2 encoding const twoByteString = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2'); - assert.equal(8, twoByteString.indexOf('\u0395', 4, 'ucs2')); - assert.equal(6, twoByteString.indexOf('\u03a3', -4, 'ucs2')); - assert.equal(4, twoByteString.indexOf('\u03a3', -6, 'ucs2')); - assert.equal(4, twoByteString.indexOf( + assert.strictEqual(8, twoByteString.indexOf('\u0395', 4, 'ucs2')); + assert.strictEqual(6, twoByteString.indexOf('\u03a3', -4, 'ucs2')); + assert.strictEqual(4, twoByteString.indexOf('\u03a3', -6, 'ucs2')); + assert.strictEqual(4, twoByteString.indexOf( Buffer.from('\u03a3', 'ucs2'), -6, 'ucs2')); - assert.equal(-1, twoByteString.indexOf('\u03a3', -2, 'ucs2')); + assert.strictEqual(-1, twoByteString.indexOf('\u03a3', -2, 'ucs2')); } const mixedByteStringUcs2 = Buffer.from('\u039a\u0391abc\u03a3\u03a3\u0395', 'ucs2'); -assert.equal(6, mixedByteStringUcs2.indexOf('bc', 0, 'ucs2')); -assert.equal(10, mixedByteStringUcs2.indexOf('\u03a3', 0, 'ucs2')); -assert.equal(-1, mixedByteStringUcs2.indexOf('\u0396', 0, 'ucs2')); +assert.strictEqual(6, mixedByteStringUcs2.indexOf('bc', 0, 'ucs2')); +assert.strictEqual(10, mixedByteStringUcs2.indexOf('\u03a3', 0, 'ucs2')); +assert.strictEqual(-1, mixedByteStringUcs2.indexOf('\u0396', 0, 'ucs2')); -assert.equal( +assert.strictEqual( 6, mixedByteStringUcs2.indexOf(Buffer.from('bc', 'ucs2'), 0, 'ucs2')); -assert.equal( +assert.strictEqual( 10, mixedByteStringUcs2.indexOf(Buffer.from('\u03a3', 'ucs2'), 0, 'ucs2')); -assert.equal( +assert.strictEqual( -1, mixedByteStringUcs2.indexOf(Buffer.from('\u0396', 'ucs2'), 0, 'ucs2')); { const twoByteString = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2'); // Test single char pattern - assert.equal(0, twoByteString.indexOf('\u039a', 0, 'ucs2')); - assert.equal(2, twoByteString.indexOf('\u0391', 0, 'ucs2'), 'Alpha'); - assert.equal(4, twoByteString.indexOf('\u03a3', 0, 'ucs2'), 'First Sigma'); - assert.equal(6, twoByteString.indexOf('\u03a3', 6, 'ucs2'), 'Second Sigma'); - assert.equal(8, twoByteString.indexOf('\u0395', 0, 'ucs2'), 'Epsilon'); - assert.equal(-1, twoByteString.indexOf('\u0392', 0, 'ucs2'), 'Not beta'); + assert.strictEqual(0, twoByteString.indexOf('\u039a', 0, 'ucs2')); + assert.strictEqual(2, twoByteString.indexOf('\u0391', 0, 'ucs2'), + 'Alpha'); + assert.strictEqual(4, twoByteString.indexOf('\u03a3', 0, 'ucs2'), + 'First Sigma'); + assert.strictEqual(6, twoByteString.indexOf('\u03a3', 6, 'ucs2'), + 'Second Sigma'); + assert.strictEqual(8, twoByteString.indexOf('\u0395', 0, 'ucs2'), + 'Epsilon'); + assert.strictEqual(-1, twoByteString.indexOf('\u0392', 0, 'ucs2'), + 'Not beta'); // Test multi-char pattern - assert.equal( + assert.strictEqual( 0, twoByteString.indexOf('\u039a\u0391', 0, 'ucs2'), 'Lambda Alpha'); - assert.equal( + assert.strictEqual( 2, twoByteString.indexOf('\u0391\u03a3', 0, 'ucs2'), 'Alpha Sigma'); - assert.equal( + assert.strictEqual( 4, twoByteString.indexOf('\u03a3\u03a3', 0, 'ucs2'), 'Sigma Sigma'); - assert.equal( + assert.strictEqual( 6, twoByteString.indexOf('\u03a3\u0395', 0, 'ucs2'), 'Sigma Epsilon'); } const mixedByteStringUtf8 = Buffer.from('\u039a\u0391abc\u03a3\u03a3\u0395'); -assert.equal(5, mixedByteStringUtf8.indexOf('bc')); -assert.equal(5, mixedByteStringUtf8.indexOf('bc', 5)); -assert.equal(5, mixedByteStringUtf8.indexOf('bc', -8)); -assert.equal(7, mixedByteStringUtf8.indexOf('\u03a3')); -assert.equal(-1, mixedByteStringUtf8.indexOf('\u0396')); +assert.strictEqual(5, mixedByteStringUtf8.indexOf('bc')); +assert.strictEqual(5, mixedByteStringUtf8.indexOf('bc', 5)); +assert.strictEqual(5, mixedByteStringUtf8.indexOf('bc', -8)); +assert.strictEqual(7, mixedByteStringUtf8.indexOf('\u03a3')); +assert.strictEqual(-1, mixedByteStringUtf8.indexOf('\u0396')); // Test complex string indexOf algorithms. Only trigger for long strings. @@ -247,23 +252,25 @@ const longBufferString = Buffer.from(longString); let pattern = 'ABACABADABACABA'; for (let i = 0; i < longBufferString.length - pattern.length; i += 7) { const index = longBufferString.indexOf(pattern, i); - assert.equal((i + 15) & ~0xf, index, 'Long ABACABA...-string at index ' + i); + assert.strictEqual((i + 15) & ~0xf, index, + 'Long ABACABA...-string at index ' + i); } -assert.equal(510, longBufferString.indexOf('AJABACA'), 'Long AJABACA, First J'); -assert.equal( +assert.strictEqual(510, longBufferString.indexOf('AJABACA'), + 'Long AJABACA, First J'); +assert.strictEqual( 1534, longBufferString.indexOf('AJABACA', 511), 'Long AJABACA, Second J'); pattern = 'JABACABADABACABA'; -assert.equal( +assert.strictEqual( 511, longBufferString.indexOf(pattern), 'Long JABACABA..., First J'); -assert.equal( +assert.strictEqual( 1535, longBufferString.indexOf(pattern, 512), 'Long JABACABA..., Second J'); // Search for a non-ASCII string in a pure ASCII string. const asciiString = Buffer.from( 'arglebargleglopglyfarglebargleglopglyfarglebargleglopglyf'); -assert.equal(-1, asciiString.indexOf('\x2061')); -assert.equal(3, asciiString.indexOf('leb', 0)); +assert.strictEqual(-1, asciiString.indexOf('\x2061')); +assert.strictEqual(3, asciiString.indexOf('leb', 0)); // Search in string containing many non-ASCII chars. const allCodePoints = []; @@ -274,8 +281,8 @@ const allCharsBufferUcs2 = Buffer.from(allCharsString, 'ucs2'); // Search for string long enough to trigger complex search with ASCII pattern // and UC16 subject. -assert.equal(-1, allCharsBufferUtf8.indexOf('notfound')); -assert.equal(-1, allCharsBufferUcs2.indexOf('notfound')); +assert.strictEqual(-1, allCharsBufferUtf8.indexOf('notfound')); +assert.strictEqual(-1, allCharsBufferUcs2.indexOf('notfound')); // Needle is longer than haystack, but only because it's encoded as UTF-16 assert.strictEqual(Buffer.from('aaaa').indexOf('a'.repeat(4), 'ucs2'), -1); @@ -308,10 +315,10 @@ assert.strictEqual(Buffer.from('aaaaa').indexOf('b', 'ucs2'), -1); } const patternBufferUtf8 = allCharsBufferUtf8.slice(index, index + length); - assert.equal(index, allCharsBufferUtf8.indexOf(patternBufferUtf8)); + assert.strictEqual(index, allCharsBufferUtf8.indexOf(patternBufferUtf8)); const patternStringUtf8 = patternBufferUtf8.toString(); - assert.equal(index, allCharsBufferUtf8.indexOf(patternStringUtf8)); + assert.strictEqual(index, allCharsBufferUtf8.indexOf(patternStringUtf8)); } } } @@ -327,11 +334,11 @@ assert.strictEqual(Buffer.from('aaaaa').indexOf('b', 'ucs2'), -1); const patternBufferUcs2 = allCharsBufferUcs2.slice(index, index + length); - assert.equal( + assert.strictEqual( index, allCharsBufferUcs2.indexOf(patternBufferUcs2, 0, 'ucs2')); const patternStringUcs2 = patternBufferUcs2.toString('ucs2'); - assert.equal( + assert.strictEqual( index, allCharsBufferUcs2.indexOf(patternStringUcs2, 0, 'ucs2')); } } @@ -357,62 +364,62 @@ assert.throws(() => { // Test lastIndexOf basic functionality; Buffer b contains 'abcdef'. // lastIndexOf string: -assert.equal(b.lastIndexOf('a'), 0); -assert.equal(b.lastIndexOf('a', 1), 0); -assert.equal(b.lastIndexOf('b', 1), 1); -assert.equal(b.lastIndexOf('c', 1), -1); -assert.equal(b.lastIndexOf('a', -1), 0); -assert.equal(b.lastIndexOf('a', -4), 0); -assert.equal(b.lastIndexOf('a', -b.length), 0); -assert.equal(b.lastIndexOf('a', -b.length - 1), -1); -assert.equal(b.lastIndexOf('a', NaN), 0); -assert.equal(b.lastIndexOf('a', -Infinity), -1); -assert.equal(b.lastIndexOf('a', Infinity), 0); +assert.strictEqual(b.lastIndexOf('a'), 0); +assert.strictEqual(b.lastIndexOf('a', 1), 0); +assert.strictEqual(b.lastIndexOf('b', 1), 1); +assert.strictEqual(b.lastIndexOf('c', 1), -1); +assert.strictEqual(b.lastIndexOf('a', -1), 0); +assert.strictEqual(b.lastIndexOf('a', -4), 0); +assert.strictEqual(b.lastIndexOf('a', -b.length), 0); +assert.strictEqual(b.lastIndexOf('a', -b.length - 1), -1); +assert.strictEqual(b.lastIndexOf('a', NaN), 0); +assert.strictEqual(b.lastIndexOf('a', -Infinity), -1); +assert.strictEqual(b.lastIndexOf('a', Infinity), 0); // lastIndexOf Buffer: -assert.equal(b.lastIndexOf(buf_a), 0); -assert.equal(b.lastIndexOf(buf_a, 1), 0); -assert.equal(b.lastIndexOf(buf_a, -1), 0); -assert.equal(b.lastIndexOf(buf_a, -4), 0); -assert.equal(b.lastIndexOf(buf_a, -b.length), 0); -assert.equal(b.lastIndexOf(buf_a, -b.length - 1), -1); -assert.equal(b.lastIndexOf(buf_a, NaN), 0); -assert.equal(b.lastIndexOf(buf_a, -Infinity), -1); -assert.equal(b.lastIndexOf(buf_a, Infinity), 0); -assert.equal(b.lastIndexOf(buf_bc), 1); -assert.equal(b.lastIndexOf(buf_bc, 2), 1); -assert.equal(b.lastIndexOf(buf_bc, -1), 1); -assert.equal(b.lastIndexOf(buf_bc, -3), 1); -assert.equal(b.lastIndexOf(buf_bc, -5), 1); -assert.equal(b.lastIndexOf(buf_bc, -6), -1); -assert.equal(b.lastIndexOf(buf_bc, NaN), 1); -assert.equal(b.lastIndexOf(buf_bc, -Infinity), -1); -assert.equal(b.lastIndexOf(buf_bc, Infinity), 1); -assert.equal(b.lastIndexOf(buf_f), b.length - 1); -assert.equal(b.lastIndexOf(buf_z), -1); -assert.equal(b.lastIndexOf(buf_empty), -1); -assert.equal(b.lastIndexOf(buf_empty, 1), -1); -assert.equal(b.lastIndexOf(buf_empty, b.length + 1), -1); -assert.equal(b.lastIndexOf(buf_empty, Infinity), -1); +assert.strictEqual(b.lastIndexOf(buf_a), 0); +assert.strictEqual(b.lastIndexOf(buf_a, 1), 0); +assert.strictEqual(b.lastIndexOf(buf_a, -1), 0); +assert.strictEqual(b.lastIndexOf(buf_a, -4), 0); +assert.strictEqual(b.lastIndexOf(buf_a, -b.length), 0); +assert.strictEqual(b.lastIndexOf(buf_a, -b.length - 1), -1); +assert.strictEqual(b.lastIndexOf(buf_a, NaN), 0); +assert.strictEqual(b.lastIndexOf(buf_a, -Infinity), -1); +assert.strictEqual(b.lastIndexOf(buf_a, Infinity), 0); +assert.strictEqual(b.lastIndexOf(buf_bc), 1); +assert.strictEqual(b.lastIndexOf(buf_bc, 2), 1); +assert.strictEqual(b.lastIndexOf(buf_bc, -1), 1); +assert.strictEqual(b.lastIndexOf(buf_bc, -3), 1); +assert.strictEqual(b.lastIndexOf(buf_bc, -5), 1); +assert.strictEqual(b.lastIndexOf(buf_bc, -6), -1); +assert.strictEqual(b.lastIndexOf(buf_bc, NaN), 1); +assert.strictEqual(b.lastIndexOf(buf_bc, -Infinity), -1); +assert.strictEqual(b.lastIndexOf(buf_bc, Infinity), 1); +assert.strictEqual(b.lastIndexOf(buf_f), b.length - 1); +assert.strictEqual(b.lastIndexOf(buf_z), -1); +assert.strictEqual(b.lastIndexOf(buf_empty), -1); +assert.strictEqual(b.lastIndexOf(buf_empty, 1), -1); +assert.strictEqual(b.lastIndexOf(buf_empty, b.length + 1), -1); +assert.strictEqual(b.lastIndexOf(buf_empty, Infinity), -1); // lastIndexOf number: -assert.equal(b.lastIndexOf(0x61), 0); -assert.equal(b.lastIndexOf(0x61, 1), 0); -assert.equal(b.lastIndexOf(0x61, -1), 0); -assert.equal(b.lastIndexOf(0x61, -4), 0); -assert.equal(b.lastIndexOf(0x61, -b.length), 0); -assert.equal(b.lastIndexOf(0x61, -b.length - 1), -1); -assert.equal(b.lastIndexOf(0x61, NaN), 0); -assert.equal(b.lastIndexOf(0x61, -Infinity), -1); -assert.equal(b.lastIndexOf(0x61, Infinity), 0); -assert.equal(b.lastIndexOf(0x0), -1); +assert.strictEqual(b.lastIndexOf(0x61), 0); +assert.strictEqual(b.lastIndexOf(0x61, 1), 0); +assert.strictEqual(b.lastIndexOf(0x61, -1), 0); +assert.strictEqual(b.lastIndexOf(0x61, -4), 0); +assert.strictEqual(b.lastIndexOf(0x61, -b.length), 0); +assert.strictEqual(b.lastIndexOf(0x61, -b.length - 1), -1); +assert.strictEqual(b.lastIndexOf(0x61, NaN), 0); +assert.strictEqual(b.lastIndexOf(0x61, -Infinity), -1); +assert.strictEqual(b.lastIndexOf(0x61, Infinity), 0); +assert.strictEqual(b.lastIndexOf(0x0), -1); // Test weird offset arguments. // Behaviour should match String.lastIndexOf: -assert.equal(b.lastIndexOf('b', 0), -1); -assert.equal(b.lastIndexOf('b', undefined), 1); -assert.equal(b.lastIndexOf('b', null), -1); -assert.equal(b.lastIndexOf('b', {}), 1); -assert.equal(b.lastIndexOf('b', []), -1); -assert.equal(b.lastIndexOf('b', [2]), 1); +assert.strictEqual(b.lastIndexOf('b', 0), -1); +assert.strictEqual(b.lastIndexOf('b', undefined), 1); +assert.strictEqual(b.lastIndexOf('b', null), -1); +assert.strictEqual(b.lastIndexOf('b', {}), 1); +assert.strictEqual(b.lastIndexOf('b', []), -1); +assert.strictEqual(b.lastIndexOf('b', [2]), 1); // Test needles longer than the haystack. assert.strictEqual(b.lastIndexOf('aaaaaaaaaaaaaaa', 'ucs2'), -1); @@ -440,20 +447,21 @@ assert.strictEqual(buf_bc.lastIndexOf(Buffer.from('你好'), 7), -1); // Test lastIndexOf on a longer buffer: const bufferString = new Buffer('a man a plan a canal panama'); -assert.equal(15, bufferString.lastIndexOf('canal')); -assert.equal(21, bufferString.lastIndexOf('panama')); -assert.equal(0, bufferString.lastIndexOf('a man a plan a canal panama')); -assert.equal(-1, bufferString.lastIndexOf('a man a plan a canal mexico')); -assert.equal(-1, bufferString.lastIndexOf('a man a plan a canal mexico city')); -assert.equal(-1, bufferString.lastIndexOf(Buffer.from('a'.repeat(1000)))); -assert.equal(0, bufferString.lastIndexOf('a man a plan', 4)); -assert.equal(13, bufferString.lastIndexOf('a ')); -assert.equal(13, bufferString.lastIndexOf('a ', 13)); -assert.equal(6, bufferString.lastIndexOf('a ', 12)); -assert.equal(0, bufferString.lastIndexOf('a ', 5)); -assert.equal(13, bufferString.lastIndexOf('a ', -1)); -assert.equal(0, bufferString.lastIndexOf('a ', -27)); -assert.equal(-1, bufferString.lastIndexOf('a ', -28)); +assert.strictEqual(15, bufferString.lastIndexOf('canal')); +assert.strictEqual(21, bufferString.lastIndexOf('panama')); +assert.strictEqual(0, bufferString.lastIndexOf('a man a plan a canal panama')); +assert.strictEqual(-1, bufferString.lastIndexOf('a man a plan a canal mexico')); +assert.strictEqual(-1, bufferString + .lastIndexOf('a man a plan a canal mexico city')); +assert.strictEqual(-1, bufferString.lastIndexOf(Buffer.from('a'.repeat(1000)))); +assert.strictEqual(0, bufferString.lastIndexOf('a man a plan', 4)); +assert.strictEqual(13, bufferString.lastIndexOf('a ')); +assert.strictEqual(13, bufferString.lastIndexOf('a ', 13)); +assert.strictEqual(6, bufferString.lastIndexOf('a ', 12)); +assert.strictEqual(0, bufferString.lastIndexOf('a ', 5)); +assert.strictEqual(13, bufferString.lastIndexOf('a ', -1)); +assert.strictEqual(0, bufferString.lastIndexOf('a ', -27)); +assert.strictEqual(-1, bufferString.lastIndexOf('a ', -28)); // Test lastIndexOf for the case that the first character can be found, // but in a part of the buffer that does not make search to search @@ -477,9 +485,9 @@ assert.strictEqual(0, Buffer.from('abc').lastIndexOf('ab', 3)); // Now, we test the BOYER-MOORE-HORSPOOL strategy. // Test lastIndexOf on a long buffer w multiple matches: pattern = 'JABACABADABACABA'; -assert.equal(1535, longBufferString.lastIndexOf(pattern)); -assert.equal(1535, longBufferString.lastIndexOf(pattern, 1535)); -assert.equal(511, longBufferString.lastIndexOf(pattern, 1534)); +assert.strictEqual(1535, longBufferString.lastIndexOf(pattern)); +assert.strictEqual(1535, longBufferString.lastIndexOf(pattern, 1535)); +assert.strictEqual(511, longBufferString.lastIndexOf(pattern, 1534)); // Finally, give it a really long input to trigger fallback from BMH to // regular BOYER-MOORE (which has better worst-case complexity). @@ -501,19 +509,19 @@ for (let i = 0; i < 1000000; i++) { parts.push((countBits(i) % 2 === 0) ? 'yolo' : 'swag'); } const reallyLong = new Buffer(parts.join(' ')); -assert.equal('yolo swag swag yolo', reallyLong.slice(0, 19).toString()); +assert.strictEqual('yolo swag swag yolo', reallyLong.slice(0, 19).toString()); // Expensive reverse searches. Stress test lastIndexOf: pattern = reallyLong.slice(0, 100000); // First 1/50th of the pattern. -assert.equal(4751360, reallyLong.lastIndexOf(pattern)); -assert.equal(3932160, reallyLong.lastIndexOf(pattern, 4000000)); -assert.equal(2949120, reallyLong.lastIndexOf(pattern, 3000000)); +assert.strictEqual(4751360, reallyLong.lastIndexOf(pattern)); +assert.strictEqual(3932160, reallyLong.lastIndexOf(pattern, 4000000)); +assert.strictEqual(2949120, reallyLong.lastIndexOf(pattern, 3000000)); pattern = reallyLong.slice(100000, 200000); // Second 1/50th. -assert.equal(4728480, reallyLong.lastIndexOf(pattern)); +assert.strictEqual(4728480, reallyLong.lastIndexOf(pattern)); pattern = reallyLong.slice(0, 1000000); // First 1/5th. -assert.equal(3932160, reallyLong.lastIndexOf(pattern)); +assert.strictEqual(3932160, reallyLong.lastIndexOf(pattern)); pattern = reallyLong.slice(0, 2000000); // first 2/5ths. -assert.equal(0, reallyLong.lastIndexOf(pattern)); +assert.strictEqual(0, reallyLong.lastIndexOf(pattern)); // test truncation of Number arguments to uint8 { diff --git a/test/parallel/test-child-process-fork-net.js b/test/parallel/test-child-process-fork-net.js index c66b808ec0addf..157704a9ccf9c9 100644 --- a/test/parallel/test-child-process-fork-net.js +++ b/test/parallel/test-child-process-fork-net.js @@ -153,7 +153,7 @@ if (process.argv[2] === 'child') { }); connect.on('close', function() { console.log('CLIENT: closed'); - assert.equal(store, 'echo'); + assert.strictEqual(store, 'echo'); server.close(); }); }); diff --git a/test/parallel/test-child-process-fork-net2.js b/test/parallel/test-child-process-fork-net2.js index 6d20f419049c7b..ef8575385a42fd 100644 --- a/test/parallel/test-child-process-fork-net2.js +++ b/test/parallel/test-child-process-fork-net2.js @@ -135,7 +135,7 @@ if (process.argv[2] === 'child') { }; process.on('exit', function() { - assert.equal(disconnected, count); - assert.equal(connected, count); + assert.strictEqual(disconnected, count); + assert.strictEqual(connected, count); }); } diff --git a/test/parallel/test-child-process-fork-ref.js b/test/parallel/test-child-process-fork-ref.js index 1f8816c0cfaf1c..a7ff8c04cbab25 100644 --- a/test/parallel/test-child-process-fork-ref.js +++ b/test/parallel/test-child-process-fork-ref.js @@ -33,6 +33,6 @@ if (process.argv[2] === 'child') { child.once('exit', function() { assert.deepStrictEqual(ipc, ['1', '2']); - assert.equal(stdout, '3'); + assert.strictEqual(stdout, '3'); }); } diff --git a/test/parallel/test-child-process-ipc.js b/test/parallel/test-child-process-ipc.js index cbaa270f5e8440..da952e6c9bf1ae 100644 --- a/test/parallel/test-child-process-ipc.js +++ b/test/parallel/test-child-process-ipc.js @@ -30,7 +30,7 @@ child.stdout.on('data', function(data) { child.stdin.write('echo me\r\n'); } else { console.error('testing for echo me'); - assert.equal('echo me\r\n', data); + assert.strictEqual('echo me\r\n', data); gotEcho = true; child.stdin.end(); } diff --git a/test/parallel/test-child-process-set-blocking.js b/test/parallel/test-child-process-set-blocking.js index 54037aea69feb2..d6a044619b6479 100644 --- a/test/parallel/test-child-process-set-blocking.js +++ b/test/parallel/test-child-process-set-blocking.js @@ -10,5 +10,5 @@ const cp = ch.spawn('python', ['-c', 'print ' + SIZE + ' * "C"'], { }); cp.on('exit', common.mustCall(function(code) { - assert.equal(0, code); + assert.strictEqual(0, code); })); diff --git a/test/parallel/test-child-process-spawnsync-env.js b/test/parallel/test-child-process-spawnsync-env.js index 6f5ea3dc83d107..b5a1c723660faa 100644 --- a/test/parallel/test-child-process-spawnsync-env.js +++ b/test/parallel/test-child-process-spawnsync-env.js @@ -11,5 +11,5 @@ if (process.argv[2] === 'child') { env: Object.assign(process.env, { foo: expected }) }); - assert.equal(child.stdout.toString().trim(), expected); + assert.strictEqual(child.stdout.toString().trim(), expected); } diff --git a/test/parallel/test-crypto-dh.js b/test/parallel/test-crypto-dh.js index 2a06fc6e7b86d6..b76e188bc6f0d6 100644 --- a/test/parallel/test-crypto-dh.js +++ b/test/parallel/test-crypto-dh.js @@ -19,9 +19,9 @@ let key2 = dh2.generateKeys('hex'); let secret1 = dh1.computeSecret(key2, 'hex', 'base64'); let secret2 = dh2.computeSecret(key1, 'latin1', 'buffer'); -assert.equal(secret1, secret2.toString('base64')); -assert.equal(dh1.verifyError, 0); -assert.equal(dh2.verifyError, 0); +assert.strictEqual(secret1, secret2.toString('base64')); +assert.strictEqual(dh1.verifyError, 0); +assert.strictEqual(dh2.verifyError, 0); assert.throws(function() { crypto.createDiffieHellman([0x1, 0x2]); @@ -50,11 +50,11 @@ assert.deepStrictEqual(dh1.getPrime(), dh3.getPrime()); assert.deepStrictEqual(dh1.getGenerator(), dh3.getGenerator()); assert.deepStrictEqual(dh1.getPublicKey(), dh3.getPublicKey()); assert.deepStrictEqual(dh1.getPrivateKey(), dh3.getPrivateKey()); -assert.equal(dh3.verifyError, 0); +assert.strictEqual(dh3.verifyError, 0); const secret3 = dh3.computeSecret(key2, 'hex', 'base64'); -assert.equal(secret1, secret3); +assert.strictEqual(secret1, secret3); // Run this one twice to make sure that the dh3 clears its error properly { @@ -78,9 +78,9 @@ alice.generateKeys(); bob.generateKeys(); const aSecret = alice.computeSecret(bob.getPublicKey()).toString('hex'); const bSecret = bob.computeSecret(alice.getPublicKey()).toString('hex'); -assert.equal(aSecret, bSecret); -assert.equal(alice.verifyError, DH_NOT_SUITABLE_GENERATOR); -assert.equal(bob.verifyError, DH_NOT_SUITABLE_GENERATOR); +assert.strictEqual(aSecret, bSecret); +assert.strictEqual(alice.verifyError, DH_NOT_SUITABLE_GENERATOR); +assert.strictEqual(bob.verifyError, DH_NOT_SUITABLE_GENERATOR); /* Ensure specific generator (buffer) works as expected. * The values below (modp2/modp2buf) are for a 1024 bits long prime from @@ -107,9 +107,9 @@ exmodp2.generateKeys(); let modp2Secret = modp2.computeSecret(exmodp2.getPublicKey()).toString('hex'); const exmodp2Secret = exmodp2.computeSecret(modp2.getPublicKey()) .toString('hex'); -assert.equal(modp2Secret, exmodp2Secret); -assert.equal(modp2.verifyError, DH_NOT_SUITABLE_GENERATOR); -assert.equal(exmodp2.verifyError, DH_NOT_SUITABLE_GENERATOR); +assert.strictEqual(modp2Secret, exmodp2Secret); +assert.strictEqual(modp2.verifyError, DH_NOT_SUITABLE_GENERATOR); +assert.strictEqual(exmodp2.verifyError, DH_NOT_SUITABLE_GENERATOR); // Ensure specific generator (string with encoding) works as expected. @@ -118,8 +118,8 @@ exmodp2_2.generateKeys(); modp2Secret = modp2.computeSecret(exmodp2_2.getPublicKey()).toString('hex'); const exmodp2_2Secret = exmodp2_2.computeSecret(modp2.getPublicKey()) .toString('hex'); -assert.equal(modp2Secret, exmodp2_2Secret); -assert.equal(exmodp2_2.verifyError, DH_NOT_SUITABLE_GENERATOR); +assert.strictEqual(modp2Secret, exmodp2_2Secret); +assert.strictEqual(exmodp2_2.verifyError, DH_NOT_SUITABLE_GENERATOR); // Ensure specific generator (string without encoding) works as expected. @@ -128,8 +128,8 @@ exmodp2_3.generateKeys(); modp2Secret = modp2.computeSecret(exmodp2_3.getPublicKey()).toString('hex'); const exmodp2_3Secret = exmodp2_3.computeSecret(modp2.getPublicKey()) .toString('hex'); -assert.equal(modp2Secret, exmodp2_3Secret); -assert.equal(exmodp2_3.verifyError, DH_NOT_SUITABLE_GENERATOR); +assert.strictEqual(modp2Secret, exmodp2_3Secret); +assert.strictEqual(exmodp2_3.verifyError, DH_NOT_SUITABLE_GENERATOR); // Ensure specific generator (numeric) works as expected. @@ -138,8 +138,8 @@ exmodp2_4.generateKeys(); modp2Secret = modp2.computeSecret(exmodp2_4.getPublicKey()).toString('hex'); const exmodp2_4Secret = exmodp2_4.computeSecret(modp2.getPublicKey()) .toString('hex'); -assert.equal(modp2Secret, exmodp2_4Secret); -assert.equal(exmodp2_4.verifyError, DH_NOT_SUITABLE_GENERATOR); +assert.strictEqual(modp2Secret, exmodp2_4Secret); +assert.strictEqual(exmodp2_4.verifyError, DH_NOT_SUITABLE_GENERATOR); const p = 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74' + @@ -147,7 +147,7 @@ const p = 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74' + '4FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' + 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF'; const bad_dh = crypto.createDiffieHellman(p, 'hex'); -assert.equal(bad_dh.verifyError, DH_NOT_SUITABLE_GENERATOR); +assert.strictEqual(bad_dh.verifyError, DH_NOT_SUITABLE_GENERATOR); // Test ECDH @@ -158,7 +158,7 @@ key2 = ecdh2.generateKeys('hex'); secret1 = ecdh1.computeSecret(key2, 'hex', 'base64'); secret2 = ecdh2.computeSecret(key1, 'latin1', 'buffer'); -assert.equal(secret1, secret2.toString('base64')); +assert.strictEqual(secret1, secret2.toString('base64')); // Oakley curves do not clean up ERR stack, it was causing unexpected failure // when accessing other OpenSSL APIs afterwards. @@ -166,7 +166,7 @@ crypto.createECDH('Oakley-EC2N-3'); crypto.createHash('sha256'); // Point formats -assert.equal(ecdh1.getPublicKey('buffer', 'uncompressed')[0], 4); +assert.strictEqual(ecdh1.getPublicKey('buffer', 'uncompressed')[0], 4); let firstByte = ecdh1.getPublicKey('buffer', 'compressed')[0]; assert(firstByte === 2 || firstByte === 3); firstByte = ecdh1.getPublicKey('buffer', 'hybrid')[0]; @@ -210,9 +210,9 @@ const cafebabePubPtUnComp = '04672a31bfc59d3f04548ec9b7daeeba2f61814e8ccc40448045007f5479f693a3' + '2e02c7f93d13dc2732b760ca377a5897b9dd41a1c1b29dc0442fdce6d0a04d1d'; ecdh5.setPrivateKey(cafebabeKey, 'hex'); -assert.equal(ecdh5.getPrivateKey('hex'), cafebabeKey); +assert.strictEqual(ecdh5.getPrivateKey('hex'), cafebabeKey); // Show that the public point (key) is generated while setting the private key. -assert.equal(ecdh5.getPublicKey('hex'), cafebabePubPtUnComp); +assert.strictEqual(ecdh5.getPublicKey('hex'), cafebabePubPtUnComp); // Compressed and uncompressed public points/keys for other party's private key // 0xDEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEF @@ -225,24 +225,26 @@ const peerPubPtUnComp = const sharedSecret = '1da220b5329bbe8bfd19ceef5a5898593f411a6f12ea40f2a8eead9a5cf59970'; -assert.equal(ecdh5.computeSecret(peerPubPtComp, 'hex', 'hex'), sharedSecret); -assert.equal(ecdh5.computeSecret(peerPubPtUnComp, 'hex', 'hex'), sharedSecret); +assert.strictEqual(ecdh5.computeSecret(peerPubPtComp, 'hex', 'hex'), + sharedSecret); +assert.strictEqual(ecdh5.computeSecret(peerPubPtUnComp, 'hex', 'hex'), + sharedSecret); // Verify that we still have the same key pair as before the computation. -assert.equal(ecdh5.getPrivateKey('hex'), cafebabeKey); -assert.equal(ecdh5.getPublicKey('hex'), cafebabePubPtUnComp); +assert.strictEqual(ecdh5.getPrivateKey('hex'), cafebabeKey); +assert.strictEqual(ecdh5.getPublicKey('hex'), cafebabePubPtUnComp); // Verify setting and getting compressed and non-compressed serializations. ecdh5.setPublicKey(cafebabePubPtComp, 'hex'); -assert.equal(ecdh5.getPublicKey('hex'), cafebabePubPtUnComp); -assert.equal(ecdh5.getPublicKey('hex', 'compressed'), cafebabePubPtComp); +assert.strictEqual(ecdh5.getPublicKey('hex'), cafebabePubPtUnComp); +assert.strictEqual(ecdh5.getPublicKey('hex', 'compressed'), cafebabePubPtComp); ecdh5.setPublicKey(cafebabePubPtUnComp, 'hex'); -assert.equal(ecdh5.getPublicKey('hex'), cafebabePubPtUnComp); -assert.equal(ecdh5.getPublicKey('hex', 'compressed'), cafebabePubPtComp); +assert.strictEqual(ecdh5.getPublicKey('hex'), cafebabePubPtUnComp); +assert.strictEqual(ecdh5.getPublicKey('hex', 'compressed'), cafebabePubPtComp); // Show why allowing the public key to be set on this type does not make sense. ecdh5.setPublicKey(peerPubPtComp, 'hex'); -assert.equal(ecdh5.getPublicKey('hex'), peerPubPtUnComp); +assert.strictEqual(ecdh5.getPublicKey('hex'), peerPubPtUnComp); assert.throws(function() { // Error because the public key does not match the private key anymore. ecdh5.computeSecret(peerPubPtComp, 'hex', 'hex'); @@ -261,5 +263,5 @@ ecdh5.setPrivateKey(cafebabeKey, 'hex'); ecdh5.setPrivateKey(element, 'hex'); }, /Private key is not valid for specified curve/); // Verify object state did not change. - assert.equal(ecdh5.getPrivateKey('hex'), cafebabeKey); + assert.strictEqual(ecdh5.getPrivateKey('hex'), cafebabeKey); }); diff --git a/test/parallel/test-crypto-domains.js b/test/parallel/test-crypto-domains.js index 2749382fa5c780..d0dcf7f2107f77 100644 --- a/test/parallel/test-crypto-domains.js +++ b/test/parallel/test-crypto-domains.js @@ -12,7 +12,7 @@ if (!common.hasCrypto) { const crypto = require('crypto'); d.on('error', common.mustCall(function(e) { - assert.equal(e.message, expect.shift()); + assert.strictEqual(e.message, expect.shift()); }, 3)); d.run(function() { diff --git a/test/parallel/test-dh-padding.js b/test/parallel/test-dh-padding.js index 1d9d47ec0e10a3..4744d204739a5d 100644 --- a/test/parallel/test-dh-padding.js +++ b/test/parallel/test-dh-padding.js @@ -85,7 +85,7 @@ const p = crypto.createDiffieHellman( p.setPublicKey(apub, 'hex'); p.setPrivateKey(apriv, 'hex'); -assert.equal( +assert.strictEqual( p.computeSecret(bpub, 'hex', 'hex').toString('hex'), secret ); diff --git a/test/parallel/test-domain-nested.js b/test/parallel/test-domain-nested.js index d0618b5bad724b..6d673adc7e6387 100644 --- a/test/parallel/test-domain-nested.js +++ b/test/parallel/test-domain-nested.js @@ -6,7 +6,7 @@ const assert = require('assert'); const domain = require('domain'); process.on('exit', function(c) { - assert.equal(domain._stack.length, 0); + assert.strictEqual(domain._stack.length, 0); }); domain.create().run(function() { diff --git a/test/parallel/test-event-emitter-prepend.js b/test/parallel/test-event-emitter-prepend.js index 5a3b66b0cb3250..b511af9ae3691d 100644 --- a/test/parallel/test-event-emitter-prepend.js +++ b/test/parallel/test-event-emitter-prepend.js @@ -7,13 +7,14 @@ const assert = require('assert'); const myEE = new EventEmitter(); let m = 0; // This one comes last. -myEE.on('foo', common.mustCall(() => assert.equal(m, 2))); +myEE.on('foo', common.mustCall(() => assert.strictEqual(m, 2))); // This one comes second. -myEE.prependListener('foo', common.mustCall(() => assert.equal(m++, 1))); +myEE.prependListener('foo', common.mustCall(() => assert.strictEqual(m++, 1))); // This one comes first. -myEE.prependOnceListener('foo', common.mustCall(() => assert.equal(m++, 0))); +myEE.prependOnceListener('foo', + common.mustCall(() => assert.strictEqual(m++, 0))); myEE.emit('foo'); diff --git a/test/parallel/test-event-emitter-subclass.js b/test/parallel/test-event-emitter-subclass.js index d35802b413136b..eb2018e78e4b85 100644 --- a/test/parallel/test-event-emitter-subclass.js +++ b/test/parallel/test-event-emitter-subclass.js @@ -43,4 +43,4 @@ const ee2 = new MyEE2(); ee1.on('x', function() {}); -assert.equal(ee2.listenerCount('x'), 0); +assert.strictEqual(ee2.listenerCount('x'), 0); diff --git a/test/parallel/test-fs-error-messages.js b/test/parallel/test-fs-error-messages.js index 1a05ef80a44a5c..f2ea85531bf463 100644 --- a/test/parallel/test-fs-error-messages.js +++ b/test/parallel/test-fs-error-messages.js @@ -12,7 +12,7 @@ const existingDir2 = path.join(common.fixturesDir, 'keys'); // ASYNC_CALL fs.stat(fn, function(err) { - assert.equal(fn, err.path); + assert.strictEqual(fn, err.path); assert.ok(0 <= err.message.indexOf(fn)); }); @@ -204,7 +204,7 @@ try { } process.on('exit', function() { - assert.equal(expected, errors.length, - 'Test fs sync exceptions raised, got ' + errors.length + + assert.strictEqual(expected, errors.length, + 'Test fs sync exceptions raised, got ' + errors.length + ' expected ' + expected); }); diff --git a/test/parallel/test-fs-mkdir-rmdir.js b/test/parallel/test-fs-mkdir-rmdir.js index 0bddf673ecb107..bac18fc027931d 100644 --- a/test/parallel/test-fs-mkdir-rmdir.js +++ b/test/parallel/test-fs-mkdir-rmdir.js @@ -29,8 +29,8 @@ fs.mkdir(d, 0o666, function(err) { fs.mkdir(d, 0o666, function(err) { assert.ok(err.message.match(/^EEXIST/), 'got EEXIST message'); - assert.equal(err.code, 'EEXIST', 'got EEXIST code'); - assert.equal(err.path, d, 'got proper path for EEXIST'); + assert.strictEqual(err.code, 'EEXIST', 'got EEXIST code'); + assert.strictEqual(err.path, d, 'got proper path for EEXIST'); fs.rmdir(d, assert.ifError); }); diff --git a/test/parallel/test-fs-mkdir.js b/test/parallel/test-fs-mkdir.js index 620231102273e3..73fc899ce57597 100644 --- a/test/parallel/test-fs-mkdir.js +++ b/test/parallel/test-fs-mkdir.js @@ -33,8 +33,8 @@ common.refreshTmpDir(); unlink(pathname); fs.mkdir(pathname, 0o777, common.mustCall(function(err) { - assert.equal(err, null); - assert.equal(common.fileExists(pathname), true); + assert.strictEqual(err, null); + assert.strictEqual(common.fileExists(pathname), true); })); process.on('exit', function() { diff --git a/test/parallel/test-fs-mkdtemp.js b/test/parallel/test-fs-mkdtemp.js index c387090989c882..d4773aa37b7bf5 100644 --- a/test/parallel/test-fs-mkdtemp.js +++ b/test/parallel/test-fs-mkdtemp.js @@ -14,8 +14,8 @@ assert.strictEqual(path.basename(tmpFolder).length, 'foo.XXXXXX'.length); assert(common.fileExists(tmpFolder)); const utf8 = fs.mkdtempSync(path.join(common.tmpDir, '\u0222abc.')); -assert.equal(Buffer.byteLength(path.basename(utf8)), - Buffer.byteLength('\u0222abc.XXXXXX')); +assert.strictEqual(Buffer.byteLength(path.basename(utf8)), + Buffer.byteLength('\u0222abc.XXXXXX')); assert(common.fileExists(utf8)); function handler(err, folder) { diff --git a/test/parallel/test-fs-open-flags.js b/test/parallel/test-fs-open-flags.js index c8d6dd5eee4783..878726580b6f6a 100644 --- a/test/parallel/test-fs-open-flags.js +++ b/test/parallel/test-fs-open-flags.js @@ -15,21 +15,21 @@ const O_WRONLY = fs.constants.O_WRONLY || 0; const { stringToFlags } = require('internal/fs'); -assert.equal(stringToFlags('r'), O_RDONLY); -assert.equal(stringToFlags('r+'), O_RDWR); -assert.equal(stringToFlags('w'), O_TRUNC | O_CREAT | O_WRONLY); -assert.equal(stringToFlags('w+'), O_TRUNC | O_CREAT | O_RDWR); -assert.equal(stringToFlags('a'), O_APPEND | O_CREAT | O_WRONLY); -assert.equal(stringToFlags('a+'), O_APPEND | O_CREAT | O_RDWR); - -assert.equal(stringToFlags('wx'), O_TRUNC | O_CREAT | O_WRONLY | O_EXCL); -assert.equal(stringToFlags('xw'), O_TRUNC | O_CREAT | O_WRONLY | O_EXCL); -assert.equal(stringToFlags('wx+'), O_TRUNC | O_CREAT | O_RDWR | O_EXCL); -assert.equal(stringToFlags('xw+'), O_TRUNC | O_CREAT | O_RDWR | O_EXCL); -assert.equal(stringToFlags('ax'), O_APPEND | O_CREAT | O_WRONLY | O_EXCL); -assert.equal(stringToFlags('xa'), O_APPEND | O_CREAT | O_WRONLY | O_EXCL); -assert.equal(stringToFlags('ax+'), O_APPEND | O_CREAT | O_RDWR | O_EXCL); -assert.equal(stringToFlags('xa+'), O_APPEND | O_CREAT | O_RDWR | O_EXCL); +assert.strictEqual(stringToFlags('r'), O_RDONLY); +assert.strictEqual(stringToFlags('r+'), O_RDWR); +assert.strictEqual(stringToFlags('w'), O_TRUNC | O_CREAT | O_WRONLY); +assert.strictEqual(stringToFlags('w+'), O_TRUNC | O_CREAT | O_RDWR); +assert.strictEqual(stringToFlags('a'), O_APPEND | O_CREAT | O_WRONLY); +assert.strictEqual(stringToFlags('a+'), O_APPEND | O_CREAT | O_RDWR); + +assert.strictEqual(stringToFlags('wx'), O_TRUNC | O_CREAT | O_WRONLY | O_EXCL); +assert.strictEqual(stringToFlags('xw'), O_TRUNC | O_CREAT | O_WRONLY | O_EXCL); +assert.strictEqual(stringToFlags('wx+'), O_TRUNC | O_CREAT | O_RDWR | O_EXCL); +assert.strictEqual(stringToFlags('xw+'), O_TRUNC | O_CREAT | O_RDWR | O_EXCL); +assert.strictEqual(stringToFlags('ax'), O_APPEND | O_CREAT | O_WRONLY | O_EXCL); +assert.strictEqual(stringToFlags('xa'), O_APPEND | O_CREAT | O_WRONLY | O_EXCL); +assert.strictEqual(stringToFlags('ax+'), O_APPEND | O_CREAT | O_RDWR | O_EXCL); +assert.strictEqual(stringToFlags('xa+'), O_APPEND | O_CREAT | O_RDWR | O_EXCL); ('+ +a +r +w rw wa war raw r++ a++ w++ x +x x+ rx rx+ wxx wax xwx xxx') .split(' ') diff --git a/test/parallel/test-fs-read-buffer-zero-length.js b/test/parallel/test-fs-read-buffer-zero-length.js index 35b1f7b566f685..4c7dd73f60ebb1 100644 --- a/test/parallel/test-fs-read-buffer-zero-length.js +++ b/test/parallel/test-fs-read-buffer-zero-length.js @@ -10,10 +10,10 @@ const bufferAsync = Buffer.alloc(0); const bufferSync = Buffer.alloc(0); fs.read(fd, bufferAsync, 0, 0, 0, common.mustCall(function(err, bytesRead) { - assert.equal(bytesRead, 0); + assert.strictEqual(bytesRead, 0); assert.deepStrictEqual(bufferAsync, Buffer.alloc(0)); })); const r = fs.readSync(fd, bufferSync, 0, 0, 0); assert.deepStrictEqual(bufferSync, Buffer.alloc(0)); -assert.equal(r, 0); +assert.strictEqual(r, 0); diff --git a/test/parallel/test-fs-read-stream.js b/test/parallel/test-fs-read-stream.js index d4fad6e6f79c07..d17703fabe6a27 100644 --- a/test/parallel/test-fs-read-stream.js +++ b/test/parallel/test-fs-read-stream.js @@ -61,7 +61,7 @@ file.on('close', function() { assert.strictEqual(file.bytesRead, fileSize); callbacks.close++; - //assert.equal(fs.readFileSync(fn), fileContent); + //assert.strictEqual(fs.readFileSync(fn), fileContent); }); const file3 = fs.createReadStream(fn, {encoding: 'utf8'}); diff --git a/test/parallel/test-fs-read-zero-length.js b/test/parallel/test-fs-read-zero-length.js index 9c4cde52362ccc..42e260360e79e2 100644 --- a/test/parallel/test-fs-read-zero-length.js +++ b/test/parallel/test-fs-read-zero-length.js @@ -9,10 +9,10 @@ const expected = ''; fs.read(fd, 0, 0, 'utf-8', common.mustCall(function(err, str, bytesRead) { assert.ok(!err); - assert.equal(str, expected); - assert.equal(bytesRead, 0); + assert.strictEqual(str, expected); + assert.strictEqual(bytesRead, 0); })); const r = fs.readSync(fd, 0, 0, 'utf-8'); -assert.equal(r[0], expected); -assert.equal(r[1], 0); +assert.strictEqual(r[0], expected); +assert.strictEqual(r[1], 0); diff --git a/test/parallel/test-fs-readdir-ucs2.js b/test/parallel/test-fs-readdir-ucs2.js index 53b16de4b9bea0..4d5f53abd8ead9 100644 --- a/test/parallel/test-fs-readdir-ucs2.js +++ b/test/parallel/test-fs-readdir-ucs2.js @@ -20,7 +20,7 @@ fs.closeSync(fs.openSync(fullpath, 'w+')); fs.readdir(common.tmpDir, 'ucs2', (err, list) => { assert.ifError(err); - assert.equal(1, list.length); + assert.strictEqual(1, list.length); const fn = list[0]; assert.deepStrictEqual(filebuff, Buffer.from(fn, 'ucs2')); assert.strictEqual(fn, filename); diff --git a/test/parallel/test-fs-readdir.js b/test/parallel/test-fs-readdir.js index f38ae49c90a18f..57612f3e26b183 100644 --- a/test/parallel/test-fs-readdir.js +++ b/test/parallel/test-fs-readdir.js @@ -31,5 +31,5 @@ assert.throws(function() { }, /Error: ENOTDIR: not a directory/); fs.readdir(__filename, common.mustCall(function(e) { - assert.equal(e.code, 'ENOTDIR'); + assert.strictEqual(e.code, 'ENOTDIR'); })); diff --git a/test/parallel/test-fs-realpath.js b/test/parallel/test-fs-realpath.js index a444bf49846b1e..aeb48e1edb9d75 100644 --- a/test/parallel/test-fs-realpath.js +++ b/test/parallel/test-fs-realpath.js @@ -508,6 +508,6 @@ function runTest() { process.on('exit', function() { - assert.equal(numtests, testsRun); - assert.equal(async_completed, async_expected); + assert.strictEqual(numtests, testsRun); + assert.strictEqual(async_completed, async_expected); }); diff --git a/test/parallel/test-fs-stat.js b/test/parallel/test-fs-stat.js index 32ba47c2fe0c1e..00fcc1df21c586 100644 --- a/test/parallel/test-fs-stat.js +++ b/test/parallel/test-fs-stat.js @@ -57,25 +57,25 @@ fs.stat(__filename, common.mustCall(function(err, s) { console.dir(s); console.log('isDirectory: ' + JSON.stringify(s.isDirectory())); - assert.equal(false, s.isDirectory()); + assert.strictEqual(false, s.isDirectory()); console.log('isFile: ' + JSON.stringify(s.isFile())); - assert.equal(true, s.isFile()); + assert.strictEqual(true, s.isFile()); console.log('isSocket: ' + JSON.stringify(s.isSocket())); - assert.equal(false, s.isSocket()); + assert.strictEqual(false, s.isSocket()); console.log('isBlockDevice: ' + JSON.stringify(s.isBlockDevice())); - assert.equal(false, s.isBlockDevice()); + assert.strictEqual(false, s.isBlockDevice()); console.log('isCharacterDevice: ' + JSON.stringify(s.isCharacterDevice())); - assert.equal(false, s.isCharacterDevice()); + assert.strictEqual(false, s.isCharacterDevice()); console.log('isFIFO: ' + JSON.stringify(s.isFIFO())); - assert.equal(false, s.isFIFO()); + assert.strictEqual(false, s.isFIFO()); console.log('isSymbolicLink: ' + JSON.stringify(s.isSymbolicLink())); - assert.equal(false, s.isSymbolicLink()); + assert.strictEqual(false, s.isSymbolicLink()); assert.ok(s.mtime instanceof Date); })); diff --git a/test/parallel/test-fs-sync-fd-leak.js b/test/parallel/test-fs-sync-fd-leak.js index 353519593e2c4e..75125d6c679784 100644 --- a/test/parallel/test-fs-sync-fd-leak.js +++ b/test/parallel/test-fs-sync-fd-leak.js @@ -8,7 +8,7 @@ fs.openSync = function() { return 42; }; fs.closeSync = function(fd) { - assert.equal(fd, 42); + assert.strictEqual(fd, 42); close_called++; }; fs.readSync = function() { @@ -40,10 +40,10 @@ function ensureThrows(cb) { try { cb(); } catch (e) { - assert.equal(e.message, 'BAM'); + assert.strictEqual(e.message, 'BAM'); got_exception = true; } - assert.equal(close_called, 1); - assert.equal(got_exception, true); + assert.strictEqual(close_called, 1); + assert.strictEqual(got_exception, true); } diff --git a/test/parallel/test-fs-watch-enoent.js b/test/parallel/test-fs-watch-enoent.js index f9aa58c3d522cc..38f10e1430a360 100644 --- a/test/parallel/test-fs-watch-enoent.js +++ b/test/parallel/test-fs-watch-enoent.js @@ -8,7 +8,7 @@ assert.throws(function() { }, function(err) { assert(err); assert(/non-existent-file/.test(err)); - assert.equal(err.filename, 'non-existent-file'); + assert.strictEqual(err.filename, 'non-existent-file'); return true; }); @@ -16,6 +16,6 @@ const watcher = fs.watch(__filename); watcher.on('error', common.mustCall(function(err) { assert(err); assert(/non-existent-file/.test(err)); - assert.equal(err.filename, 'non-existent-file'); + assert.strictEqual(err.filename, 'non-existent-file'); })); watcher._handle.onchange(-1, 'ENOENT', 'non-existent-file'); diff --git a/test/parallel/test-fs-watch-stop-async.js b/test/parallel/test-fs-watch-stop-async.js index 5cbfd58418024a..56350430bc7912 100644 --- a/test/parallel/test-fs-watch-stop-async.js +++ b/test/parallel/test-fs-watch-stop-async.js @@ -12,8 +12,8 @@ const listener = common.mustCall(() => { triggered = false; watch.once('stop', listener); // Should trigger. watch.stop(); -assert.equal(triggered, false); +assert.strictEqual(triggered, false); setImmediate(() => { - assert.equal(triggered, true); + assert.strictEqual(triggered, true); watch.removeListener('stop', listener); }); diff --git a/test/parallel/test-fs-write-stream-change-open.js b/test/parallel/test-fs-write-stream-change-open.js index f68cc0a6d386e2..146b507a48ac61 100644 --- a/test/parallel/test-fs-write-stream-change-open.js +++ b/test/parallel/test-fs-write-stream-change-open.js @@ -29,5 +29,5 @@ stream.write('foo'); stream.end(); process.on('exit', function() { - assert.equal(fs.open, _fs_open); + assert.strictEqual(fs.open, _fs_open); }); diff --git a/test/parallel/test-fs-write-stream-err.js b/test/parallel/test-fs-write-stream-err.js index d50fd07103222e..4a2b3cd130b4c4 100644 --- a/test/parallel/test-fs-write-stream-err.js +++ b/test/parallel/test-fs-write-stream-err.js @@ -33,14 +33,14 @@ fs.write = function() { fs.close = common.mustCall(function(fd_, cb) { console.error('fs.close', fd_, stream.fd); - assert.equal(fd_, stream.fd); + assert.strictEqual(fd_, stream.fd); process.nextTick(cb); }); stream.on('error', common.mustCall(function(err_) { console.error('error handler'); - assert.equal(stream.fd, null); - assert.equal(err_, err); + assert.strictEqual(stream.fd, null); + assert.strictEqual(err_, err); })); @@ -48,6 +48,6 @@ stream.write(Buffer.allocUnsafe(256), function() { console.error('first cb'); stream.write(Buffer.allocUnsafe(256), common.mustCall(function(err_) { console.error('second cb'); - assert.equal(err_, err); + assert.strictEqual(err_, err); })); }); diff --git a/test/parallel/test-fs-write-string-coerce.js b/test/parallel/test-fs-write-string-coerce.js index 2694312b863571..8251a45766f918 100644 --- a/test/parallel/test-fs-write-string-coerce.js +++ b/test/parallel/test-fs-write-string-coerce.js @@ -17,7 +17,7 @@ fs.open(fn, 'w', 0o644, common.mustCall(function(err, fd) { fs.write(fd, data, 0, 'utf8', common.mustCall(function(err, written) { console.log('write done'); assert.ifError(err); - assert.equal(Buffer.byteLength(expected), written); + assert.strictEqual(Buffer.byteLength(expected), written); fs.closeSync(fd); const found = fs.readFileSync(fn, 'utf8'); console.log('expected: "%s"', expected); diff --git a/test/parallel/test-http-abort-queued.js b/test/parallel/test-http-abort-queued.js index 8e8339aa82d3dd..60dde248df542c 100644 --- a/test/parallel/test-http-abort-queued.js +++ b/test/parallel/test-http-abort-queued.js @@ -8,7 +8,7 @@ let complete; const server = http.createServer(function(req, res) { // We should not see the queued /thatotherone request within the server // as it should be aborted before it is sent. - assert.equal(req.url, '/'); + assert.strictEqual(req.url, '/'); res.writeHead(200); res.write('foo'); @@ -23,7 +23,7 @@ server.listen(0, function() { console.log('listen', server.address().port); const agent = new http.Agent({maxSockets: 1}); - assert.equal(Object.keys(agent.sockets).length, 0); + assert.strictEqual(Object.keys(agent.sockets).length, 0); const options = { hostname: 'localhost', @@ -35,8 +35,8 @@ server.listen(0, function() { const req1 = http.request(options); req1.on('response', function(res1) { - assert.equal(Object.keys(agent.sockets).length, 1); - assert.equal(Object.keys(agent.requests).length, 0); + assert.strictEqual(Object.keys(agent.sockets).length, 1); + assert.strictEqual(Object.keys(agent.requests).length, 0); const req2 = http.request({ method: 'GET', @@ -45,19 +45,19 @@ server.listen(0, function() { path: '/thatotherone', agent: agent }); - assert.equal(Object.keys(agent.sockets).length, 1); - assert.equal(Object.keys(agent.requests).length, 1); + assert.strictEqual(Object.keys(agent.sockets).length, 1); + assert.strictEqual(Object.keys(agent.requests).length, 1); req2.on('error', function(err) { // This is expected in response to our explicit abort call - assert.equal(err.code, 'ECONNRESET'); + assert.strictEqual(err.code, 'ECONNRESET'); }); req2.end(); req2.abort(); - assert.equal(Object.keys(agent.sockets).length, 1); - assert.equal(Object.keys(agent.requests).length, 1); + assert.strictEqual(Object.keys(agent.sockets).length, 1); + assert.strictEqual(Object.keys(agent.requests).length, 1); console.log('Got res: ' + res1.statusCode); console.dir(res1.headers); @@ -72,8 +72,8 @@ server.listen(0, function() { console.log('Response ended.'); setTimeout(function() { - assert.equal(Object.keys(agent.sockets).length, 0); - assert.equal(Object.keys(agent.requests).length, 0); + assert.strictEqual(Object.keys(agent.sockets).length, 0); + assert.strictEqual(Object.keys(agent.requests).length, 0); server.close(); }, 100); diff --git a/test/parallel/test-http-agent-error-on-idle.js b/test/parallel/test-http-agent-error-on-idle.js index b2bf6334dcbc1b..23fa4dddfab57c 100644 --- a/test/parallel/test-http-agent-error-on-idle.js +++ b/test/parallel/test-http-agent-error-on-idle.js @@ -23,13 +23,13 @@ server.listen(0, function() { const socketKey = agent.getName(requestParams); get(function(res) { - assert.equal(res.statusCode, 200); + assert.strictEqual(res.statusCode, 200); res.resume(); res.on('end', function() { process.nextTick(function() { const freeSockets = agent.freeSockets[socketKey]; - assert.equal(freeSockets.length, 1, - 'expect a free socket on ' + socketKey); + assert.strictEqual(freeSockets.length, 1, + 'expect a free socket on ' + socketKey); //generate a random error on the free socket const freeSocket = freeSockets[0]; @@ -45,8 +45,8 @@ server.listen(0, function() { } function done() { - assert.equal(Object.keys(agent.freeSockets).length, 0, - 'expect the freeSockets pool to be empty'); + assert.strictEqual(Object.keys(agent.freeSockets).length, 0, + 'expect the freeSockets pool to be empty'); agent.destroy(); server.close(); diff --git a/test/parallel/test-http-agent-keepalive.js b/test/parallel/test-http-agent-keepalive.js index a78f97edec1fdc..9ea3fd7677aebe 100644 --- a/test/parallel/test-http-agent-keepalive.js +++ b/test/parallel/test-http-agent-keepalive.js @@ -37,22 +37,22 @@ function get(path, callback) { } function checkDataAndSockets(body) { - assert.equal(body.toString(), 'hello world'); - assert.equal(agent.sockets[name].length, 1); - assert.equal(agent.freeSockets[name], undefined); + assert.strictEqual(body.toString(), 'hello world'); + assert.strictEqual(agent.sockets[name].length, 1); + assert.strictEqual(agent.freeSockets[name], undefined); } function second() { // request second, use the same socket get('/second', function(res) { - assert.equal(res.statusCode, 200); + assert.strictEqual(res.statusCode, 200); res.on('data', checkDataAndSockets); res.on('end', function() { - assert.equal(agent.sockets[name].length, 1); - assert.equal(agent.freeSockets[name], undefined); + assert.strictEqual(agent.sockets[name].length, 1); + assert.strictEqual(agent.freeSockets[name], undefined); process.nextTick(function() { - assert.equal(agent.sockets[name], undefined); - assert.equal(agent.freeSockets[name].length, 1); + assert.strictEqual(agent.sockets[name], undefined); + assert.strictEqual(agent.freeSockets[name].length, 1); remoteClose(); }); }); @@ -65,16 +65,16 @@ function remoteClose() { assert.deepStrictEqual(res.statusCode, 200); res.on('data', checkDataAndSockets); res.on('end', function() { - assert.equal(agent.sockets[name].length, 1); - assert.equal(agent.freeSockets[name], undefined); + assert.strictEqual(agent.sockets[name].length, 1); + assert.strictEqual(agent.freeSockets[name], undefined); process.nextTick(function() { - assert.equal(agent.sockets[name], undefined); - assert.equal(agent.freeSockets[name].length, 1); + assert.strictEqual(agent.sockets[name], undefined); + assert.strictEqual(agent.freeSockets[name].length, 1); // waitting remote server close the socket setTimeout(function() { - assert.equal(agent.sockets[name], undefined); - assert.equal(agent.freeSockets[name], undefined, - 'freeSockets is not empty'); + assert.strictEqual(agent.sockets[name], undefined); + assert.strictEqual(agent.freeSockets[name], undefined, + 'freeSockets is not empty'); remoteError(); }, common.platformTimeout(200)); }); @@ -89,13 +89,13 @@ function remoteError() { }); req.on('error', function(err) { assert.ok(err); - assert.equal(err.message, 'socket hang up'); - assert.equal(agent.sockets[name].length, 1); - assert.equal(agent.freeSockets[name], undefined); + assert.strictEqual(err.message, 'socket hang up'); + assert.strictEqual(agent.sockets[name].length, 1); + assert.strictEqual(agent.freeSockets[name], undefined); // Wait socket 'close' event emit setTimeout(function() { - assert.equal(agent.sockets[name], undefined); - assert.equal(agent.freeSockets[name], undefined); + assert.strictEqual(agent.sockets[name], undefined); + assert.strictEqual(agent.freeSockets[name], undefined); done(); }, common.platformTimeout(1)); }); @@ -110,14 +110,14 @@ server.listen(0, function() { name = `localhost:${server.address().port}:`; // request first, and keep alive get('/first', function(res) { - assert.equal(res.statusCode, 200); + assert.strictEqual(res.statusCode, 200); res.on('data', checkDataAndSockets); res.on('end', function() { - assert.equal(agent.sockets[name].length, 1); - assert.equal(agent.freeSockets[name], undefined); + assert.strictEqual(agent.sockets[name].length, 1); + assert.strictEqual(agent.freeSockets[name], undefined); process.nextTick(function() { - assert.equal(agent.sockets[name], undefined); - assert.equal(agent.freeSockets[name].length, 1); + assert.strictEqual(agent.sockets[name], undefined); + assert.strictEqual(agent.freeSockets[name].length, 1); second(); }); }); diff --git a/test/parallel/test-http-agent-maxsockets.js b/test/parallel/test-http-agent-maxsockets.js index 6814aca3e76fbc..fc7618c5c02fe7 100644 --- a/test/parallel/test-http-agent-maxsockets.js +++ b/test/parallel/test-http-agent-maxsockets.js @@ -29,15 +29,15 @@ function done() { return; } const freepool = agent.freeSockets[Object.keys(agent.freeSockets)[0]]; - assert.equal(freepool.length, 2, - 'expect keep 2 free sockets, but got ' + freepool.length); + assert.strictEqual(freepool.length, 2, + 'expect keep 2 free sockets, but got ' + freepool.length); agent.destroy(); server.close(); } server.listen(0, function() { get('/1', function(res) { - assert.equal(res.statusCode, 200); + assert.strictEqual(res.statusCode, 200); res.resume(); res.on('end', function() { process.nextTick(done); @@ -45,7 +45,7 @@ server.listen(0, function() { }); get('/2', function(res) { - assert.equal(res.statusCode, 200); + assert.strictEqual(res.statusCode, 200); res.resume(); res.on('end', function() { process.nextTick(done); diff --git a/test/parallel/test-http-agent.js b/test/parallel/test-http-agent.js index 85975979cb3265..cfb37539ede878 100644 --- a/test/parallel/test-http-agent.js +++ b/test/parallel/test-http-agent.js @@ -35,5 +35,5 @@ server.listen(0, function() { process.on('exit', function() { - assert.equal(N * M, responses); + assert.strictEqual(N * M, responses); }); diff --git a/test/parallel/test-http-automatic-headers.js b/test/parallel/test-http-automatic-headers.js index 5fc8d780af9396..37a5c43901c33d 100644 --- a/test/parallel/test-http-automatic-headers.js +++ b/test/parallel/test-http-automatic-headers.js @@ -18,13 +18,13 @@ server.on('listening', function() { path: '/hello', agent: agent }, function(res) { - assert.equal(res.statusCode, 200); - assert.equal(res.headers['x-date'], 'foo'); - assert.equal(res.headers['x-connection'], 'bar'); - assert.equal(res.headers['x-content-length'], 'baz'); + assert.strictEqual(res.statusCode, 200); + assert.strictEqual(res.headers['x-date'], 'foo'); + assert.strictEqual(res.headers['x-connection'], 'bar'); + assert.strictEqual(res.headers['x-content-length'], 'baz'); assert(res.headers['date']); - assert.equal(res.headers['connection'], 'keep-alive'); - assert.equal(res.headers['content-length'], '0'); + assert.strictEqual(res.headers['connection'], 'keep-alive'); + assert.strictEqual(res.headers['content-length'], '0'); server.close(); agent.destroy(); }); diff --git a/test/parallel/test-http-blank-header.js b/test/parallel/test-http-blank-header.js index 2a6bf482077166..edd8923fa8e2f7 100644 --- a/test/parallel/test-http-blank-header.js +++ b/test/parallel/test-http-blank-header.js @@ -5,8 +5,8 @@ const http = require('http'); const net = require('net'); const server = http.createServer(common.mustCall(function(req, res) { - assert.equal('GET', req.method); - assert.equal('/blah', req.url); + assert.strictEqual('GET', req.method); + assert.strictEqual('/blah', req.url); assert.deepStrictEqual({ host: 'mapdevel.trolologames.ru:443', origin: 'http://mapdevel.trolologames.ru', diff --git a/test/parallel/test-http-buffer-sanity.js b/test/parallel/test-http-buffer-sanity.js index c240cd13b1825c..4226f1c65237fa 100644 --- a/test/parallel/test-http-buffer-sanity.js +++ b/test/parallel/test-http-buffer-sanity.js @@ -23,7 +23,7 @@ const web = http.Server(function(req, res) { process.stdout.write(','); measuredSize += d.length; for (let j = 0; j < d.length; j++) { - assert.equal(buffer[i], d[j]); + assert.strictEqual(buffer[i], d[j]); i++; } }); @@ -54,7 +54,7 @@ web.listen(0, common.mustCall(function() { console.log('Got response'); res.setEncoding('utf8'); res.on('data', common.mustCall(function(string) { - assert.equal('thanks', string); + assert.strictEqual('thanks', string); })); })); req.end(buffer); @@ -62,5 +62,5 @@ web.listen(0, common.mustCall(function() { process.on('exit', function() { - assert.equal(bufferSize, measuredSize); + assert.strictEqual(bufferSize, measuredSize); }); diff --git a/test/parallel/test-http-catch-uncaughtexception.js b/test/parallel/test-http-catch-uncaughtexception.js index 06d9b9a6e5d4e0..1366b6e26ea37f 100644 --- a/test/parallel/test-http-catch-uncaughtexception.js +++ b/test/parallel/test-http-catch-uncaughtexception.js @@ -5,7 +5,7 @@ const assert = require('assert'); const http = require('http'); const uncaughtCallback = common.mustCall(function(er) { - assert.equal(er.message, 'get did fail'); + assert.strictEqual(er.message, 'get did fail'); }); process.on('uncaughtException', uncaughtCallback); diff --git a/test/parallel/test-http-chunk-problem.js b/test/parallel/test-http-chunk-problem.js index 82e8534af9e334..0ffd71813e7108 100644 --- a/test/parallel/test-http-chunk-problem.js +++ b/test/parallel/test-http-chunk-problem.js @@ -52,8 +52,8 @@ function executeRequest(cb) { 'shasum' ].join(' '), (err, stdout, stderr) => { assert.ifError(err); - assert.equal('8c206a1a87599f532ce68675536f0b1546900d7a', - stdout.slice(0, 40)); + assert.strictEqual('8c206a1a87599f532ce68675536f0b1546900d7a', + stdout.slice(0, 40)); cb(); } ); diff --git a/test/parallel/test-http-chunked.js b/test/parallel/test-http-chunked.js index 516523221133ec..b70a704bb7fce4 100644 --- a/test/parallel/test-http-chunked.js +++ b/test/parallel/test-http-chunked.js @@ -30,9 +30,9 @@ server.listen(0, function() { throw e; }); x.on('end', function() { - assert.equal('string', typeof data); + assert.strictEqual('string', typeof data); console.log('here is the response:'); - assert.equal(UTF8_STRING, data); + assert.strictEqual(UTF8_STRING, data); console.log(data); server.close(); }); diff --git a/test/parallel/test-http-client-abort.js b/test/parallel/test-http-client-abort.js index 738c620815a21a..5c5b319bfa4f5f 100644 --- a/test/parallel/test-http-client-abort.js +++ b/test/parallel/test-http-client-abort.js @@ -51,5 +51,5 @@ server.listen(0, function() { }); process.on('exit', function() { - assert.equal(N, clientAborts); + assert.strictEqual(N, clientAborts); }); diff --git a/test/parallel/test-http-client-agent.js b/test/parallel/test-http-client-agent.js index 3c2b9c89727467..277c7a33ae586a 100644 --- a/test/parallel/test-http-client-agent.js +++ b/test/parallel/test-http-client-agent.js @@ -34,7 +34,7 @@ function request(i) { socket.on('close', function() { ++count; if (count < max) { - assert.equal(http.globalAgent.sockets[name].indexOf(socket), -1); + assert.strictEqual(http.globalAgent.sockets[name].indexOf(socket), -1); } else { assert(!http.globalAgent.sockets.hasOwnProperty(name)); assert(!http.globalAgent.requests.hasOwnProperty(name)); @@ -46,5 +46,5 @@ function request(i) { } process.on('exit', function() { - assert.equal(count, max); + assert.strictEqual(count, max); }); diff --git a/test/parallel/test-http-client-get-url.js b/test/parallel/test-http-client-get-url.js index 9311110bdc041c..aa37055050c952 100644 --- a/test/parallel/test-http-client-get-url.js +++ b/test/parallel/test-http-client-get-url.js @@ -6,8 +6,8 @@ const url = require('url'); const URL = url.URL; const server = http.createServer(common.mustCall(function(req, res) { - assert.equal('GET', req.method); - assert.equal('/foo?bar', req.url); + assert.strictEqual('GET', req.method); + assert.strictEqual('/foo?bar', req.url); res.writeHead(200, {'Content-Type': 'text/plain'}); res.write('hello\n'); res.end(); diff --git a/test/parallel/test-http-client-parse-error.js b/test/parallel/test-http-client-parse-error.js index 0d8f577a78566c..e649f983a51626 100644 --- a/test/parallel/test-http-client-parse-error.js +++ b/test/parallel/test-http-client-parse-error.js @@ -27,13 +27,13 @@ net.createServer(function(c) { }).on('error', function(e) { console.log('got error from client'); assert.ok(e.message.indexOf('Parse Error') >= 0); - assert.equal(e.code, 'HPE_INVALID_CONSTANT'); + assert.strictEqual(e.code, 'HPE_INVALID_CONSTANT'); parseErrors++; }).end(); } }); process.on('exit', function() { - assert.equal(connects, 2); - assert.equal(parseErrors, 2); + assert.strictEqual(connects, 2); + assert.strictEqual(parseErrors, 2); }); diff --git a/test/parallel/test-http-client-race-2.js b/test/parallel/test-http-client-race-2.js index d9e89b85eca1ed..24475059c55688 100644 --- a/test/parallel/test-http-client-race-2.js +++ b/test/parallel/test-http-client-race-2.js @@ -83,7 +83,7 @@ server.on('listening', function() { }); process.on('exit', function() { - assert.equal(body1_s, body1); - assert.equal(body2_s, body2); - assert.equal(body3_s, body3); + assert.strictEqual(body1_s, body1); + assert.strictEqual(body2_s, body2); + assert.strictEqual(body3_s, body3); }); diff --git a/test/parallel/test-http-client-race.js b/test/parallel/test-http-client-race.js index 14e3300f20a436..f7610507378921 100644 --- a/test/parallel/test-http-client-race.js +++ b/test/parallel/test-http-client-race.js @@ -41,6 +41,6 @@ server.on('listening', function() { }); process.on('exit', function() { - assert.equal(body1_s, body1); - assert.equal(body2_s, body2); + assert.strictEqual(body1_s, body1); + assert.strictEqual(body2_s, body2); }); diff --git a/test/parallel/test-http-client-reject-chunked-with-content-length.js b/test/parallel/test-http-client-reject-chunked-with-content-length.js index daa0591cd75506..3d99f6ef406b1b 100644 --- a/test/parallel/test-http-client-reject-chunked-with-content-length.js +++ b/test/parallel/test-http-client-reject-chunked-with-content-length.js @@ -22,7 +22,7 @@ server.listen(0, () => { }); req.on('error', common.mustCall((err) => { assert(/^Parse Error/.test(err.message)); - assert.equal(err.code, 'HPE_UNEXPECTED_CONTENT_LENGTH'); + assert.strictEqual(err.code, 'HPE_UNEXPECTED_CONTENT_LENGTH'); server.close(); })); }); diff --git a/test/parallel/test-http-client-reject-cr-no-lf.js b/test/parallel/test-http-client-reject-cr-no-lf.js index 4cabfa0107bbc8..23530cbc7ae74c 100644 --- a/test/parallel/test-http-client-reject-cr-no-lf.js +++ b/test/parallel/test-http-client-reject-cr-no-lf.js @@ -21,7 +21,7 @@ server.listen(0, () => { }); req.on('error', common.mustCall((err) => { assert(/^Parse Error/.test(err.message)); - assert.equal(err.code, 'HPE_LF_EXPECTED'); + assert.strictEqual(err.code, 'HPE_LF_EXPECTED'); server.close(); })); }); diff --git a/test/parallel/test-http-client-response-domain.js b/test/parallel/test-http-client-response-domain.js index eb8b226acef169..20babf51a9178a 100644 --- a/test/parallel/test-http-client-response-domain.js +++ b/test/parallel/test-http-client-response-domain.js @@ -23,7 +23,7 @@ server.listen(common.PIPE, function() { function test() { d.on('error', common.mustCall(function(err) { - assert.equal('should be caught by domain', err.message); + assert.strictEqual('should be caught by domain', err.message); })); const req = http.get({ diff --git a/test/parallel/test-http-client-upload-buf.js b/test/parallel/test-http-client-upload-buf.js index 338aab9cc59ba0..208de06e8ebcd5 100644 --- a/test/parallel/test-http-client-upload-buf.js +++ b/test/parallel/test-http-client-upload-buf.js @@ -6,7 +6,7 @@ const http = require('http'); const N = 1024; const server = http.createServer(common.mustCall(function(req, res) { - assert.equal('POST', req.method); + assert.strictEqual('POST', req.method); let bytesReceived = 0; diff --git a/test/parallel/test-http-client-upload.js b/test/parallel/test-http-client-upload.js index ba60681776ba49..474dc333d142cd 100644 --- a/test/parallel/test-http-client-upload.js +++ b/test/parallel/test-http-client-upload.js @@ -4,7 +4,7 @@ const assert = require('assert'); const http = require('http'); const server = http.createServer(common.mustCall(function(req, res) { - assert.equal('POST', req.method); + assert.strictEqual('POST', req.method); req.setEncoding('utf8'); let sent_body = ''; diff --git a/test/parallel/test-http-conn-reset.js b/test/parallel/test-http-conn-reset.js index f7f08a6bf42c81..ae04c41aff5181 100644 --- a/test/parallel/test-http-conn-reset.js +++ b/test/parallel/test-http-conn-reset.js @@ -23,7 +23,7 @@ function onListen() { assert.ok(false, 'this should never run'); }); req.on('error', common.mustCall(function(err) { - assert.equal(err.code, 'ECONNRESET'); + assert.strictEqual(err.code, 'ECONNRESET'); })); req.end(); } diff --git a/test/parallel/test-http-connect-req-res.js b/test/parallel/test-http-connect-req-res.js index 0b1ca4630a562e..45881f0d7d7395 100644 --- a/test/parallel/test-http-connect-req-res.js +++ b/test/parallel/test-http-connect-req-res.js @@ -5,8 +5,8 @@ const http = require('http'); const server = http.createServer(common.fail); server.on('connect', common.mustCall(function(req, socket, firstBodyChunk) { - assert.equal(req.method, 'CONNECT'); - assert.equal(req.url, 'example.com:443'); + assert.strictEqual(req.method, 'CONNECT'); + assert.strictEqual(req.url, 'example.com:443'); console.error('Server got CONNECT request'); // It is legal for the server to send some data intended for the client @@ -46,19 +46,19 @@ server.listen(0, common.mustCall(function() { // Make sure this socket has detached. assert(!socket.ondata); assert(!socket.onend); - assert.equal(socket.listeners('connect').length, 0); - assert.equal(socket.listeners('data').length, 0); + assert.strictEqual(socket.listeners('connect').length, 0); + assert.strictEqual(socket.listeners('data').length, 0); let data = firstBodyChunk.toString(); // test that the firstBodyChunk was not parsed as HTTP - assert.equal(data, 'Head'); + assert.strictEqual(data, 'Head'); socket.on('data', function(buf) { data += buf.toString(); }); socket.on('end', function() { - assert.equal(data, 'HeadRequestEnd'); + assert.strictEqual(data, 'HeadRequestEnd'); server.close(); }); socket.end('End'); diff --git a/test/parallel/test-http-createConnection.js b/test/parallel/test-http-createConnection.js index 69592eb09ff487..279d7022795318 100644 --- a/test/parallel/test-http-createConnection.js +++ b/test/parallel/test-http-createConnection.js @@ -23,7 +23,7 @@ const server = http.createServer(common.mustCall(function(req, res) { http.get({ createConnection: fn }, function(res) { common.fail('Unexpected response callback'); }).on('error', common.mustCall(function(err) { - assert.equal(err.message, 'Could not create socket'); + assert.strictEqual(err.message, 'Could not create socket'); server.close(); })); }); diff --git a/test/parallel/test-http-default-encoding.js b/test/parallel/test-http-default-encoding.js index 46327085184069..2c41328749f027 100644 --- a/test/parallel/test-http-default-encoding.js +++ b/test/parallel/test-http-default-encoding.js @@ -33,5 +33,5 @@ server.listen(0, function() { }); process.on('exit', function() { - assert.equal(expected, result); + assert.strictEqual(expected, result); }); diff --git a/test/parallel/test-http-default-port.js b/test/parallel/test-http-default-port.js index d26150f4a824ed..146e5846c107b6 100644 --- a/test/parallel/test-http-default-port.js +++ b/test/parallel/test-http-default-port.js @@ -29,8 +29,8 @@ process.on('exit', function() { }); http.createServer(function(req, res) { - assert.equal(req.headers.host, hostExpect); - assert.equal(req.headers['x-port'], this.address().port); + assert.strictEqual(req.headers.host, hostExpect); + assert.strictEqual(req.headers['x-port'], this.address().port.toString()); res.writeHead(200); res.end('ok'); this.close(); @@ -49,8 +49,8 @@ http.createServer(function(req, res) { if (common.hasCrypto) { https.createServer(options, function(req, res) { - assert.equal(req.headers.host, hostExpect); - assert.equal(req.headers['x-port'], this.address().port); + assert.strictEqual(req.headers.host, hostExpect); + assert.strictEqual(req.headers['x-port'], this.address().port.toString()); res.writeHead(200); res.end('ok'); this.close(); diff --git a/test/parallel/test-http-destroyed-socket-write2.js b/test/parallel/test-http-destroyed-socket-write2.js index 01023a088576ef..59e0eeecfc8a7a 100644 --- a/test/parallel/test-http-destroyed-socket-write2.js +++ b/test/parallel/test-http-destroyed-socket-write2.js @@ -47,8 +47,8 @@ server.listen(0, function() { break; } - assert.equal(req.output.length, 0); - assert.equal(req.outputEncodings.length, 0); + assert.strictEqual(req.output.length, 0); + assert.strictEqual(req.outputEncodings.length, 0); server.close(); })); diff --git a/test/parallel/test-http-double-content-length.js b/test/parallel/test-http-double-content-length.js index f6c13becfd83dd..fdc79fb74ec5c2 100644 --- a/test/parallel/test-http-double-content-length.js +++ b/test/parallel/test-http-double-content-length.js @@ -13,7 +13,7 @@ const server = http.createServer((req, res) => { }); server.on('clientError', common.mustCall((err, socket) => { assert(/^Parse Error/.test(err.message)); - assert.equal(err.code, 'HPE_UNEXPECTED_CONTENT_LENGTH'); + assert.strictEqual(err.code, 'HPE_UNEXPECTED_CONTENT_LENGTH'); socket.destroy(); })); diff --git a/test/parallel/test-http-expect-continue.js b/test/parallel/test-http-expect-continue.js index 0cf90e3b115e60..01f285d29e54fb 100644 --- a/test/parallel/test-http-expect-continue.js +++ b/test/parallel/test-http-expect-continue.js @@ -10,7 +10,8 @@ let sent_continue = false; let got_continue = false; function handler(req, res) { - assert.equal(sent_continue, true, 'Full response sent before 100 Continue'); + assert.strictEqual(sent_continue, true, 'Full response sent before ' + + '100 Continue'); console.error('Server sending full response...'); res.writeHead(200, { 'Content-Type': 'text/plain', @@ -47,15 +48,15 @@ server.on('listening', function() { req.end(test_req_body); }); req.on('response', function(res) { - assert.equal(got_continue, true, - 'Full response received before 100 Continue'); - assert.equal(200, res.statusCode, - 'Final status code was ' + res.statusCode + ', not 200.'); + assert.strictEqual(got_continue, true, + 'Full response received before 100 Continue'); + assert.strictEqual(200, res.statusCode, 'Final status code was ' + + res.statusCode + ', not 200.'); res.setEncoding('utf8'); res.on('data', function(chunk) { body += chunk; }); res.on('end', function() { console.error('Got full response.'); - assert.equal(body, test_res_body, 'Response body doesn\'t match.'); + assert.strictEqual(body, test_res_body, 'Response body doesn\'t match.'); assert.ok('abcd' in res.headers, 'Response headers missing.'); outstanding_reqs--; if (outstanding_reqs === 0) { diff --git a/test/parallel/test-http-expect-handling.js b/test/parallel/test-http-expect-handling.js index f1f12847315a22..fed715bc2ace7d 100644 --- a/test/parallel/test-http-expect-handling.js +++ b/test/parallel/test-http-expect-handling.js @@ -37,8 +37,8 @@ function nextTest() { http.get(options, function(response) { console.log('client: expected status: ' + test); console.log('client: statusCode: ' + response.statusCode); - assert.equal(response.statusCode, test); - assert.equal(response.statusMessage, 'Expectation Failed'); + assert.strictEqual(response.statusCode, test); + assert.strictEqual(response.statusMessage, 'Expectation Failed'); response.on('end', function() { testsComplete++; @@ -51,5 +51,5 @@ function nextTest() { process.on('exit', function() { - assert.equal(2, testsComplete); + assert.strictEqual(2, testsComplete); }); diff --git a/test/parallel/test-http-extra-response.js b/test/parallel/test-http-extra-response.js index 6ebecaad1300de..5e994134c2e2ad 100644 --- a/test/parallel/test-http-extra-response.js +++ b/test/parallel/test-http-extra-response.js @@ -36,7 +36,7 @@ const server = net.createServer(function(socket) { }); socket.on('error', function(err) { - assert.equal(err.code, 'ECONNRESET'); + assert.strictEqual(err.code, 'ECONNRESET'); }); }); @@ -53,7 +53,7 @@ server.listen(0, common.mustCall(function() { res.on('end', common.mustCall(function() { console.log('Response ended, read ' + buffer.length + ' bytes'); - assert.equal(body, buffer); + assert.strictEqual(body, buffer); server.close(); })); })); diff --git a/test/parallel/test-http-flush-headers.js b/test/parallel/test-http-flush-headers.js index c2b382188a14c1..8ca5e92e5e02bc 100644 --- a/test/parallel/test-http-flush-headers.js +++ b/test/parallel/test-http-flush-headers.js @@ -5,7 +5,7 @@ const http = require('http'); const server = http.createServer(); server.on('request', function(req, res) { - assert.equal(req.headers['foo'], 'bar'); + assert.strictEqual(req.headers['foo'], 'bar'); res.end('ok'); server.close(); }); diff --git a/test/parallel/test-http-flush-response-headers.js b/test/parallel/test-http-flush-response-headers.js index ea7d2d97b4dc7a..bfc43a602b7018 100644 --- a/test/parallel/test-http-flush-response-headers.js +++ b/test/parallel/test-http-flush-response-headers.js @@ -20,7 +20,7 @@ server.listen(0, common.localhostIPv4, function() { req.end(); function onResponse(res) { - assert.equal(res.headers['foo'], 'bar'); + assert.strictEqual(res.headers['foo'], 'bar'); res.destroy(); server.close(); } diff --git a/test/parallel/test-http-full-response.js b/test/parallel/test-http-full-response.js index c834c6e6545320..881734ceb1af6f 100644 --- a/test/parallel/test-http-full-response.js +++ b/test/parallel/test-http-full-response.js @@ -38,8 +38,8 @@ function runAb(opts, callback) { m = /HTML transferred:\s*(\d+) bytes/mi.exec(stdout); const htmlTransfered = parseInt(m[1]); - assert.equal(bodyLength, documentLength); - assert.equal(completeRequests * documentLength, htmlTransfered); + assert.strictEqual(bodyLength, documentLength); + assert.strictEqual(completeRequests * documentLength, htmlTransfered); if (callback) callback(); }); diff --git a/test/parallel/test-http-get-pipeline-problem.js b/test/parallel/test-http-get-pipeline-problem.js index 15c96a9a4e12ea..56bfb33456dff7 100644 --- a/test/parallel/test-http-get-pipeline-problem.js +++ b/test/parallel/test-http-get-pipeline-problem.js @@ -74,8 +74,8 @@ function checkFiles() { const fn = i + '.jpg'; assert.ok(files.indexOf(fn) >= 0, "couldn't find '" + fn + "'"); const stat = fs.statSync(common.tmpDir + '/' + fn); - assert.equal(image.length, stat.size, - "size doesn't match on '" + fn + + assert.strictEqual(image.length, stat.size, + "size doesn't match on '" + fn + "'. Got " + stat.size + ' bytes'); } @@ -84,7 +84,7 @@ function checkFiles() { process.on('exit', function() { - assert.equal(total, requests); - assert.equal(total, responses); + assert.strictEqual(total, requests); + assert.strictEqual(total, responses); assert.ok(checkedFiles); }); diff --git a/test/parallel/test-http-header-read.js b/test/parallel/test-http-header-read.js index 3d9e756d505238..5465fd30f272be 100644 --- a/test/parallel/test-http-header-read.js +++ b/test/parallel/test-http-header-read.js @@ -18,7 +18,7 @@ const s = http.createServer(function(req, res) { // and does not throw an exception (Issue 752) assert.doesNotThrow( function() { - assert.equal(plain, res.getHeader(contentType)); + assert.strictEqual(plain, res.getHeader(contentType)); } ); }); diff --git a/test/parallel/test-http-host-headers.js b/test/parallel/test-http-host-headers.js index 0f6233190ce875..c127b3375b224c 100644 --- a/test/parallel/test-http-host-headers.js +++ b/test/parallel/test-http-host-headers.js @@ -7,10 +7,10 @@ const httpServer = http.createServer(reqHandler); function reqHandler(req, res) { console.log('Got request: ' + req.headers.host + ' ' + req.url); if (req.url === '/setHostFalse5') { - assert.equal(req.headers.host, undefined); + assert.strictEqual(req.headers.host, undefined); } else { - assert.equal(req.headers.host, `localhost:${this.address().port}`, - 'Wrong host header for req[' + req.url + ']: ' + + assert.strictEqual(req.headers.host, `localhost:${this.address().port}`, + 'Wrong host header for req[' + req.url + ']: ' + req.headers.host); } res.writeHead(200, {}); diff --git a/test/parallel/test-http-keep-alive-close-on-header.js b/test/parallel/test-http-keep-alive-close-on-header.js index 15d5d62d429658..b36fb2e8db9a5a 100644 --- a/test/parallel/test-http-keep-alive-close-on-header.js +++ b/test/parallel/test-http-keep-alive-close-on-header.js @@ -25,7 +25,7 @@ server.listen(0, function() { port: this.address().port, agent: agent }, function(res) { - assert.equal(1, agent.sockets[name].length); + assert.strictEqual(1, agent.sockets[name].length); res.resume(); }); request.on('socket', function(s) { @@ -42,7 +42,7 @@ server.listen(0, function() { port: this.address().port, agent: agent }, function(res) { - assert.equal(1, agent.sockets[name].length); + assert.strictEqual(1, agent.sockets[name].length); res.resume(); }); request.on('socket', function(s) { @@ -59,7 +59,7 @@ server.listen(0, function() { agent: agent }, function(response) { response.on('end', function() { - assert.equal(1, agent.sockets[name].length); + assert.strictEqual(1, agent.sockets[name].length); server.close(); }); response.resume(); @@ -73,5 +73,5 @@ server.listen(0, function() { }); process.on('exit', function() { - assert.equal(3, connectCount); + assert.strictEqual(3, connectCount); }); diff --git a/test/parallel/test-http-keepalive-client.js b/test/parallel/test-http-keepalive-client.js index c9cf7bba96a7db..eaefa3887c395d 100644 --- a/test/parallel/test-http-keepalive-client.js +++ b/test/parallel/test-http-keepalive-client.js @@ -9,7 +9,7 @@ let serverSocket = null; const server = http.createServer(function(req, res) { // They should all come in on the same server socket. if (serverSocket) { - assert.equal(req.socket, serverSocket); + assert.strictEqual(req.socket, serverSocket); } else { serverSocket = req.socket; } @@ -45,7 +45,7 @@ function makeRequest(n) { req.on('socket', function(sock) { if (clientSocket) { - assert.equal(sock, clientSocket); + assert.strictEqual(sock, clientSocket); } else { clientSocket = sock; } @@ -58,7 +58,7 @@ function makeRequest(n) { data += c; }); res.on('end', function() { - assert.equal(data, '/' + n); + assert.strictEqual(data, '/' + n); setTimeout(function() { actualRequests++; makeRequest(n - 1); @@ -68,6 +68,6 @@ function makeRequest(n) { } process.on('exit', function() { - assert.equal(actualRequests, expectRequests); + assert.strictEqual(actualRequests, expectRequests); console.log('ok'); }); diff --git a/test/parallel/test-http-keepalive-maxsockets.js b/test/parallel/test-http-keepalive-maxsockets.js index 14e9e88ef7fd09..0d684a43f778f9 100644 --- a/test/parallel/test-http-keepalive-maxsockets.js +++ b/test/parallel/test-http-keepalive-maxsockets.js @@ -22,17 +22,17 @@ server.listen(0, function() { let closed = false; makeReqs(10, function(er) { assert.ifError(er); - assert.equal(count(agent.freeSockets), 2); - assert.equal(count(agent.sockets), 0); - assert.equal(serverSockets.length, 5); + assert.strictEqual(count(agent.freeSockets), 2); + assert.strictEqual(count(agent.sockets), 0); + assert.strictEqual(serverSockets.length, 5); // now make 10 more reqs. // should use the 2 free reqs from the pool first. makeReqs(10, function(er) { assert.ifError(er); - assert.equal(count(agent.freeSockets), 2); - assert.equal(count(agent.sockets), 0); - assert.equal(serverSockets.length, 8); + assert.strictEqual(count(agent.freeSockets), 2); + assert.strictEqual(count(agent.sockets), 0); + assert.strictEqual(serverSockets.length, 8); agent.destroy(); server.close(function() { @@ -72,7 +72,7 @@ server.listen(0, function() { data += c; }); res.on('end', function() { - assert.equal(data, '/' + i); + assert.strictEqual(data, '/' + i); cb(); }); }).end(); diff --git a/test/parallel/test-http-keepalive-request.js b/test/parallel/test-http-keepalive-request.js index dc9bdefb333d13..5f53f6d999f38d 100644 --- a/test/parallel/test-http-keepalive-request.js +++ b/test/parallel/test-http-keepalive-request.js @@ -9,7 +9,7 @@ let serverSocket = null; const server = http.createServer(function(req, res) { // They should all come in on the same server socket. if (serverSocket) { - assert.equal(req.socket, serverSocket); + assert.strictEqual(req.socket, serverSocket); } else { serverSocket = req.socket; } @@ -45,7 +45,7 @@ function makeRequest(n) { req.on('socket', function(sock) { if (clientSocket) { - assert.equal(sock, clientSocket); + assert.strictEqual(sock, clientSocket); } else { clientSocket = sock; } @@ -58,7 +58,7 @@ function makeRequest(n) { data += c; }); res.on('end', function() { - assert.equal(data, '/' + n); + assert.strictEqual(data, '/' + n); setTimeout(function() { actualRequests++; makeRequest(n - 1); @@ -68,6 +68,6 @@ function makeRequest(n) { } process.on('exit', function() { - assert.equal(actualRequests, expectRequests); + assert.strictEqual(actualRequests, expectRequests); console.log('ok'); }); diff --git a/test/parallel/test-http-localaddress.js b/test/parallel/test-http-localaddress.js index e8df6888866f9c..d48a4ec8f5b0ee 100644 --- a/test/parallel/test-http-localaddress.js +++ b/test/parallel/test-http-localaddress.js @@ -10,7 +10,7 @@ if (!common.hasMultiLocalhost()) { const server = http.createServer(function(req, res) { console.log('Connect from: ' + req.connection.remoteAddress); - assert.equal('127.0.0.2', req.connection.remoteAddress); + assert.strictEqual('127.0.0.2', req.connection.remoteAddress); req.on('end', function() { res.writeHead(200, { 'Content-Type': 'text/plain' }); diff --git a/test/parallel/test-http-malformed-request.js b/test/parallel/test-http-malformed-request.js index a36c9fdbe29451..93aff802c7afbd 100644 --- a/test/parallel/test-http-malformed-request.js +++ b/test/parallel/test-http-malformed-request.js @@ -31,5 +31,5 @@ server.on('listening', function() { }); process.on('exit', function() { - assert.equal(nrequests_expected, nrequests_completed); + assert.strictEqual(nrequests_expected, nrequests_completed); }); diff --git a/test/parallel/test-http-max-headers-count.js b/test/parallel/test-http-max-headers-count.js index 018ed33c1b9e49..fd92637f7ac10b 100644 --- a/test/parallel/test-http-max-headers-count.js +++ b/test/parallel/test-http-max-headers-count.js @@ -21,7 +21,7 @@ let max = maxAndExpected[requests][0]; let expected = maxAndExpected[requests][1]; const server = http.createServer(function(req, res) { - assert.equal(Object.keys(req.headers).length, expected); + assert.strictEqual(Object.keys(req.headers).length, expected); if (++requests < maxAndExpected.length) { max = maxAndExpected[requests][0]; expected = maxAndExpected[requests][1]; @@ -47,7 +47,7 @@ server.listen(0, function() { port: server.address().port, headers: headers }, function(res) { - assert.equal(Object.keys(res.headers).length, expected); + assert.strictEqual(Object.keys(res.headers).length, expected); res.on('end', function() { if (++responses < maxAndExpected.length) { doRequest(); @@ -63,6 +63,6 @@ server.listen(0, function() { }); process.on('exit', function() { - assert.equal(requests, maxAndExpected.length); - assert.equal(responses, maxAndExpected.length); + assert.strictEqual(requests, maxAndExpected.length); + assert.strictEqual(responses, maxAndExpected.length); }); diff --git a/test/parallel/test-http-multi-line-headers.js b/test/parallel/test-http-multi-line-headers.js index 2096f533a196d1..f7998c254870d5 100644 --- a/test/parallel/test-http-multi-line-headers.js +++ b/test/parallel/test-http-multi-line-headers.js @@ -27,8 +27,8 @@ server.listen(0, common.mustCall(function() { host: '127.0.0.1', port: this.address().port }, common.mustCall(function(res) { - assert.equal(res.headers['content-type'], - 'text/plain; x-unix-mode=0600; name="hello.txt"'); + assert.strictEqual(res.headers['content-type'], + 'text/plain; x-unix-mode=0600; name="hello.txt"'); res.destroy(); })); })); diff --git a/test/parallel/test-http-parser-bad-ref.js b/test/parallel/test-http-parser-bad-ref.js index 69682128fadbdf..97b4685e18382b 100644 --- a/test/parallel/test-http-parser-bad-ref.js +++ b/test/parallel/test-http-parser-bad-ref.js @@ -83,7 +83,7 @@ demoBug('POST /1/22 HTTP/1.1\r\n' + /* eslint-enable align-function-arguments */ process.on('exit', function() { - assert.equal(2, headersComplete); - assert.equal(2, messagesComplete); + assert.strictEqual(2, headersComplete); + assert.strictEqual(2, messagesComplete); console.log('done!'); }); diff --git a/test/parallel/test-http-parser-free.js b/test/parallel/test-http-parser-free.js index 80cc3cc64ee5b3..aff0fa6198ef44 100644 --- a/test/parallel/test-http-parser-free.js +++ b/test/parallel/test-http-parser-free.js @@ -31,5 +31,5 @@ server.listen(0, function() { }); process.on('exit', function() { - assert.equal(responses, N); + assert.strictEqual(responses, N); }); diff --git a/test/parallel/test-http-parser.js b/test/parallel/test-http-parser.js index e1215fbd13ae40..de7302e60d91ba 100644 --- a/test/parallel/test-http-parser.js +++ b/test/parallel/test-http-parser.js @@ -51,7 +51,7 @@ function mustCall(f, times) { process.setMaxListeners(256); process.on('exit', function() { - assert.equal(actual, times || 1); + assert.strictEqual(actual, times || 1); }); return function() { @@ -64,7 +64,7 @@ function mustCall(f, times) { function expectBody(expected) { return mustCall(function(buf, start, len) { const body = '' + buf.slice(start, start + len); - assert.equal(body, expected); + assert.strictEqual(body, expected); }); } @@ -535,10 +535,10 @@ function expectBody(expected) { const onHeadersComplete1 = function(versionMajor, versionMinor, headers, method, url, statusCode, statusMessage, upgrade, shouldKeepAlive) { - assert.equal(method, methods.indexOf('PUT')); - assert.equal(url, '/this'); - assert.equal(versionMajor, 1); - assert.equal(versionMinor, 1); + assert.strictEqual(method, methods.indexOf('PUT')); + assert.strictEqual(url, '/this'); + assert.strictEqual(versionMajor, 1); + assert.strictEqual(versionMinor, 1); assert.deepStrictEqual( headers, ['Content-Type', 'text/plain', 'Transfer-Encoding', 'chunked']); diff --git a/test/parallel/test-http-pause.js b/test/parallel/test-http-pause.js index 8bb8dd4b5da25c..440cab413c50a5 100644 --- a/test/parallel/test-http-pause.js +++ b/test/parallel/test-http-pause.js @@ -50,6 +50,6 @@ server.listen(0, function() { }); process.on('exit', function() { - assert.equal(expectedServer, resultServer); - assert.equal(expectedClient, resultClient); + assert.strictEqual(expectedServer, resultServer); + assert.strictEqual(expectedClient, resultClient); }); diff --git a/test/parallel/test-http-pipeline-regr-2639.js b/test/parallel/test-http-pipeline-regr-2639.js index 7933e419d324f7..133e4126683d9b 100644 --- a/test/parallel/test-http-pipeline-regr-2639.js +++ b/test/parallel/test-http-pipeline-regr-2639.js @@ -29,5 +29,5 @@ const server = http.createServer(function(req, res) { }); process.on('exit', function() { - assert.equal(received, COUNT); + assert.strictEqual(received, COUNT); }); diff --git a/test/parallel/test-http-pipeline-regr-3332.js b/test/parallel/test-http-pipeline-regr-3332.js index 3ab9e6104c9848..b34ad499850b70 100644 --- a/test/parallel/test-http-pipeline-regr-3332.js +++ b/test/parallel/test-http-pipeline-regr-3332.js @@ -36,5 +36,5 @@ process.on('exit', function() { // The server should pause connection on pipeline flood, but it shoul still // resume it and finish processing the requests, when its output queue will // be empty again. - assert.equal(received, COUNT); + assert.strictEqual(received, COUNT); }); diff --git a/test/parallel/test-http-proxy.js b/test/parallel/test-http-proxy.js index 8e7fd55a0ed6ea..91dce932dc576b 100644 --- a/test/parallel/test-http-proxy.js +++ b/test/parallel/test-http-proxy.js @@ -29,8 +29,8 @@ const proxy = http.createServer(function(req, res) { console.error('proxy res headers: ' + JSON.stringify(proxy_res.headers)); - assert.equal('world', proxy_res.headers['hello']); - assert.equal('text/plain', proxy_res.headers['content-type']); + assert.strictEqual('world', proxy_res.headers['hello']); + assert.strictEqual('text/plain', proxy_res.headers['content-type']); assert.deepStrictEqual(cookies, proxy_res.headers['set-cookie']); res.writeHead(proxy_res.statusCode, proxy_res.headers); @@ -58,10 +58,10 @@ function startReq() { path: '/test' }, function(res) { console.error('got res'); - assert.equal(200, res.statusCode); + assert.strictEqual(200, res.statusCode); - assert.equal('world', res.headers['hello']); - assert.equal('text/plain', res.headers['content-type']); + assert.strictEqual('world', res.headers['hello']); + assert.strictEqual('text/plain', res.headers['content-type']); assert.deepStrictEqual(cookies, res.headers['set-cookie']); res.setEncoding('utf8'); @@ -82,5 +82,5 @@ console.error('listen backend'); backend.listen(0, startReq); process.on('exit', function() { - assert.equal(body, 'hello world\n'); + assert.strictEqual(body, 'hello world\n'); }); diff --git a/test/parallel/test-http-remove-header-stays-removed.js b/test/parallel/test-http-remove-header-stays-removed.js index 077ff0f5b33f40..c38a042283dbb9 100644 --- a/test/parallel/test-http-remove-header-stays-removed.js +++ b/test/parallel/test-http-remove-header-stays-removed.js @@ -23,13 +23,13 @@ const server = http.createServer(function(request, response) { let response = ''; process.on('exit', function() { - assert.equal('beep boop\n', response); + assert.strictEqual('beep boop\n', response); console.log('ok'); }); server.listen(0, function() { http.get({ port: this.address().port }, function(res) { - assert.equal(200, res.statusCode); + assert.strictEqual(200, res.statusCode); assert.deepStrictEqual(res.headers, { date: 'coffee o clock' }); res.setEncoding('ascii'); diff --git a/test/parallel/test-http-request-dont-override-options.js b/test/parallel/test-http-request-dont-override-options.js index 04235fd0e42b4e..33ed2ed6c0070d 100644 --- a/test/parallel/test-http-request-dont-override-options.js +++ b/test/parallel/test-http-request-dont-override-options.js @@ -33,7 +33,7 @@ http.createServer(function(req, res) { }).end(); process.on('exit', function() { - assert.equal(requests, 1); + assert.strictEqual(requests, 1); assert.strictEqual(options.host, undefined); assert.strictEqual(options.hostname, common.localhostIPv4); diff --git a/test/parallel/test-http-res-write-after-end.js b/test/parallel/test-http-res-write-after-end.js index 2ee0e4e29d95e4..45db9fe13f7655 100644 --- a/test/parallel/test-http-res-write-after-end.js +++ b/test/parallel/test-http-res-write-after-end.js @@ -12,7 +12,7 @@ const server = http.Server(common.mustCall(function(req, res) { res.end(); const r = res.write('This should raise an error.'); - assert.equal(r, true, 'write after end should return true'); + assert.strictEqual(r, true, 'write after end should return true'); })); server.listen(0, function() { diff --git a/test/parallel/test-http-response-multi-content-length.js b/test/parallel/test-http-response-multi-content-length.js index 7cd802a74aa80c..f3dce208756f74 100644 --- a/test/parallel/test-http-response-multi-content-length.js +++ b/test/parallel/test-http-response-multi-content-length.js @@ -39,7 +39,7 @@ server.listen(0, common.mustCall(() => { } ).on('error', common.mustCall((err) => { assert(/^Parse Error/.test(err.message)); - assert.equal(err.code, 'HPE_UNEXPECTED_CONTENT_LENGTH'); + assert.strictEqual(err.code, 'HPE_UNEXPECTED_CONTENT_LENGTH'); count++; if (count === MAX_COUNT) server.close(); @@ -48,5 +48,5 @@ server.listen(0, common.mustCall(() => { })); process.on('exit', () => { - assert.equal(count, MAX_COUNT); + assert.strictEqual(count, MAX_COUNT); }); diff --git a/test/parallel/test-http-response-multiheaders.js b/test/parallel/test-http-response-multiheaders.js index 8f48dc2377f3c3..5739dac31d690b 100644 --- a/test/parallel/test-http-response-multiheaders.js +++ b/test/parallel/test-http-response-multiheaders.js @@ -60,9 +60,9 @@ server.listen(0, common.mustCall(function() { common.mustCall(function(res) { if (++count === 2) server.close(); for (const name of norepeat) { - assert.equal(res.headers[name], 'A'); + assert.strictEqual(res.headers[name], 'A'); } - assert.equal(res.headers['x-a'], 'A, B'); + assert.strictEqual(res.headers['x-a'], 'A, B'); }) ); } diff --git a/test/parallel/test-http-response-no-headers.js b/test/parallel/test-http-response-no-headers.js index 3f44b4ef5fde0b..e10571af4ccf25 100644 --- a/test/parallel/test-http-response-no-headers.js +++ b/test/parallel/test-http-response-no-headers.js @@ -32,7 +32,7 @@ function test(httpVersion, callback) { }); res.on('end', common.mustCall(function() { - assert.equal(body, expected[httpVersion]); + assert.strictEqual(body, expected[httpVersion]); server.close(); if (callback) process.nextTick(callback); })); diff --git a/test/parallel/test-http-response-readable.js b/test/parallel/test-http-response-readable.js index 07c0a40e4bf1a8..a4906643d3d35b 100644 --- a/test/parallel/test-http-response-readable.js +++ b/test/parallel/test-http-response-readable.js @@ -10,9 +10,10 @@ const testServer = new http.Server(function(req, res) { testServer.listen(0, function() { http.get({ port: this.address().port }, function(res) { - assert.equal(res.readable, true, 'res.readable initially true'); + assert.strictEqual(res.readable, true, 'res.readable initially true'); res.on('end', function() { - assert.equal(res.readable, false, 'res.readable set to false after end'); + assert.strictEqual(res.readable, false, + 'res.readable set to false after end'); testServer.close(); }); res.resume(); diff --git a/test/parallel/test-http-response-status-message.js b/test/parallel/test-http-response-status-message.js index d17dfb24c6b4c8..95859634ac394a 100644 --- a/test/parallel/test-http-response-status-message.js +++ b/test/parallel/test-http-response-status-message.js @@ -47,7 +47,7 @@ const runTest = function(testCaseIndex) { }, function(response) { console.log('client: expected status message: ' + testCase.statusMessage); console.log('client: actual status message: ' + response.statusMessage); - assert.equal(testCase.statusMessage, response.statusMessage); + assert.strictEqual(testCase.statusMessage, response.statusMessage); response.on('end', function() { testsComplete++; @@ -66,5 +66,5 @@ const runTest = function(testCaseIndex) { server.listen(0, function() { runTest(0); }); process.on('exit', function() { - assert.equal(testCases.length, testsComplete); + assert.strictEqual(testCases.length, testsComplete); }); diff --git a/test/parallel/test-http-server-client-error.js b/test/parallel/test-http-server-client-error.js index 260963dc24daaa..88c224f8374145 100644 --- a/test/parallel/test-http-server-client-error.js +++ b/test/parallel/test-http-server-client-error.js @@ -26,13 +26,13 @@ server.listen(0, function() { chunks += chunk; }); client.once('end', function() { - assert.equal(chunks, 'HTTP/1.1 400 Bad Request\r\n\r\n'); + assert.strictEqual(chunks, 'HTTP/1.1 400 Bad Request\r\n\r\n'); }); } // Normal request http.get({ port: this.address().port, path: '/' }, function(res) { - assert.equal(res.statusCode, 200); + assert.strictEqual(res.statusCode, 200); res.resume(); res.once('end', next); }); diff --git a/test/parallel/test-http-server-multiheaders.js b/test/parallel/test-http-server-multiheaders.js index 189ab0657bacb0..a89d45fd6c6195 100644 --- a/test/parallel/test-http-server-multiheaders.js +++ b/test/parallel/test-http-server-multiheaders.js @@ -8,15 +8,16 @@ const assert = require('assert'); const http = require('http'); const srv = http.createServer(function(req, res) { - assert.equal(req.headers.accept, 'abc, def, ghijklmnopqrst'); - assert.equal(req.headers.host, 'foo'); - assert.equal(req.headers['www-authenticate'], 'foo, bar, baz'); - assert.equal(req.headers['proxy-authenticate'], 'foo, bar, baz'); - assert.equal(req.headers['x-foo'], 'bingo'); - assert.equal(req.headers['x-bar'], 'banjo, bango'); - assert.equal(req.headers['sec-websocket-protocol'], 'chat, share'); - assert.equal(req.headers['sec-websocket-extensions'], 'foo; 1, bar; 2, baz'); - assert.equal(req.headers['constructor'], 'foo, bar, baz'); + assert.strictEqual(req.headers.accept, 'abc, def, ghijklmnopqrst'); + assert.strictEqual(req.headers.host, 'foo'); + assert.strictEqual(req.headers['www-authenticate'], 'foo, bar, baz'); + assert.strictEqual(req.headers['proxy-authenticate'], 'foo, bar, baz'); + assert.strictEqual(req.headers['x-foo'], 'bingo'); + assert.strictEqual(req.headers['x-bar'], 'banjo, bango'); + assert.strictEqual(req.headers['sec-websocket-protocol'], 'chat, share'); + assert.strictEqual(req.headers['sec-websocket-extensions'], + 'foo; 1, bar; 2, baz'); + assert.strictEqual(req.headers['constructor'], 'foo, bar, baz'); res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('EOF'); diff --git a/test/parallel/test-http-server-multiheaders2.js b/test/parallel/test-http-server-multiheaders2.js index 82cc9960329a11..53e68e6f0d3e74 100644 --- a/test/parallel/test-http-server-multiheaders2.js +++ b/test/parallel/test-http-server-multiheaders2.js @@ -50,12 +50,12 @@ const multipleForbidden = [ const srv = http.createServer(function(req, res) { multipleForbidden.forEach(function(header) { - assert.equal(req.headers[header.toLowerCase()], - 'foo', 'header parsed incorrectly: ' + header); + assert.strictEqual(req.headers[header.toLowerCase()], + 'foo', 'header parsed incorrectly: ' + header); }); multipleAllowed.forEach(function(header) { - assert.equal(req.headers[header.toLowerCase()], - 'foo, bar', 'header parsed incorrectly: ' + header); + assert.strictEqual(req.headers[header.toLowerCase()], + 'foo, bar', 'header parsed incorrectly: ' + header); }); res.writeHead(200, {'Content-Type': 'text/plain'}); diff --git a/test/parallel/test-http-server-reject-chunked-with-content-length.js b/test/parallel/test-http-server-reject-chunked-with-content-length.js index d8697cd38cde72..b158fda75c5846 100644 --- a/test/parallel/test-http-server-reject-chunked-with-content-length.js +++ b/test/parallel/test-http-server-reject-chunked-with-content-length.js @@ -14,7 +14,7 @@ const server = http.createServer((req, res) => { }); server.on('clientError', common.mustCall((err) => { assert(/^Parse Error/.test(err.message)); - assert.equal(err.code, 'HPE_UNEXPECTED_CONTENT_LENGTH'); + assert.strictEqual(err.code, 'HPE_UNEXPECTED_CONTENT_LENGTH'); server.close(); })); server.listen(0, () => { diff --git a/test/parallel/test-http-server-reject-cr-no-lf.js b/test/parallel/test-http-server-reject-cr-no-lf.js index 81a7208d982334..73508cf08e9b7a 100644 --- a/test/parallel/test-http-server-reject-cr-no-lf.js +++ b/test/parallel/test-http-server-reject-cr-no-lf.js @@ -16,7 +16,7 @@ const server = http.createServer((req, res) => { }); server.on('clientError', common.mustCall((err) => { assert(/^Parse Error/.test(err.message)); - assert.equal(err.code, 'HPE_LF_EXPECTED'); + assert.strictEqual(err.code, 'HPE_LF_EXPECTED'); server.close(); })); server.listen(0, () => { diff --git a/test/parallel/test-http-server-unconsume.js b/test/parallel/test-http-server-unconsume.js index fca2691aacc25d..9f80e9ea82de48 100644 --- a/test/parallel/test-http-server-unconsume.js +++ b/test/parallel/test-http-server-unconsume.js @@ -26,5 +26,5 @@ const server = http.createServer(function(req, res) { }); process.on('exit', function() { - assert.equal(received, 'hello world'); + assert.strictEqual(received, 'hello world'); }); diff --git a/test/parallel/test-http-set-cookies.js b/test/parallel/test-http-set-cookies.js index cb06352b3ca85d..7be28b04034fb0 100644 --- a/test/parallel/test-http-set-cookies.js +++ b/test/parallel/test-http-set-cookies.js @@ -27,7 +27,7 @@ server.on('listening', function() { // set-cookie headers are always return in an array. // even if there is only one. assert.deepStrictEqual(['A'], res.headers['set-cookie']); - assert.equal('text/plain', res.headers['content-type']); + assert.strictEqual('text/plain', res.headers['content-type']); res.on('data', function(chunk) { console.log(chunk.toString()); @@ -44,7 +44,7 @@ server.on('listening', function() { http.get({ port: this.address().port, path: '/two' }, function(res) { assert.deepStrictEqual(['A', 'B'], res.headers['set-cookie']); - assert.equal('text/plain', res.headers['content-type']); + assert.strictEqual('text/plain', res.headers['content-type']); res.on('data', function(chunk) { console.log(chunk.toString()); @@ -60,5 +60,5 @@ server.on('listening', function() { }); process.on('exit', function() { - assert.equal(2, nresponses); + assert.strictEqual(2, nresponses); }); diff --git a/test/parallel/test-http-set-timeout-server.js b/test/parallel/test-http-set-timeout-server.js index 7a2447763e4cf9..097aeb260bdc5e 100644 --- a/test/parallel/test-http-set-timeout-server.js +++ b/test/parallel/test-http-set-timeout-server.js @@ -118,7 +118,7 @@ test(function serverRequestNotTimeoutAfterEnd(cb) { test(function serverResponseTimeoutWithPipeline(cb) { let caughtTimeout = ''; process.on('exit', function() { - assert.equal(caughtTimeout, '/2'); + assert.strictEqual(caughtTimeout, '/2'); }); const server = http.createServer(function(req, res) { const s = res.setTimeout(50, function() { diff --git a/test/parallel/test-http-should-keep-alive.js b/test/parallel/test-http-should-keep-alive.js index 77a3c3922a20f0..190c8c8d8843ad 100644 --- a/test/parallel/test-http-should-keep-alive.js +++ b/test/parallel/test-http-should-keep-alive.js @@ -30,8 +30,8 @@ const server = net.createServer(function(socket) { }).listen(0, function() { function makeRequest() { const req = http.get({port: server.address().port}, function(res) { - assert.equal(req.shouldKeepAlive, SHOULD_KEEP_ALIVE[responses], - SERVER_RESPONSES[responses] + ' should ' + + assert.strictEqual(req.shouldKeepAlive, SHOULD_KEEP_ALIVE[responses], + SERVER_RESPONSES[responses] + ' should ' + (SHOULD_KEEP_ALIVE[responses] ? '' : 'not ') + 'Keep-Alive'); ++responses; @@ -48,6 +48,6 @@ const server = net.createServer(function(socket) { }); process.on('exit', function() { - assert.equal(requests, SERVER_RESPONSES.length); - assert.equal(responses, SHOULD_KEEP_ALIVE.length); + assert.strictEqual(requests, SERVER_RESPONSES.length); + assert.strictEqual(responses, SHOULD_KEEP_ALIVE.length); }); diff --git a/test/parallel/test-http-status-code.js b/test/parallel/test-http-status-code.js index b5060109bf4985..111b5db16daecb 100644 --- a/test/parallel/test-http-status-code.js +++ b/test/parallel/test-http-status-code.js @@ -14,7 +14,7 @@ const s = http.createServer(function(req, res) { const t = tests[testIdx]; res.writeHead(t, {'Content-Type': 'text/plain'}); console.log('--\nserver: statusCode after writeHead: ' + res.statusCode); - assert.equal(res.statusCode, t); + assert.strictEqual(res.statusCode, t); res.end('hello world\n'); }); @@ -30,7 +30,7 @@ function nextTest() { http.get({ port: s.address().port }, function(response) { console.log('client: expected status: ' + test); console.log('client: statusCode: ' + response.statusCode); - assert.equal(response.statusCode, test); + assert.strictEqual(response.statusCode, test); response.on('end', function() { testsComplete++; testIdx += 1; @@ -42,5 +42,5 @@ function nextTest() { process.on('exit', function() { - assert.equal(5, testsComplete); + assert.strictEqual(5, testsComplete); }); diff --git a/test/parallel/test-http-status-message.js b/test/parallel/test-http-status-message.js index 668b02ee0780b4..54c683212b8ff1 100644 --- a/test/parallel/test-http-status-message.js +++ b/test/parallel/test-http-status-message.js @@ -23,7 +23,7 @@ function test() { }); client.on('end', function() { const head = Buffer.concat(bufs).toString('latin1').split('\r\n')[0]; - assert.equal('HTTP/1.1 200 Custom Message', head); + assert.strictEqual('HTTP/1.1 200 Custom Message', head); console.log('ok'); s.close(); }); diff --git a/test/parallel/test-http-timeout-overflow.js b/test/parallel/test-http-timeout-overflow.js index 39b4550d57e529..755859ddc9992d 100644 --- a/test/parallel/test-http-timeout-overflow.js +++ b/test/parallel/test-http-timeout-overflow.js @@ -37,6 +37,6 @@ server.listen(0, function() { }); process.once('exit', function() { - assert.equal(clientRequests, 1); - assert.equal(serverRequests, 1); + assert.strictEqual(clientRequests, 1); + assert.strictEqual(serverRequests, 1); }); diff --git a/test/parallel/test-http-upgrade-advertise.js b/test/parallel/test-http-upgrade-advertise.js index 3deb71fbea1b75..99a3e8fd353015 100644 --- a/test/parallel/test-http-upgrade-advertise.js +++ b/test/parallel/test-http-upgrade-advertise.js @@ -18,7 +18,7 @@ function fire() { const test = tests.shift(); const done = common.mustCall(function done(result) { - assert.equal(result, test.expected); + assert.strictEqual(result, test.expected); fire(); }); diff --git a/test/parallel/test-http-upgrade-agent.js b/test/parallel/test-http-upgrade-agent.js index a196ba904905a3..e0e1c6d1f3fb6d 100644 --- a/test/parallel/test-http-upgrade-agent.js +++ b/test/parallel/test-http-upgrade-agent.js @@ -47,7 +47,7 @@ srv.listen(0, '127.0.0.1', common.mustCall(function() { }); socket.on('close', common.mustCall(function() { - assert.equal(recvData, 'nurtzo'); + assert.strictEqual(recvData.toString(), 'nurtzo'); })); console.log(res.headers); diff --git a/test/parallel/test-http-upgrade-server.js b/test/parallel/test-http-upgrade-server.js index 221263e98ce9cd..b7335b49e83c5f 100644 --- a/test/parallel/test-http-upgrade-server.js +++ b/test/parallel/test-http-upgrade-server.js @@ -76,20 +76,20 @@ function test_upgrade_with_listener() { conn.on('data', function(data) { state++; - assert.equal('string', typeof data); + assert.strictEqual('string', typeof data); if (state === 1) { - assert.equal('HTTP/1.1 101', data.substr(0, 12)); - assert.equal('WjN}|M(6', request_upgradeHead.toString('utf8')); + assert.strictEqual('HTTP/1.1 101', data.substr(0, 12)); + assert.strictEqual('WjN}|M(6', request_upgradeHead.toString('utf8')); conn.write('test', 'utf8'); } else if (state === 2) { - assert.equal('test', data); + assert.strictEqual('test', data); conn.write('kill', 'utf8'); } }); conn.on('end', function() { - assert.equal(2, state); + assert.strictEqual(2, state); conn.end(); server.removeAllListeners('upgrade'); test_upgrade_no_listener(); @@ -135,8 +135,8 @@ function test_standard_http() { }); conn.once('data', function(data) { - assert.equal('string', typeof data); - assert.equal('HTTP/1.1 200', data.substr(0, 12)); + assert.strictEqual('string', typeof data); + assert.strictEqual('HTTP/1.1 200', data.substr(0, 12)); conn.end(); }); @@ -158,7 +158,7 @@ server.listen(0, function() { Fin. -----------------------------------------------*/ process.on('exit', function() { - assert.equal(3, requests_recv); - assert.equal(3, requests_sent); + assert.strictEqual(3, requests_recv); + assert.strictEqual(3, requests_sent); assert.ok(test_upgrade_no_listener_ended); }); diff --git a/test/parallel/test-http-upgrade-server2.js b/test/parallel/test-http-upgrade-server2.js index c64b2e843637af..3ff33a9c794c25 100644 --- a/test/parallel/test-http-upgrade-server2.js +++ b/test/parallel/test-http-upgrade-server2.js @@ -15,7 +15,7 @@ server.on('upgrade', function(req, socket, upgradeHead) { }); process.on('uncaughtException', common.mustCall(function(e) { - assert.equal('upgrade error', e.message); + assert.strictEqual('upgrade error', e.message); process.exit(0); })); diff --git a/test/parallel/test-http-write-callbacks.js b/test/parallel/test-http-write-callbacks.js index 3783dc305e39a7..03250a0030ceff 100644 --- a/test/parallel/test-http-write-callbacks.js +++ b/test/parallel/test-http-write-callbacks.js @@ -14,9 +14,9 @@ const clientIncomingExpect = 'asdffoobar'; process.on('exit', function() { assert(serverEndCb); - assert.equal(serverIncoming, serverIncomingExpect); + assert.strictEqual(serverIncoming, serverIncomingExpect); assert(clientEndCb); - assert.equal(clientIncoming, clientIncomingExpect); + assert.strictEqual(clientIncoming, clientIncomingExpect); console.log('ok'); }); @@ -28,7 +28,7 @@ const server = http.createServer(function(req, res) { server.on('checkContinue', function(req, res) { server.close(); - assert.equal(req.method, 'PUT'); + assert.strictEqual(req.method, 'PUT'); res.writeContinue(function() { // continue has been written req.on('end', function() { diff --git a/test/parallel/test-http-write-empty-string.js b/test/parallel/test-http-write-empty-string.js index 69463fb3a50852..81ebc61eef2af4 100644 --- a/test/parallel/test-http-write-empty-string.js +++ b/test/parallel/test-http-write-empty-string.js @@ -21,7 +21,7 @@ server.listen(0, common.mustCall(function() { http.get({ port: this.address().port }, common.mustCall(function(res) { let response = ''; - assert.equal(200, res.statusCode); + assert.strictEqual(200, res.statusCode); res.setEncoding('ascii'); res.on('data', function(chunk) { response += chunk; diff --git a/test/parallel/test-http-write-head.js b/test/parallel/test-http-write-head.js index 12f5e00b0db493..a0e4a7fde3594f 100644 --- a/test/parallel/test-http-write-head.js +++ b/test/parallel/test-http-write-head.js @@ -25,7 +25,8 @@ const s = http.createServer(function(req, res) { res.setHeader('foo', undefined); } catch (e) { assert.ok(e instanceof Error); - assert.equal(e.message, '"value" required in setHeader("foo", value)'); + assert.strictEqual(e.message, + '"value" required in setHeader("foo", value)'); threw = true; } assert.ok(threw, 'Undefined value should throw'); @@ -39,7 +40,7 @@ s.listen(0, runTest); function runTest() { http.get({ port: this.address().port }, function(response) { response.on('end', function() { - assert.equal(response.headers['test'], '2'); + assert.strictEqual(response.headers['test'], '2'); assert.notStrictEqual(response.rawHeaders.indexOf('Test'), -1); s.close(); }); diff --git a/test/parallel/test-http-zero-length-write.js b/test/parallel/test-http-zero-length-write.js index 63446e460471e4..11db6b1aa17f45 100644 --- a/test/parallel/test-http-zero-length-write.js +++ b/test/parallel/test-http-zero-length-write.js @@ -47,7 +47,7 @@ const server = http.createServer(function(req, res) { actual += c; }); req.on('end', function() { - assert.equal(actual, expect); + assert.strictEqual(actual, expect); getSrc().pipe(res); }); server.close(); @@ -62,7 +62,7 @@ server.listen(0, function() { actual += c; }); res.on('end', function() { - assert.equal(actual, expect); + assert.strictEqual(actual, expect); }); }); getSrc().pipe(req); diff --git a/test/parallel/test-http.js b/test/parallel/test-http.js index a80a2b8856558b..1178c745e1e12a 100644 --- a/test/parallel/test-http.js +++ b/test/parallel/test-http.js @@ -36,7 +36,7 @@ const server = http.Server(function(req, res) { }); req.resume(); - //assert.equal('127.0.0.1', res.connection.remoteAddress); + //assert.strictEqual('127.0.0.1', res.connection.remoteAddress); }); server.listen(0); diff --git a/test/parallel/test-https-agent-disable-session-reuse.js b/test/parallel/test-https-agent-disable-session-reuse.js index 8e694a61b72a03..7cca9c713ae011 100644 --- a/test/parallel/test-https-agent-disable-session-reuse.js +++ b/test/parallel/test-https-agent-disable-session-reuse.js @@ -52,8 +52,8 @@ const server = https.createServer(options, function(req, res) { }); process.on('exit', function() { - assert.equal(serverRequests, TOTAL_REQS); - assert.equal(clientSessions.length, TOTAL_REQS); + assert.strictEqual(serverRequests, TOTAL_REQS); + assert.strictEqual(clientSessions.length, TOTAL_REQS); assert.notStrictEqual(clientSessions[0].toString('hex'), clientSessions[1].toString('hex')); }); diff --git a/test/parallel/test-https-agent-sni.js b/test/parallel/test-https-agent-sni.js index ca15dc3db3a88d..9bfbe3d5c6525d 100644 --- a/test/parallel/test-https-agent-sni.js +++ b/test/parallel/test-https-agent-sni.js @@ -31,7 +31,7 @@ server.listen(0, function() { function expectResponse(id) { return common.mustCall(function(res) { res.resume(); - assert.equal(res.headers['x-sni'], 'sni.' + id); + assert.strictEqual(res.headers['x-sni'], 'sni.' + id); }); } diff --git a/test/parallel/test-https-client-get-url.js b/test/parallel/test-https-client-get-url.js index 1f4f6ff748b410..caaa7522cef57b 100644 --- a/test/parallel/test-https-client-get-url.js +++ b/test/parallel/test-https-client-get-url.js @@ -21,8 +21,8 @@ const options = { }; const server = https.createServer(options, common.mustCall(function(req, res) { - assert.equal('GET', req.method); - assert.equal('/foo?bar', req.url); + assert.strictEqual('GET', req.method); + assert.strictEqual('/foo?bar', req.url); res.writeHead(200, {'Content-Type': 'text/plain'}); res.write('hello\n'); res.end(); diff --git a/test/parallel/test-https-drain.js b/test/parallel/test-https-drain.js index 0b18795078fd1f..8e85ca70b97c47 100644 --- a/test/parallel/test-https-drain.js +++ b/test/parallel/test-https-drain.js @@ -71,5 +71,5 @@ server.listen(0, function() { }); process.on('exit', function() { - assert.equal(sent, received); + assert.strictEqual(sent, received); }); diff --git a/test/parallel/test-https-eof-for-eom.js b/test/parallel/test-https-eof-for-eom.js index d5e896c7695cfd..cb48f71e51a226 100644 --- a/test/parallel/test-https-eof-for-eom.js +++ b/test/parallel/test-https-eof-for-eom.js @@ -57,7 +57,7 @@ server.listen(0, common.mustCall(function() { server.close(); console.log('3) Client got response headers.'); - assert.equal('gws', res.headers.server); + assert.strictEqual('gws', res.headers.server); res.setEncoding('utf8'); res.on('data', function(s) { diff --git a/test/parallel/test-https-foafssl.js b/test/parallel/test-https-foafssl.js index f1b8d442e27893..5a9b8eb832cae3 100644 --- a/test/parallel/test-https-foafssl.js +++ b/test/parallel/test-https-foafssl.js @@ -66,7 +66,7 @@ server.listen(0, function() { client.stdout.on('data', function(data) { const message = data.toString(); const contents = message.split(CRLF + CRLF).pop(); - assert.equal(body, contents); + assert.strictEqual(body, contents); server.close(); }); diff --git a/test/parallel/test-https-host-headers.js b/test/parallel/test-https-host-headers.js index 190f15f29a8078..ce18522fc5b5f2 100644 --- a/test/parallel/test-https-host-headers.js +++ b/test/parallel/test-https-host-headers.js @@ -18,10 +18,10 @@ const httpsServer = https.createServer(options, reqHandler); function reqHandler(req, res) { console.log('Got request: ' + req.headers.host + ' ' + req.url); if (req.url === '/setHostFalse5') { - assert.equal(req.headers.host, undefined); + assert.strictEqual(req.headers.host, undefined); } else { - assert.equal(req.headers.host, `localhost:${this.address().port}`, - 'Wrong host header for req[' + req.url + ']: ' + + assert.strictEqual(req.headers.host, `localhost:${this.address().port}`, + 'Wrong host header for req[' + req.url + ']: ' + req.headers.host); } res.writeHead(200, {}); diff --git a/test/parallel/test-https-localaddress.js b/test/parallel/test-https-localaddress.js index 78583b38ecf1cf..1c796f5843c63c 100644 --- a/test/parallel/test-https-localaddress.js +++ b/test/parallel/test-https-localaddress.js @@ -21,7 +21,7 @@ const options = { const server = https.createServer(options, function(req, res) { console.log('Connect from: ' + req.connection.remoteAddress); - assert.equal('127.0.0.2', req.connection.remoteAddress); + assert.strictEqual('127.0.0.2', req.connection.remoteAddress); req.on('end', function() { res.writeHead(200, { 'Content-Type': 'text/plain' }); diff --git a/test/parallel/test-https-pfx.js b/test/parallel/test-https-pfx.js index c30bbc0848d137..0e3a2ba3cd2663 100644 --- a/test/parallel/test-https-pfx.js +++ b/test/parallel/test-https-pfx.js @@ -22,8 +22,9 @@ const options = { }; const server = https.createServer(options, function(req, res) { - assert.equal(req.socket.authorized, false); // not a client cert - assert.equal(req.socket.authorizationError, 'DEPTH_ZERO_SELF_SIGNED_CERT'); + assert.strictEqual(req.socket.authorized, false); // not a client cert + assert.strictEqual(req.socket.authorizationError, + 'DEPTH_ZERO_SELF_SIGNED_CERT'); res.writeHead(200); res.end('OK'); }); diff --git a/test/parallel/test-https-set-timeout-server.js b/test/parallel/test-https-set-timeout-server.js index 4cf999667d7384..d6db87e61cc1d3 100644 --- a/test/parallel/test-https-set-timeout-server.js +++ b/test/parallel/test-https-set-timeout-server.js @@ -117,7 +117,7 @@ test(function serverRequestNotTimeoutAfterEnd(cb) { test(function serverResponseTimeoutWithPipeline(cb) { let caughtTimeout = ''; process.on('exit', function() { - assert.equal(caughtTimeout, '/2'); + assert.strictEqual(caughtTimeout, '/2'); }); const server = https.createServer(serverOptions, function(req, res) { res.setTimeout(50, function() { diff --git a/test/parallel/test-https-simple.js b/test/parallel/test-https-simple.js index 0040b9dd054058..8616e6c710c463 100644 --- a/test/parallel/test-https-simple.js +++ b/test/parallel/test-https-simple.js @@ -52,7 +52,7 @@ server.listen(0, function() { }); res.on('end', function() { - assert.equal(responseBody, body); + assert.strictEqual(responseBody, body); testSucceeded(); }); }); @@ -82,11 +82,11 @@ server.listen(0, function() { checkCertReq.end(); checkCertReq.on('error', function(e) { - assert.equal(e.code, 'UNABLE_TO_VERIFY_LEAF_SIGNATURE'); + assert.strictEqual(e.code, 'UNABLE_TO_VERIFY_LEAF_SIGNATURE'); testSucceeded(); }); }); process.on('exit', function() { - assert.equal(successful, tests); + assert.strictEqual(successful, tests); }); diff --git a/test/parallel/test-internal-modules-expose.js b/test/parallel/test-internal-modules-expose.js index dd3a7f7a3cd0b7..02ddfd87c363fc 100644 --- a/test/parallel/test-internal-modules-expose.js +++ b/test/parallel/test-internal-modules-expose.js @@ -4,4 +4,4 @@ require('../common'); const assert = require('assert'); -assert.equal(typeof require('internal/freelist').FreeList, 'function'); +assert.strictEqual(typeof require('internal/freelist').FreeList, 'function'); diff --git a/test/parallel/test-listen-fd-cluster.js b/test/parallel/test-listen-fd-cluster.js index de1fbed7b56aff..98810a39335acc 100644 --- a/test/parallel/test-listen-fd-cluster.js +++ b/test/parallel/test-listen-fd-cluster.js @@ -50,8 +50,8 @@ test(function(parent, port) { // it's really annoying when tests leave orphans! parent.kill(); parent.on('exit', function() { - assert.equal(s, 'hello from worker\n'); - assert.equal(res.statusCode, 200); + assert.strictEqual(s, 'hello from worker\n'); + assert.strictEqual(res.statusCode, 200); console.log('ok'); ok = true; }); diff --git a/test/parallel/test-listen-fd-detached-inherit.js b/test/parallel/test-listen-fd-detached-inherit.js index 2ac4d83dba6691..36e4df28897383 100644 --- a/test/parallel/test-listen-fd-detached-inherit.js +++ b/test/parallel/test-listen-fd-detached-inherit.js @@ -52,8 +52,8 @@ function test() { parent.kill(); } catch (e) {} - assert.equal(s, 'hello from child\n'); - assert.equal(res.statusCode, 200); + assert.strictEqual(s, 'hello from child\n'); + assert.strictEqual(res.statusCode, 200); }); }); } diff --git a/test/parallel/test-listen-fd-detached.js b/test/parallel/test-listen-fd-detached.js index 1194d001610fce..ec9d039e96e3f2 100644 --- a/test/parallel/test-listen-fd-detached.js +++ b/test/parallel/test-listen-fd-detached.js @@ -52,8 +52,8 @@ function test() { parent.kill(); } catch (e) {} - assert.equal(s, 'hello from child\n'); - assert.equal(res.statusCode, 200); + assert.strictEqual(s, 'hello from child\n'); + assert.strictEqual(res.statusCode, 200); }); }); } diff --git a/test/parallel/test-listen-fd-server.js b/test/parallel/test-listen-fd-server.js index 60aa8717a8c24e..5a1ffbb989cf8d 100644 --- a/test/parallel/test-listen-fd-server.js +++ b/test/parallel/test-listen-fd-server.js @@ -38,8 +38,8 @@ test(function(child, port) { res.on('end', function() { child.kill(); child.on('exit', function() { - assert.equal(s, 'hello from child\n'); - assert.equal(res.statusCode, 200); + assert.strictEqual(s, 'hello from child\n'); + assert.strictEqual(res.statusCode, 200); console.log('ok'); ok = true; }); diff --git a/test/parallel/test-memory-usage-emfile.js b/test/parallel/test-memory-usage-emfile.js index 09ab270b70fa21..c5345079a7f47b 100644 --- a/test/parallel/test-memory-usage-emfile.js +++ b/test/parallel/test-memory-usage-emfile.js @@ -10,4 +10,4 @@ while (files.length < 256) files.push(fs.openSync(__filename, 'r')); const r = process.memoryUsage(); -assert.equal(true, r['rss'] > 0); +assert.strictEqual(true, r['rss'] > 0); diff --git a/test/parallel/test-microtask-queue-integration-domain.js b/test/parallel/test-microtask-queue-integration-domain.js index 7110af7648ae8a..df90b6d3a372da 100644 --- a/test/parallel/test-microtask-queue-integration-domain.js +++ b/test/parallel/test-microtask-queue-integration-domain.js @@ -19,7 +19,7 @@ let expected = 0; let done = 0; process.on('exit', function() { - assert.equal(done, expected); + assert.strictEqual(done, expected); }); function test(scheduleMicrotask) { diff --git a/test/parallel/test-microtask-queue-integration.js b/test/parallel/test-microtask-queue-integration.js index d212bbae96b001..22704ab4a51d49 100644 --- a/test/parallel/test-microtask-queue-integration.js +++ b/test/parallel/test-microtask-queue-integration.js @@ -12,7 +12,7 @@ let expected = 0; let done = 0; process.on('exit', function() { - assert.equal(done, expected); + assert.strictEqual(done, expected); }); function test(scheduleMicrotask) { diff --git a/test/parallel/test-microtask-queue-run-domain.js b/test/parallel/test-microtask-queue-run-domain.js index 7d34ec829a003c..8ce2f6cd992648 100644 --- a/test/parallel/test-microtask-queue-run-domain.js +++ b/test/parallel/test-microtask-queue-run-domain.js @@ -16,7 +16,7 @@ function enqueueMicrotask(fn) { let done = 0; process.on('exit', function() { - assert.equal(done, 2); + assert.strictEqual(done, 2); }); // no nextTick, microtask diff --git a/test/parallel/test-microtask-queue-run-immediate-domain.js b/test/parallel/test-microtask-queue-run-immediate-domain.js index e09087f74e32a9..8c4d4d40d46d6b 100644 --- a/test/parallel/test-microtask-queue-run-immediate-domain.js +++ b/test/parallel/test-microtask-queue-run-immediate-domain.js @@ -16,7 +16,7 @@ function enqueueMicrotask(fn) { let done = 0; process.on('exit', function() { - assert.equal(done, 2); + assert.strictEqual(done, 2); }); // no nextTick, microtask diff --git a/test/parallel/test-microtask-queue-run-immediate.js b/test/parallel/test-microtask-queue-run-immediate.js index c5ed6c6dcbc1ae..9fee54b2d741cf 100644 --- a/test/parallel/test-microtask-queue-run-immediate.js +++ b/test/parallel/test-microtask-queue-run-immediate.js @@ -9,7 +9,7 @@ function enqueueMicrotask(fn) { let done = 0; process.on('exit', function() { - assert.equal(done, 2); + assert.strictEqual(done, 2); }); // no nextTick, microtask diff --git a/test/parallel/test-microtask-queue-run.js b/test/parallel/test-microtask-queue-run.js index 71e1fbedbaecbd..1a8f8e2ba32bc0 100644 --- a/test/parallel/test-microtask-queue-run.js +++ b/test/parallel/test-microtask-queue-run.js @@ -9,7 +9,7 @@ function enqueueMicrotask(fn) { let done = 0; process.on('exit', function() { - assert.equal(done, 2); + assert.strictEqual(done, 2); }); // no nextTick, microtask diff --git a/test/parallel/test-net-better-error-messages-path.js b/test/parallel/test-net-better-error-messages-path.js index 2f821ef5d703be..7cdc14b9bd4333 100644 --- a/test/parallel/test-net-better-error-messages-path.js +++ b/test/parallel/test-net-better-error-messages-path.js @@ -8,6 +8,6 @@ const c = net.connect(fp); c.on('connect', common.fail); c.on('error', common.mustCall(function(e) { - assert.equal(e.code, 'ENOENT'); - assert.equal(e.message, 'connect ENOENT ' + fp); + assert.strictEqual(e.code, 'ENOENT'); + assert.strictEqual(e.message, 'connect ENOENT ' + fp); })); diff --git a/test/parallel/test-net-binary.js b/test/parallel/test-net-binary.js index bcc554ac4024f6..0c5cac1c37290b 100644 --- a/test/parallel/test-net-binary.js +++ b/test/parallel/test-net-binary.js @@ -55,7 +55,7 @@ echoServer.on('listening', function() { }); process.on('exit', function() { - assert.equal(2 * 256, recv.length); + assert.strictEqual(2 * 256, recv.length); const a = recv.split(''); diff --git a/test/parallel/test-net-bind-twice.js b/test/parallel/test-net-bind-twice.js index 17fdc90cb3742b..c10b4019e4b95f 100644 --- a/test/parallel/test-net-bind-twice.js +++ b/test/parallel/test-net-bind-twice.js @@ -9,7 +9,7 @@ server1.listen(0, '127.0.0.1', common.mustCall(function() { server2.listen(this.address().port, '127.0.0.1', common.fail); server2.on('error', common.mustCall(function(e) { - assert.equal(e.code, 'EADDRINUSE'); + assert.strictEqual(e.code, 'EADDRINUSE'); server1.close(); })); })); diff --git a/test/parallel/test-net-bytes-read.js b/test/parallel/test-net-bytes-read.js index 52fb577b9e7830..aed14fe279eb5b 100644 --- a/test/parallel/test-net-bytes-read.js +++ b/test/parallel/test-net-bytes-read.js @@ -23,14 +23,14 @@ const server = net.createServer((socket) => { }); socket.on('end', common.mustCall(() => { - assert.equal(socket.bytesRead, prev); - assert.equal(big.length, prev); + assert.strictEqual(socket.bytesRead, prev); + assert.strictEqual(big.length, prev); })); socket.on('close', common.mustCall(() => { assert(!socket._handle); - assert.equal(socket.bytesRead, prev); - assert.equal(big.length, prev); + assert.strictEqual(socket.bytesRead, prev); + assert.strictEqual(big.length, prev); })); }); socket.end(); diff --git a/test/parallel/test-net-bytes-stats.js b/test/parallel/test-net-bytes-stats.js index 4cc6eee8373e86..33e089da50880a 100644 --- a/test/parallel/test-net-bytes-stats.js +++ b/test/parallel/test-net-bytes-stats.js @@ -52,6 +52,6 @@ tcp.listen(0, function doTest() { }); process.on('exit', function() { - assert.equal(bytesRead, 12); - assert.equal(bytesWritten, 12); + assert.strictEqual(bytesRead, 12); + assert.strictEqual(bytesWritten, 12); }); diff --git a/test/parallel/test-net-connect-buffer.js b/test/parallel/test-net-connect-buffer.js index c43ee1abd0e305..1e296675879130 100644 --- a/test/parallel/test-net-connect-buffer.js +++ b/test/parallel/test-net-connect-buffer.js @@ -18,7 +18,7 @@ const tcp = net.Server(function(s) { s.on('end', function() { console.error('SERVER: end', buf.toString()); - assert.equal(buf, "L'État, c'est moi"); + assert.strictEqual(buf, "L'État, c'est moi"); console.log('tcp socket disconnect'); s.end(); }); @@ -41,7 +41,7 @@ tcp.listen(0, function() { console.log('connecting = ' + socket.connecting); - assert.equal('opening', socket.readyState); + assert.strictEqual('opening', socket.readyState); // Make sure that anything besides a buffer or a string throws. [null, @@ -76,18 +76,18 @@ tcp.listen(0, function() { dataWritten = true; assert.ok(connectHappened); console.error('socket.bytesWritten', socket.bytesWritten); - //assert.equal(socket.bytesWritten, Buffer.from(a + b).length); + //assert.strictEqual(socket.bytesWritten, Buffer.from(a + b).length); console.error('data written'); }); console.error('socket.bytesWritten', socket.bytesWritten); console.error('write returned', r); - assert.equal(socket.bytesWritten, Buffer.from(a).length); + assert.strictEqual(socket.bytesWritten, Buffer.from(a).length); - assert.equal(false, r); + assert.strictEqual(false, r); socket.end(b); - assert.equal('opening', socket.readyState); + assert.strictEqual('opening', socket.readyState); }); process.on('exit', function() { diff --git a/test/parallel/test-net-connect-local-error.js b/test/parallel/test-net-connect-local-error.js index 8f1784565d38ee..23bfacde336f36 100644 --- a/test/parallel/test-net-connect-local-error.js +++ b/test/parallel/test-net-connect-local-error.js @@ -10,6 +10,6 @@ const client = net.connect({ }); client.on('error', common.mustCall(function onError(err) { - assert.equal(err.localPort, common.PORT); - assert.equal(err.localAddress, common.localhostIPv4); + assert.strictEqual(err.localPort, common.PORT); + assert.strictEqual(err.localAddress, common.localhostIPv4); })); diff --git a/test/parallel/test-net-create-connection.js b/test/parallel/test-net-create-connection.js index a5d8cd101d974d..dc5981ecd20221 100644 --- a/test/parallel/test-net-create-connection.js +++ b/test/parallel/test-net-create-connection.js @@ -102,5 +102,5 @@ server.on('close', function() { }); process.on('exit', function() { - assert.equal(clientConnected, expectedConnections); + assert.strictEqual(clientConnected, expectedConnections); }); diff --git a/test/parallel/test-net-dns-error.js b/test/parallel/test-net-dns-error.js index aa288c5fde1ffa..5ca02313686589 100644 --- a/test/parallel/test-net-dns-error.js +++ b/test/parallel/test-net-dns-error.js @@ -12,11 +12,11 @@ function do_not_call() { const socket = net.connect(42, host, do_not_call); socket.on('error', common.mustCall(function(err) { - assert.equal(err.code, 'ENOTFOUND'); + assert.strictEqual(err.code, 'ENOTFOUND'); })); socket.on('lookup', function(err, ip, type) { assert(err instanceof Error); - assert.equal(err.code, 'ENOTFOUND'); - assert.equal(ip, undefined); - assert.equal(type, undefined); + assert.strictEqual(err.code, 'ENOTFOUND'); + assert.strictEqual(ip, undefined); + assert.strictEqual(type, undefined); }); diff --git a/test/parallel/test-net-dns-lookup.js b/test/parallel/test-net-dns-lookup.js index 8d9930f4b7a366..166029f31c482f 100644 --- a/test/parallel/test-net-dns-lookup.js +++ b/test/parallel/test-net-dns-lookup.js @@ -11,9 +11,9 @@ const server = net.createServer(function(client) { server.listen(0, '127.0.0.1', common.mustCall(function() { net.connect(this.address().port, 'localhost') .on('lookup', common.mustCall(function(err, ip, type, host) { - assert.equal(err, null); - assert.equal(ip, '127.0.0.1'); - assert.equal(type, '4'); - assert.equal(host, 'localhost'); + assert.strictEqual(err, null); + assert.strictEqual(ip, '127.0.0.1'); + assert.strictEqual(type, 4); + assert.strictEqual(host, 'localhost'); })); })); diff --git a/test/parallel/test-net-eaddrinuse.js b/test/parallel/test-net-eaddrinuse.js index 3d7ceb8d5e38f7..cf4293e8230875 100644 --- a/test/parallel/test-net-eaddrinuse.js +++ b/test/parallel/test-net-eaddrinuse.js @@ -9,7 +9,7 @@ const server2 = net.createServer(function(socket) { }); server1.listen(0, function() { server2.on('error', function(error) { - assert.equal(true, error.message.indexOf('EADDRINUSE') >= 0); + assert.strictEqual(true, error.message.indexOf('EADDRINUSE') >= 0); server1.close(); }); server2.listen(this.address().port); diff --git a/test/parallel/test-net-error-twice.js b/test/parallel/test-net-error-twice.js index 98a2c337559b06..3c25d1c98ed346 100644 --- a/test/parallel/test-net-error-twice.js +++ b/test/parallel/test-net-error-twice.js @@ -38,5 +38,5 @@ const srv = net.createServer(function onConnection(conn) { process.on('exit', function() { console.log(errs); - assert.equal(errs.length, 1); + assert.strictEqual(errs.length, 1); }); diff --git a/test/parallel/test-net-isip.js b/test/parallel/test-net-isip.js index 65d88523fe930e..626f29488b67ea 100644 --- a/test/parallel/test-net-isip.js +++ b/test/parallel/test-net-isip.js @@ -3,68 +3,70 @@ require('../common'); const assert = require('assert'); const net = require('net'); -assert.equal(net.isIP('127.0.0.1'), 4); -assert.equal(net.isIP('x127.0.0.1'), 0); -assert.equal(net.isIP('example.com'), 0); -assert.equal(net.isIP('0000:0000:0000:0000:0000:0000:0000:0000'), 6); -assert.equal(net.isIP('0000:0000:0000:0000:0000:0000:0000:0000::0000'), 0); -assert.equal(net.isIP('1050:0:0:0:5:600:300c:326b'), 6); -assert.equal(net.isIP('2001:252:0:1::2008:6'), 6); -assert.equal(net.isIP('2001:dead:beef:1::2008:6'), 6); -assert.equal(net.isIP('2001::'), 6); -assert.equal(net.isIP('2001:dead::'), 6); -assert.equal(net.isIP('2001:dead:beef::'), 6); -assert.equal(net.isIP('2001:dead:beef:1::'), 6); -assert.equal(net.isIP('ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff'), 6); -assert.equal(net.isIP(':2001:252:0:1::2008:6:'), 0); -assert.equal(net.isIP(':2001:252:0:1::2008:6'), 0); -assert.equal(net.isIP('2001:252:0:1::2008:6:'), 0); -assert.equal(net.isIP('2001:252::1::2008:6'), 0); -assert.equal(net.isIP('::2001:252:1:2008:6'), 6); -assert.equal(net.isIP('::2001:252:1:1.1.1.1'), 6); -assert.equal(net.isIP('::2001:252:1:255.255.255.255'), 6); -assert.equal(net.isIP('::2001:252:1:255.255.255.255.76'), 0); -assert.equal(net.isIP('::anything'), 0); -assert.equal(net.isIP('::1'), 6); -assert.equal(net.isIP('::'), 6); -assert.equal(net.isIP('0000:0000:0000:0000:0000:0000:12345:0000'), 0); -assert.equal(net.isIP('0'), 0); -assert.equal(net.isIP(), 0); -assert.equal(net.isIP(''), 0); -assert.equal(net.isIP(null), 0); -assert.equal(net.isIP(123), 0); -assert.equal(net.isIP(true), 0); -assert.equal(net.isIP({}), 0); -assert.equal(net.isIP({ toString: () => '::2001:252:1:255.255.255.255' }), 6); -assert.equal(net.isIP({ toString: () => '127.0.0.1' }), 4); -assert.equal(net.isIP({ toString: () => 'bla' }), 0); +assert.strictEqual(net.isIP('127.0.0.1'), 4); +assert.strictEqual(net.isIP('x127.0.0.1'), 0); +assert.strictEqual(net.isIP('example.com'), 0); +assert.strictEqual(net.isIP('0000:0000:0000:0000:0000:0000:0000:0000'), 6); +assert.strictEqual(net.isIP('0000:0000:0000:0000:0000:0000:0000:0000::0000'), + 0); +assert.strictEqual(net.isIP('1050:0:0:0:5:600:300c:326b'), 6); +assert.strictEqual(net.isIP('2001:252:0:1::2008:6'), 6); +assert.strictEqual(net.isIP('2001:dead:beef:1::2008:6'), 6); +assert.strictEqual(net.isIP('2001::'), 6); +assert.strictEqual(net.isIP('2001:dead::'), 6); +assert.strictEqual(net.isIP('2001:dead:beef::'), 6); +assert.strictEqual(net.isIP('2001:dead:beef:1::'), 6); +assert.strictEqual(net.isIP('ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff'), 6); +assert.strictEqual(net.isIP(':2001:252:0:1::2008:6:'), 0); +assert.strictEqual(net.isIP(':2001:252:0:1::2008:6'), 0); +assert.strictEqual(net.isIP('2001:252:0:1::2008:6:'), 0); +assert.strictEqual(net.isIP('2001:252::1::2008:6'), 0); +assert.strictEqual(net.isIP('::2001:252:1:2008:6'), 6); +assert.strictEqual(net.isIP('::2001:252:1:1.1.1.1'), 6); +assert.strictEqual(net.isIP('::2001:252:1:255.255.255.255'), 6); +assert.strictEqual(net.isIP('::2001:252:1:255.255.255.255.76'), 0); +assert.strictEqual(net.isIP('::anything'), 0); +assert.strictEqual(net.isIP('::1'), 6); +assert.strictEqual(net.isIP('::'), 6); +assert.strictEqual(net.isIP('0000:0000:0000:0000:0000:0000:12345:0000'), 0); +assert.strictEqual(net.isIP('0'), 0); +assert.strictEqual(net.isIP(), 0); +assert.strictEqual(net.isIP(''), 0); +assert.strictEqual(net.isIP(null), 0); +assert.strictEqual(net.isIP(123), 0); +assert.strictEqual(net.isIP(true), 0); +assert.strictEqual(net.isIP({}), 0); +assert.strictEqual(net.isIP({ toString: () => '::2001:252:1:255.255.255.255' }), + 6); +assert.strictEqual(net.isIP({ toString: () => '127.0.0.1' }), 4); +assert.strictEqual(net.isIP({ toString: () => 'bla' }), 0); -assert.equal(net.isIPv4('127.0.0.1'), true); -assert.equal(net.isIPv4('example.com'), false); -assert.equal(net.isIPv4('2001:252:0:1::2008:6'), false); -assert.equal(net.isIPv4(), false); -assert.equal(net.isIPv4(''), false); -assert.equal(net.isIPv4(null), false); -assert.equal(net.isIPv4(123), false); -assert.equal(net.isIPv4(true), false); -assert.equal(net.isIPv4({}), false); -assert.equal(net.isIPv4({ +assert.strictEqual(net.isIPv4('127.0.0.1'), true); +assert.strictEqual(net.isIPv4('example.com'), false); +assert.strictEqual(net.isIPv4('2001:252:0:1::2008:6'), false); +assert.strictEqual(net.isIPv4(), false); +assert.strictEqual(net.isIPv4(''), false); +assert.strictEqual(net.isIPv4(null), false); +assert.strictEqual(net.isIPv4(123), false); +assert.strictEqual(net.isIPv4(true), false); +assert.strictEqual(net.isIPv4({}), false); +assert.strictEqual(net.isIPv4({ toString: () => '::2001:252:1:255.255.255.255' }), false); -assert.equal(net.isIPv4({ toString: () => '127.0.0.1' }), true); -assert.equal(net.isIPv4({ toString: () => 'bla' }), false); +assert.strictEqual(net.isIPv4({ toString: () => '127.0.0.1' }), true); +assert.strictEqual(net.isIPv4({ toString: () => 'bla' }), false); -assert.equal(net.isIPv6('127.0.0.1'), false); -assert.equal(net.isIPv6('example.com'), false); -assert.equal(net.isIPv6('2001:252:0:1::2008:6'), true); -assert.equal(net.isIPv6(), false); -assert.equal(net.isIPv6(''), false); -assert.equal(net.isIPv6(null), false); -assert.equal(net.isIPv6(123), false); -assert.equal(net.isIPv6(true), false); -assert.equal(net.isIPv6({}), false); -assert.equal(net.isIPv6({ +assert.strictEqual(net.isIPv6('127.0.0.1'), false); +assert.strictEqual(net.isIPv6('example.com'), false); +assert.strictEqual(net.isIPv6('2001:252:0:1::2008:6'), true); +assert.strictEqual(net.isIPv6(), false); +assert.strictEqual(net.isIPv6(''), false); +assert.strictEqual(net.isIPv6(null), false); +assert.strictEqual(net.isIPv6(123), false); +assert.strictEqual(net.isIPv6(true), false); +assert.strictEqual(net.isIPv6({}), false); +assert.strictEqual(net.isIPv6({ toString: () => '::2001:252:1:255.255.255.255' }), true); -assert.equal(net.isIPv6({ toString: () => '127.0.0.1' }), false); -assert.equal(net.isIPv6({ toString: () => 'bla' }), false); +assert.strictEqual(net.isIPv6({ toString: () => '127.0.0.1' }), false); +assert.strictEqual(net.isIPv6({ toString: () => 'bla' }), false); diff --git a/test/parallel/test-net-listen-exclusive-random-ports.js b/test/parallel/test-net-listen-exclusive-random-ports.js index cc1ab4d805994f..1909af067ce4d7 100644 --- a/test/parallel/test-net-listen-exclusive-random-ports.js +++ b/test/parallel/test-net-listen-exclusive-random-ports.js @@ -10,11 +10,11 @@ if (cluster.isMaster) { const worker1 = cluster.fork(); worker1.on('message', function(port1) { - assert.equal(port1, port1 | 0, 'first worker could not listen'); + assert.strictEqual(port1, port1 | 0, 'first worker could not listen'); const worker2 = cluster.fork(); worker2.on('message', function(port2) { - assert.equal(port2, port2 | 0, 'second worker could not listen'); + assert.strictEqual(port2, port2 | 0, 'second worker could not listen'); assert.notStrictEqual(port1, port2, 'ports should not be equal'); worker1.kill(); worker2.kill(); diff --git a/test/parallel/test-net-listen-shared-ports.js b/test/parallel/test-net-listen-shared-ports.js index ce344be4a6f492..e7bc036ff3986c 100644 --- a/test/parallel/test-net-listen-shared-ports.js +++ b/test/parallel/test-net-listen-shared-ports.js @@ -10,11 +10,11 @@ if (cluster.isMaster) { const worker1 = cluster.fork(); worker1.on('message', function(msg) { - assert.equal(msg, 'success'); + assert.strictEqual(msg, 'success'); const worker2 = cluster.fork(); worker2.on('message', function(msg) { - assert.equal(msg, 'server2:EADDRINUSE'); + assert.strictEqual(msg, 'server2:EADDRINUSE'); worker1.kill(); worker2.kill(); }); diff --git a/test/parallel/test-net-persistent-keepalive.js b/test/parallel/test-net-persistent-keepalive.js index 6338b5932de1fa..8756cd7d1b2960 100644 --- a/test/parallel/test-net-persistent-keepalive.js +++ b/test/parallel/test-net-persistent-keepalive.js @@ -9,14 +9,14 @@ const echoServer = net.createServer(function(connection) { serverConnection = connection; setTimeout(function() { // make sure both connections are still open - assert.equal(serverConnection.readyState, 'open'); - assert.equal(clientConnection.readyState, 'open'); + assert.strictEqual(serverConnection.readyState, 'open'); + assert.strictEqual(clientConnection.readyState, 'open'); serverConnection.end(); clientConnection.end(); echoServer.close(); }, 600); connection.setTimeout(0); - assert.equal(typeof connection.setKeepAlive, 'function'); + assert.strictEqual(typeof connection.setKeepAlive, 'function'); connection.on('end', function() { connection.end(); }); diff --git a/test/parallel/test-net-persistent-nodelay.js b/test/parallel/test-net-persistent-nodelay.js index 3f94424b0e1197..bb2a9dfd22e5cc 100644 --- a/test/parallel/test-net-persistent-nodelay.js +++ b/test/parallel/test-net-persistent-nodelay.js @@ -28,7 +28,7 @@ echoServer.on('listening', function() { assert.ok(s instanceof net.Socket); sock1.connect(this.address().port); sock1.on('end', function() { - assert.equal(callCount, 1); + assert.strictEqual(callCount, 1); echoServer.close(); }); }); diff --git a/test/parallel/test-net-persistent-ref-unref.js b/test/parallel/test-net-persistent-ref-unref.js index 1d3cbc6ffaef18..d8de7ba3f2877a 100644 --- a/test/parallel/test-net-persistent-ref-unref.js +++ b/test/parallel/test-net-persistent-ref-unref.js @@ -16,13 +16,13 @@ let refCount = 0; TCPWrap.prototype.ref = function() { ref.call(this); refCount++; - assert.equal(refCount, 0); + assert.strictEqual(refCount, 0); }; TCPWrap.prototype.unref = function() { unref.call(this); refCount--; - assert.equal(refCount, -1); + assert.strictEqual(refCount, -1); }; echoServer.listen(0); @@ -33,7 +33,7 @@ echoServer.on('listening', function() { sock.ref(); sock.connect(this.address().port); sock.on('end', function() { - assert.equal(refCount, 0); + assert.strictEqual(refCount, 0); echoServer.close(); }); }); diff --git a/test/parallel/test-net-reconnect.js b/test/parallel/test-net-reconnect.js index 47171093ca13f9..c970ad7fc5c135 100644 --- a/test/parallel/test-net-reconnect.js +++ b/test/parallel/test-net-reconnect.js @@ -23,7 +23,7 @@ const server = net.createServer(function(socket) { socket.on('close', function(had_error) { console.log('SERVER had_error: ' + JSON.stringify(had_error)); - assert.equal(false, had_error); + assert.strictEqual(false, had_error); }); }); @@ -40,7 +40,7 @@ server.listen(0, function() { client.on('data', function(chunk) { client_recv_count += 1; console.log('client_recv_count ' + client_recv_count); - assert.equal('hello\r\n', chunk); + assert.strictEqual('hello\r\n', chunk); console.error('CLIENT: calling end', client._writableState); client.end(); }); @@ -52,7 +52,7 @@ server.listen(0, function() { client.on('close', function(had_error) { console.log('CLIENT disconnect'); - assert.equal(false, had_error); + assert.strictEqual(false, had_error); if (disconnect_count++ < N) client.connect(server.address().port); // reconnect else @@ -61,7 +61,7 @@ server.listen(0, function() { }); process.on('exit', function() { - assert.equal(N + 1, disconnect_count); - assert.equal(N + 1, client_recv_count); - assert.equal(N + 1, client_end_count); + assert.strictEqual(N + 1, disconnect_count); + assert.strictEqual(N + 1, client_recv_count); + assert.strictEqual(N + 1, client_end_count); }); diff --git a/test/parallel/test-net-server-bind.js b/test/parallel/test-net-server-bind.js index e4dc64216441cf..0332b364df1ca2 100644 --- a/test/parallel/test-net-server-bind.js +++ b/test/parallel/test-net-server-bind.js @@ -70,7 +70,7 @@ server4.listen(common.PORT + 3, 127, function() { process.on('exit', function() { assert.ok(address0.port > 100); - assert.equal(common.PORT, address1.port); + assert.strictEqual(common.PORT, address1.port); let expectedConnectionKey1; @@ -79,8 +79,8 @@ process.on('exit', function() { else expectedConnectionKey1 = '4:0.0.0.0:' + address1.port; - assert.equal(connectionKey1, expectedConnectionKey1); - assert.equal(common.PORT + 1, address2.port); - assert.equal(common.PORT + 2, address3.port); - assert.equal(common.PORT + 3, address4.port); + assert.strictEqual(connectionKey1, expectedConnectionKey1); + assert.strictEqual(common.PORT + 1, address2.port); + assert.strictEqual(common.PORT + 2, address3.port); + assert.strictEqual(common.PORT + 3, address4.port); }); diff --git a/test/parallel/test-net-server-close.js b/test/parallel/test-net-server-close.js index d52cccaacfd8e6..e39f851c3906c4 100644 --- a/test/parallel/test-net-server-close.js +++ b/test/parallel/test-net-server-close.js @@ -7,12 +7,12 @@ const events = []; const sockets = []; process.on('exit', function() { - assert.equal(server.connections, 0); - assert.equal(events.length, 3); + assert.strictEqual(server.connections, 0); + assert.strictEqual(events.length, 3); // Expect to see one server event and two client events. The order of the // events is undefined because they arrive on the same event loop tick. - assert.equal(events.join(' ').match(/server/g).length, 1); - assert.equal(events.join(' ').match(/client/g).length, 2); + assert.strictEqual(events.join(' ').match(/server/g).length, 1); + assert.strictEqual(events.join(' ').match(/client/g).length, 2); }); const server = net.createServer(function(c) { diff --git a/test/parallel/test-net-server-connections.js b/test/parallel/test-net-server-connections.js index 4e41d29a505199..7ee1df1a544b95 100644 --- a/test/parallel/test-net-server-connections.js +++ b/test/parallel/test-net-server-connections.js @@ -9,4 +9,4 @@ const net = require('net'); const server = new net.Server(); -assert.equal(Object.keys(server).indexOf('connections'), -1); +assert.strictEqual(Object.keys(server).indexOf('connections'), -1); diff --git a/test/parallel/test-net-server-listen-remove-callback.js b/test/parallel/test-net-server-listen-remove-callback.js index a678922683eeb1..cd47f325a9580f 100644 --- a/test/parallel/test-net-server-listen-remove-callback.js +++ b/test/parallel/test-net-server-listen-remove-callback.js @@ -9,7 +9,7 @@ const server = net.createServer(); server.on('close', function() { const listeners = server.listeners('listening'); console.log('Closed, listeners:', listeners.length); - assert.equal(0, listeners.length); + assert.strictEqual(0, listeners.length); }); server.listen(0, function() { diff --git a/test/parallel/test-net-server-max-connections-close-makes-more-available.js b/test/parallel/test-net-server-max-connections-close-makes-more-available.js index c7fe7c74a77d37..4e1f381e0fdb50 100644 --- a/test/parallel/test-net-server-max-connections-close-makes-more-available.js +++ b/test/parallel/test-net-server-max-connections-close-makes-more-available.js @@ -29,7 +29,7 @@ const createConnection = function(index) { }); connection.on('error', function(err) { - assert.equal(err.code, 'ECONNRESET'); + assert.strictEqual(err.code, 'ECONNRESET'); resolve(); }); diff --git a/test/parallel/test-net-server-pause-on-connect.js b/test/parallel/test-net-server-pause-on-connect.js index ee5ac4e2807b0a..5b42876e6d652e 100644 --- a/test/parallel/test-net-server-pause-on-connect.js +++ b/test/parallel/test-net-server-pause-on-connect.js @@ -13,7 +13,7 @@ const server1ConnHandler = function(socket) { common.fail('data event should not have happened yet'); } - assert.equal(data.toString(), msg, 'invalid data received'); + assert.strictEqual(data.toString(), msg, 'invalid data received'); socket.end(); server1.close(); }); @@ -25,11 +25,12 @@ const server1 = net.createServer({pauseOnConnect: true}, server1ConnHandler); const server2ConnHandler = function(socket) { socket.on('data', function(data) { - assert.equal(data.toString(), msg, 'invalid data received'); + assert.strictEqual(data.toString(), msg, 'invalid data received'); socket.end(); server2.close(); - assert.equal(server1Sock.bytesRead, 0, 'no data should have been read yet'); + assert.strictEqual(server1Sock.bytesRead, 0, + 'no data should have been read yet'); server1Sock.resume(); stopped = false; }); @@ -47,5 +48,5 @@ server1.listen(0, function() { }); process.on('exit', function() { - assert.equal(stopped, false); + assert.strictEqual(stopped, false); }); diff --git a/test/parallel/test-net-stream.js b/test/parallel/test-net-stream.js index 9d091bd66f3a1e..9e1ca670e1e145 100644 --- a/test/parallel/test-net-stream.js +++ b/test/parallel/test-net-stream.js @@ -12,11 +12,11 @@ s.server = new net.Server(); s.server.connections = 10; s._server = s.server; -assert.equal(10, s.server.connections); +assert.strictEqual(10, s.server.connections); s.destroy(); -assert.equal(9, s.server.connections); +assert.strictEqual(9, s.server.connections); s.destroy(); -assert.equal(9, s.server.connections); +assert.strictEqual(9, s.server.connections); const SIZE = 2E6; const N = 10; @@ -47,5 +47,5 @@ const server = net.createServer(function(socket) { }); process.on('exit', function() { - assert.equal(server.connections, 0); + assert.strictEqual(server.connections, 0); }); diff --git a/test/parallel/test-net-sync-cork.js b/test/parallel/test-net-sync-cork.js index 4dff309cb97816..3872f5f96944fc 100644 --- a/test/parallel/test-net-sync-cork.js +++ b/test/parallel/test-net-sync-cork.js @@ -21,13 +21,13 @@ server.listen(0, function() { res = conn.write(buf); conn.uncork(); } - assert.equal(i, N); + assert.strictEqual(i, N); conn.end(); }); }); process.on('exit', function() { - assert.equal(server.connections, 0); + assert.strictEqual(server.connections, 0); }); function handle(socket) { diff --git a/test/parallel/test-next-tick-ordering.js b/test/parallel/test-next-tick-ordering.js index 2f13147d8ed733..ea019facdd8fa0 100644 --- a/test/parallel/test-next-tick-ordering.js +++ b/test/parallel/test-next-tick-ordering.js @@ -26,10 +26,10 @@ console.log('Running from main.'); process.on('exit', function() { - assert.equal('nextTick', done[0]); + assert.strictEqual('nextTick', done[0]); /* Disabling this test. I don't think we can ensure the order for (i = 0; i < N; i += 1) { - assert.equal(i, done[i + 1]); + assert.strictEqual(i, done[i + 1]); } */ }); diff --git a/test/parallel/test-next-tick.js b/test/parallel/test-next-tick.js index 3001ad0e561a77..9d2b1917fae2f7 100644 --- a/test/parallel/test-next-tick.js +++ b/test/parallel/test-next-tick.js @@ -17,8 +17,8 @@ process.nextTick(common.mustCall(function() {})); const obj = {}; process.nextTick(function(a, b) { - assert.equal(a, 42); - assert.equal(b, obj); + assert.strictEqual(a, 42); + assert.strictEqual(b, obj); }, 42, obj); process.on('exit', function() { diff --git a/test/parallel/test-npm-install.js b/test/parallel/test-npm-install.js index c7f216fce5f2fa..00a3504fa925ae 100644 --- a/test/parallel/test-npm-install.js +++ b/test/parallel/test-npm-install.js @@ -53,7 +53,7 @@ const proc = spawn(process.execPath, args, { }); function handleExit(code, signalCode) { - assert.equal(code, 0, 'npm install should run without an error'); + assert.strictEqual(code, 0, 'npm install should run without an error'); assert.ok(signalCode === null, 'signalCode should be null'); assert.doesNotThrow(function() { fs.accessSync(installDir + '/node_modules/package-name'); diff --git a/test/parallel/test-os-homedir-no-envvar.js b/test/parallel/test-os-homedir-no-envvar.js index 94d8ab5a08fa14..2f9b1b47a70477 100644 --- a/test/parallel/test-os-homedir-no-envvar.js +++ b/test/parallel/test-os-homedir-no-envvar.js @@ -26,5 +26,5 @@ if (process.argv[2] === 'child') { env: process.env }); - assert.equal(child.status, 0); + assert.strictEqual(child.status, 0); } diff --git a/test/parallel/test-path-makelong.js b/test/parallel/test-path-makelong.js index 293d6284f173bc..1284f625160ebe 100644 --- a/test/parallel/test-path-makelong.js +++ b/test/parallel/test-path-makelong.js @@ -7,18 +7,19 @@ if (common.isWindows) { const file = path.join(common.fixturesDir, 'a.js'); const resolvedFile = path.resolve(file); - assert.equal('\\\\?\\' + resolvedFile, path._makeLong(file)); - assert.equal('\\\\?\\' + resolvedFile, path._makeLong('\\\\?\\' + file)); - assert.equal('\\\\?\\UNC\\someserver\\someshare\\somefile', - path._makeLong('\\\\someserver\\someshare\\somefile')); - assert.equal('\\\\?\\UNC\\someserver\\someshare\\somefile', - path._makeLong('\\\\?\\UNC\\someserver\\someshare\\somefile')); - assert.equal('\\\\.\\pipe\\somepipe', - path._makeLong('\\\\.\\pipe\\somepipe')); + assert.strictEqual('\\\\?\\' + resolvedFile, path._makeLong(file)); + assert.strictEqual('\\\\?\\' + resolvedFile, path._makeLong('\\\\?\\' + + file)); + assert.strictEqual('\\\\?\\UNC\\someserver\\someshare\\somefile', + path._makeLong('\\\\someserver\\someshare\\somefile')); + assert.strictEqual('\\\\?\\UNC\\someserver\\someshare\\somefile', path + ._makeLong('\\\\?\\UNC\\someserver\\someshare\\somefile')); + assert.strictEqual('\\\\.\\pipe\\somepipe', + path._makeLong('\\\\.\\pipe\\somepipe')); } -assert.equal(path._makeLong(null), null); -assert.equal(path._makeLong(100), 100); -assert.equal(path._makeLong(path), path); -assert.equal(path._makeLong(false), false); -assert.equal(path._makeLong(true), true); +assert.strictEqual(path._makeLong(null), null); +assert.strictEqual(path._makeLong(100), 100); +assert.strictEqual(path._makeLong(path), path); +assert.strictEqual(path._makeLong(false), false); +assert.strictEqual(path._makeLong(true), true); diff --git a/test/parallel/test-path-parse-format.js b/test/parallel/test-path-parse-format.js index f112bc0e4067cd..ac0cf62117f09d 100644 --- a/test/parallel/test-path-parse-format.js +++ b/test/parallel/test-path-parse-format.js @@ -154,7 +154,7 @@ trailingTests.forEach(function(test) { failures.push('\n' + message); }); }); -assert.equal(failures.length, 0, failures.join('')); +assert.strictEqual(failures.length, 0, failures.join('')); function checkErrors(path) { errors.forEach(function(errorCase) { diff --git a/test/parallel/test-path-zero-length-strings.js b/test/parallel/test-path-zero-length-strings.js index b08ef4809201eb..ec9585fafaa169 100644 --- a/test/parallel/test-path-zero-length-strings.js +++ b/test/parallel/test-path-zero-length-strings.js @@ -12,28 +12,28 @@ const pwd = process.cwd(); // join will internally ignore all the zero-length strings and it will return // '.' if the joined string is a zero-length string. -assert.equal(path.posix.join(''), '.'); -assert.equal(path.posix.join('', ''), '.'); -assert.equal(path.win32.join(''), '.'); -assert.equal(path.win32.join('', ''), '.'); -assert.equal(path.join(pwd), pwd); -assert.equal(path.join(pwd, ''), pwd); +assert.strictEqual(path.posix.join(''), '.'); +assert.strictEqual(path.posix.join('', ''), '.'); +assert.strictEqual(path.win32.join(''), '.'); +assert.strictEqual(path.win32.join('', ''), '.'); +assert.strictEqual(path.join(pwd), pwd); +assert.strictEqual(path.join(pwd, ''), pwd); // normalize will return '.' if the input is a zero-length string -assert.equal(path.posix.normalize(''), '.'); -assert.equal(path.win32.normalize(''), '.'); -assert.equal(path.normalize(pwd), pwd); +assert.strictEqual(path.posix.normalize(''), '.'); +assert.strictEqual(path.win32.normalize(''), '.'); +assert.strictEqual(path.normalize(pwd), pwd); // Since '' is not a valid path in any of the common environments, return false -assert.equal(path.posix.isAbsolute(''), false); -assert.equal(path.win32.isAbsolute(''), false); +assert.strictEqual(path.posix.isAbsolute(''), false); +assert.strictEqual(path.win32.isAbsolute(''), false); // resolve, internally ignores all the zero-length strings and returns the // current working directory -assert.equal(path.resolve(''), pwd); -assert.equal(path.resolve('', ''), pwd); +assert.strictEqual(path.resolve(''), pwd); +assert.strictEqual(path.resolve('', ''), pwd); // relative, internally calls resolve. So, '' is actually the current directory -assert.equal(path.relative('', pwd), ''); -assert.equal(path.relative(pwd, ''), ''); -assert.equal(path.relative(pwd, pwd), ''); +assert.strictEqual(path.relative('', pwd), ''); +assert.strictEqual(path.relative(pwd, ''), ''); +assert.strictEqual(path.relative(pwd, pwd), ''); diff --git a/test/parallel/test-path.js b/test/parallel/test-path.js index 3843088ebdc14b..b074e83c131a24 100644 --- a/test/parallel/test-path.js +++ b/test/parallel/test-path.js @@ -453,7 +453,7 @@ if (common.isWindows) { const spawnResult = child.spawnSync( process.argv[0], [resolveFixture, currentDriveLetter]); const resolvedPath = spawnResult.stdout.toString().trim(); - assert.equal(resolvedPath.toLowerCase(), process.cwd().toLowerCase()); + assert.strictEqual(resolvedPath.toLowerCase(), process.cwd().toLowerCase()); } diff --git a/test/parallel/test-pipe-stream.js b/test/parallel/test-pipe-stream.js index 5e3774fc99d535..8fd9d31d499089 100644 --- a/test/parallel/test-pipe-stream.js +++ b/test/parallel/test-pipe-stream.js @@ -26,7 +26,7 @@ function test(clazz, cb) { }); conn.on('data', function(data) { - assert.equal(data.toString(), 'PONG'); + assert.strictEqual(data.toString(), 'PONG'); have_pong = true; conn.destroy(); }); @@ -38,7 +38,7 @@ function test(clazz, cb) { }); conn.on('data', function(data) { - assert.equal(data.toString(), 'PING'); + assert.strictEqual(data.toString(), 'PING'); have_ping = true; conn.write('PONG', 'utf-8'); }); diff --git a/test/parallel/test-process-argv-0.js b/test/parallel/test-process-argv-0.js index d6b4bfe232323e..8e4f0e695ec6a1 100644 --- a/test/parallel/test-process-argv-0.js +++ b/test/parallel/test-process-argv-0.js @@ -14,7 +14,7 @@ if (process.argv[2] !== 'child') { childArgv0 += chunk; }); process.on('exit', function() { - assert.equal(childArgv0, process.execPath); + assert.strictEqual(childArgv0, process.execPath); }); } else { process.stdout.write(process.argv[0]); diff --git a/test/parallel/test-process-env.js b/test/parallel/test-process-env.js index 21898d19425ca3..5ea0a4a57efc68 100644 --- a/test/parallel/test-process-env.js +++ b/test/parallel/test-process-env.js @@ -63,8 +63,8 @@ process.env.TZ = 'Europe/Amsterdam'; // time difference between Greenwich and Amsterdam is +2 hours in the summer date = new Date('Fri, 10 Sep 1982 03:15:00 GMT'); -assert.equal(3, date.getUTCHours()); -assert.equal(5, date.getHours()); +assert.strictEqual(3, date.getUTCHours()); +assert.strictEqual(5, date.getHours()); */ /* eslint-enable max-len */ diff --git a/test/parallel/test-process-exit-code.js b/test/parallel/test-process-exit-code.js index 337502ffcb30e8..8d0ed1b33bae76 100644 --- a/test/parallel/test-process-exit-code.js +++ b/test/parallel/test-process-exit-code.js @@ -22,14 +22,14 @@ switch (process.argv[2]) { function child1() { process.exitCode = 42; process.on('exit', function(code) { - assert.equal(code, 42); + assert.strictEqual(code, 42); }); } function child2() { process.exitCode = 99; process.on('exit', function(code) { - assert.equal(code, 42); + assert.strictEqual(code, 42); }); process.exit(42); } @@ -37,7 +37,7 @@ function child2() { function child3() { process.exitCode = 99; process.on('exit', function(code) { - assert.equal(code, 0); + assert.strictEqual(code, 0); }); process.exit(0); } @@ -56,7 +56,7 @@ function child4() { function child5() { process.exitCode = 95; process.on('exit', function(code) { - assert.equal(code, 95); + assert.strictEqual(code, 95); process.exitCode = 99; }); } @@ -75,7 +75,7 @@ function test(arg, exit) { const f = __filename; const option = { stdio: [ 0, 1, 'ignore' ] }; spawn(node, [f, arg], option).on('exit', function(code) { - assert.equal(code, exit, 'wrong exit for ' + + assert.strictEqual(code, exit, 'wrong exit for ' + arg + '\nexpected:' + exit + ' but got:' + code); console.log('ok - %s exited with %d', arg, exit); diff --git a/test/parallel/test-process-exit-recursive.js b/test/parallel/test-process-exit-recursive.js index 1634aad15497f5..48ad8259168a90 100644 --- a/test/parallel/test-process-exit-recursive.js +++ b/test/parallel/test-process-exit-recursive.js @@ -6,8 +6,8 @@ const assert = require('assert'); let nexits = 0; process.on('exit', function(code) { - assert.equal(nexits++, 0); - assert.equal(code, 1); + assert.strictEqual(nexits++, 0); + assert.strictEqual(code, 1); // now override the exit code of 1 with 0 so that the test passes process.exit(0); diff --git a/test/parallel/test-process-exit.js b/test/parallel/test-process-exit.js index f7df7737ed1531..a4ea2bf51b53f5 100644 --- a/test/parallel/test-process-exit.js +++ b/test/parallel/test-process-exit.js @@ -6,8 +6,8 @@ const assert = require('assert'); let nexits = 0; process.on('exit', function(code) { - assert.equal(nexits++, 0); - assert.equal(code, 0); + assert.strictEqual(nexits++, 0); + assert.strictEqual(code, 0); process.exit(); }); diff --git a/test/parallel/test-process-getactiverequests.js b/test/parallel/test-process-getactiverequests.js index 30773f8f11380a..f1874e4ad09a86 100644 --- a/test/parallel/test-process-getactiverequests.js +++ b/test/parallel/test-process-getactiverequests.js @@ -7,4 +7,4 @@ const fs = require('fs'); for (let i = 0; i < 12; i++) fs.open(__filename, 'r', function() { }); -assert.equal(12, process._getActiveRequests().length); +assert.strictEqual(12, process._getActiveRequests().length); diff --git a/test/parallel/test-process-getgroups.js b/test/parallel/test-process-getgroups.js index e92f04853976f7..2d7a93c9a32c75 100644 --- a/test/parallel/test-process-getgroups.js +++ b/test/parallel/test-process-getgroups.js @@ -15,7 +15,7 @@ if (typeof process.getgroups === 'function') { exec('id -G', function(err, stdout) { assert.ifError(err); const real_groups = stdout.match(/\d+/g).map(Number); - assert.equal(groups.length, real_groups.length); + assert.strictEqual(groups.length, real_groups.length); check(groups, real_groups); check(real_groups, groups); }); diff --git a/test/parallel/test-process-kill-pid.js b/test/parallel/test-process-kill-pid.js index 2c6ef37fc120df..79dc00163b78f8 100644 --- a/test/parallel/test-process-kill-pid.js +++ b/test/parallel/test-process-kill-pid.js @@ -47,8 +47,8 @@ function kill(tryPid, trySig, expectPid, expectSig) { process.kill(tryPid, trySig); - assert.equal(getPid, expectPid); - assert.equal(getSig, expectSig); + assert.strictEqual(getPid.toString(), expectPid.toString()); + assert.strictEqual(getSig, expectSig); } // Note that SIGHUP and SIGTERM map to 1 and 15 respectively, even on Windows diff --git a/test/parallel/test-process-raw-debug.js b/test/parallel/test-process-raw-debug.js index 74c99b1f8f8058..dc31c3737ae1cb 100644 --- a/test/parallel/test-process-raw-debug.js +++ b/test/parallel/test-process-raw-debug.js @@ -25,7 +25,7 @@ function parent() { child.stderr.setEncoding('utf8'); child.stderr.on('end', function() { - assert.equal(output, 'I can still debug!' + os.EOL); + assert.strictEqual(output, 'I can still debug!' + os.EOL); console.log('ok - got expected message'); }); diff --git a/test/parallel/test-process-remove-all-signal-listeners.js b/test/parallel/test-process-remove-all-signal-listeners.js index 76a96f7683e452..85db45ff88c7c8 100644 --- a/test/parallel/test-process-remove-all-signal-listeners.js +++ b/test/parallel/test-process-remove-all-signal-listeners.js @@ -17,7 +17,7 @@ if (process.argv[2] !== '--do-test') { const child = spawn(process.execPath, [__filename, '--do-test']); child.once('exit', common.mustCall(function(code, signal) { - assert.equal(signal, 'SIGINT'); + assert.strictEqual(signal, 'SIGINT'); })); return; diff --git a/test/parallel/test-process-wrap.js b/test/parallel/test-process-wrap.js index 326854e98335df..fee40a84167023 100644 --- a/test/parallel/test-process-wrap.js +++ b/test/parallel/test-process-wrap.js @@ -15,8 +15,8 @@ p.onexit = function(exitCode, signal) { p.close(); pipe.readStart(); - assert.equal(0, exitCode); - assert.equal(0, signal); + assert.strictEqual(0, exitCode); + assert.strictEqual('', signal); processExited = true; }; diff --git a/test/parallel/test-promises-unhandled-rejections.js b/test/parallel/test-promises-unhandled-rejections.js index 27cb94bf704eb4..6ae70fef97a489 100644 --- a/test/parallel/test-promises-unhandled-rejections.js +++ b/test/parallel/test-promises-unhandled-rejections.js @@ -669,7 +669,7 @@ asyncTest('Throwing an error inside a rejectionHandled handler goes to' + const e = new Error(); const e2 = new Error(); const tearDownException = setupException(function(err) { - assert.equal(e2, err); + assert.strictEqual(e2, err); tearDownException(); done(); }); diff --git a/test/parallel/test-querystring-maxKeys-non-finite.js b/test/parallel/test-querystring-maxKeys-non-finite.js index 8aa47f7de0e2dc..3df381405d650a 100644 --- a/test/parallel/test-querystring-maxKeys-non-finite.js +++ b/test/parallel/test-querystring-maxKeys-non-finite.js @@ -47,9 +47,9 @@ const resultInfinityString = parse(params, undefined, undefined, { const resultNaNString = parse(params, undefined, undefined, {maxKeys: 'NaN'}); // Non Finite maxKeys should return the length of input -assert.equal(Object.keys(resultInfinity).length, count); -assert.equal(Object.keys(resultNaN).length, count); +assert.strictEqual(Object.keys(resultInfinity).length, count); +assert.strictEqual(Object.keys(resultNaN).length, count); // Strings maxKeys should return the maxLength // defined by parses internals -assert.equal(Object.keys(resultInfinityString).length, originalMaxLength); -assert.equal(Object.keys(resultNaNString).length, originalMaxLength); +assert.strictEqual(Object.keys(resultInfinityString).length, originalMaxLength); +assert.strictEqual(Object.keys(resultNaNString).length, originalMaxLength); diff --git a/test/parallel/test-querystring.js b/test/parallel/test-querystring.js index 8cc589944b0508..89c880c7e0e3ce 100644 --- a/test/parallel/test-querystring.js +++ b/test/parallel/test-querystring.js @@ -168,15 +168,15 @@ qsNoMungeTestCases.forEach(function(testCase) { // basic qsTestCases.forEach(function(testCase) { - assert.equal(testCase[1], qs.stringify(testCase[2])); + assert.strictEqual(testCase[1], qs.stringify(testCase[2])); }); qsColonTestCases.forEach(function(testCase) { - assert.equal(testCase[1], qs.stringify(testCase[2], ';', ':')); + assert.strictEqual(testCase[1], qs.stringify(testCase[2], ';', ':')); }); qsWeirdObjects.forEach(function(testCase) { - assert.equal(testCase[1], qs.stringify(testCase[0])); + assert.strictEqual(testCase[1], qs.stringify(testCase[0])); }); // invalid surrogate pair throws URIError @@ -201,7 +201,7 @@ assert.strictEqual('foo=', qs.stringify({ foo: Infinity })); y: 'z' }) }); - assert.equal(f, 'a=b&q=x%3Dy%26y%3Dz'); + assert.strictEqual(f, 'a=b&q=x%3Dy%26y%3Dz'); } assert.doesNotThrow(function() { @@ -217,14 +217,14 @@ assert.doesNotThrow(function() { y: 'z' }, ';', ':') }, ';', ':'); - assert.equal(f, 'a:b;q:x%3Ay%3By%3Az'); + assert.strictEqual(f, 'a:b;q:x%3Ay%3By%3Az'); } check(qs.parse(), {}); // Test limiting -assert.equal( +assert.strictEqual( Object.keys(qs.parse('a=1&b=1&c=1', null, null, { maxKeys: 1 })).length, 1); @@ -236,7 +236,7 @@ function testUnlimitedKeys() { const url = qs.stringify(query); - assert.equal( + assert.strictEqual( Object.keys(qs.parse(url, null, null, { maxKeys: 0 })).length, 2000); } @@ -246,26 +246,26 @@ testUnlimitedKeys(); const b = qs.unescapeBuffer('%d3%f2Ug%1f6v%24%5e%98%cb' + '%0d%ac%a2%2f%9d%eb%d8%a2%e6'); // -assert.equal(0xd3, b[0]); -assert.equal(0xf2, b[1]); -assert.equal(0x55, b[2]); -assert.equal(0x67, b[3]); -assert.equal(0x1f, b[4]); -assert.equal(0x36, b[5]); -assert.equal(0x76, b[6]); -assert.equal(0x24, b[7]); -assert.equal(0x5e, b[8]); -assert.equal(0x98, b[9]); -assert.equal(0xcb, b[10]); -assert.equal(0x0d, b[11]); -assert.equal(0xac, b[12]); -assert.equal(0xa2, b[13]); -assert.equal(0x2f, b[14]); -assert.equal(0x9d, b[15]); -assert.equal(0xeb, b[16]); -assert.equal(0xd8, b[17]); -assert.equal(0xa2, b[18]); -assert.equal(0xe6, b[19]); +assert.strictEqual(0xd3, b[0]); +assert.strictEqual(0xf2, b[1]); +assert.strictEqual(0x55, b[2]); +assert.strictEqual(0x67, b[3]); +assert.strictEqual(0x1f, b[4]); +assert.strictEqual(0x36, b[5]); +assert.strictEqual(0x76, b[6]); +assert.strictEqual(0x24, b[7]); +assert.strictEqual(0x5e, b[8]); +assert.strictEqual(0x98, b[9]); +assert.strictEqual(0xcb, b[10]); +assert.strictEqual(0x0d, b[11]); +assert.strictEqual(0xac, b[12]); +assert.strictEqual(0xa2, b[13]); +assert.strictEqual(0x2f, b[14]); +assert.strictEqual(0x9d, b[15]); +assert.strictEqual(0xeb, b[16]); +assert.strictEqual(0xd8, b[17]); +assert.strictEqual(0xa2, b[18]); +assert.strictEqual(0xe6, b[19]); // Test custom decode @@ -281,7 +281,7 @@ function demoEncode(str) { return str[0]; } const obj = { aa: 'aa', bb: 'bb', cc: 'cc' }; -assert.equal( +assert.strictEqual( qs.stringify(obj, null, null, { encodeURIComponent: demoEncode }), 'a=a&b=b&c=c'); diff --git a/test/parallel/test-readdouble.js b/test/parallel/test-readdouble.js index 728a2b4605d9ff..00340a39e631c0 100644 --- a/test/parallel/test-readdouble.js +++ b/test/parallel/test-readdouble.js @@ -19,8 +19,8 @@ function test(clazz) { buffer[5] = 0x55; buffer[6] = 0xd5; buffer[7] = 0x3f; - assert.equal(1.1945305291680097e+103, buffer.readDoubleBE(0)); - assert.equal(0.3333333333333333, buffer.readDoubleLE(0)); + assert.strictEqual(1.1945305291680097e+103, buffer.readDoubleBE(0)); + assert.strictEqual(0.3333333333333333, buffer.readDoubleLE(0)); buffer[0] = 1; buffer[1] = 0; @@ -30,18 +30,18 @@ function test(clazz) { buffer[5] = 0; buffer[6] = 0xf0; buffer[7] = 0x3f; - assert.equal(7.291122019655968e-304, buffer.readDoubleBE(0)); - assert.equal(1.0000000000000002, buffer.readDoubleLE(0)); + assert.strictEqual(7.291122019655968e-304, buffer.readDoubleBE(0)); + assert.strictEqual(1.0000000000000002, buffer.readDoubleLE(0)); buffer[0] = 2; - assert.equal(4.778309726801735e-299, buffer.readDoubleBE(0)); - assert.equal(1.0000000000000004, buffer.readDoubleLE(0)); + assert.strictEqual(4.778309726801735e-299, buffer.readDoubleBE(0)); + assert.strictEqual(1.0000000000000004, buffer.readDoubleLE(0)); buffer[0] = 1; buffer[6] = 0; buffer[7] = 0; - assert.equal(7.291122019556398e-304, buffer.readDoubleBE(0)); - assert.equal(5e-324, buffer.readDoubleLE(0)); + assert.strictEqual(7.291122019556398e-304, buffer.readDoubleBE(0)); + assert.strictEqual(5e-324, buffer.readDoubleLE(0)); buffer[0] = 0xff; buffer[1] = 0xff; @@ -52,12 +52,12 @@ function test(clazz) { buffer[6] = 0x0f; buffer[7] = 0x00; assert.ok(isNaN(buffer.readDoubleBE(0))); - assert.equal(2.225073858507201e-308, buffer.readDoubleLE(0)); + assert.strictEqual(2.225073858507201e-308, buffer.readDoubleLE(0)); buffer[6] = 0xef; buffer[7] = 0x7f; assert.ok(isNaN(buffer.readDoubleBE(0))); - assert.equal(1.7976931348623157e+308, buffer.readDoubleLE(0)); + assert.strictEqual(1.7976931348623157e+308, buffer.readDoubleLE(0)); buffer[0] = 0; buffer[1] = 0; @@ -67,42 +67,42 @@ function test(clazz) { buffer[5] = 0; buffer[6] = 0xf0; buffer[7] = 0x3f; - assert.equal(3.03865e-319, buffer.readDoubleBE(0)); - assert.equal(1, buffer.readDoubleLE(0)); + assert.strictEqual(3.03865e-319, buffer.readDoubleBE(0)); + assert.strictEqual(1, buffer.readDoubleLE(0)); buffer[6] = 0; buffer[7] = 0x40; - assert.equal(3.16e-322, buffer.readDoubleBE(0)); - assert.equal(2, buffer.readDoubleLE(0)); + assert.strictEqual(3.16e-322, buffer.readDoubleBE(0)); + assert.strictEqual(2, buffer.readDoubleLE(0)); buffer[7] = 0xc0; - assert.equal(9.5e-322, buffer.readDoubleBE(0)); - assert.equal(-2, buffer.readDoubleLE(0)); + assert.strictEqual(9.5e-322, buffer.readDoubleBE(0)); + assert.strictEqual(-2, buffer.readDoubleLE(0)); buffer[6] = 0x10; buffer[7] = 0; - assert.equal(2.0237e-320, buffer.readDoubleBE(0)); - assert.equal(2.2250738585072014e-308, buffer.readDoubleLE(0)); + assert.strictEqual(2.0237e-320, buffer.readDoubleBE(0)); + assert.strictEqual(2.2250738585072014e-308, buffer.readDoubleLE(0)); buffer[6] = 0; - assert.equal(0, buffer.readDoubleBE(0)); - assert.equal(0, buffer.readDoubleLE(0)); - assert.equal(false, 1 / buffer.readDoubleLE(0) < 0); + assert.strictEqual(0, buffer.readDoubleBE(0)); + assert.strictEqual(0, buffer.readDoubleLE(0)); + assert.strictEqual(false, 1 / buffer.readDoubleLE(0) < 0); buffer[7] = 0x80; - assert.equal(6.3e-322, buffer.readDoubleBE(0)); - assert.equal(0, buffer.readDoubleLE(0)); - assert.equal(true, 1 / buffer.readDoubleLE(0) < 0); + assert.strictEqual(6.3e-322, buffer.readDoubleBE(0)); + assert.strictEqual(0, buffer.readDoubleLE(0)); + assert.strictEqual(true, 1 / buffer.readDoubleLE(0) < 0); buffer[6] = 0xf0; buffer[7] = 0x7f; - assert.equal(3.0418e-319, buffer.readDoubleBE(0)); - assert.equal(Infinity, buffer.readDoubleLE(0)); + assert.strictEqual(3.0418e-319, buffer.readDoubleBE(0)); + assert.strictEqual(Infinity, buffer.readDoubleLE(0)); buffer[6] = 0xf0; buffer[7] = 0xff; - assert.equal(3.04814e-319, buffer.readDoubleBE(0)); - assert.equal(-Infinity, buffer.readDoubleLE(0)); + assert.strictEqual(3.04814e-319, buffer.readDoubleBE(0)); + assert.strictEqual(-Infinity, buffer.readDoubleLE(0)); } diff --git a/test/parallel/test-readfloat.js b/test/parallel/test-readfloat.js index 437e4778671bd2..0175c195b8ec22 100644 --- a/test/parallel/test-readfloat.js +++ b/test/parallel/test-readfloat.js @@ -15,56 +15,56 @@ function test(clazz) { buffer[1] = 0; buffer[2] = 0x80; buffer[3] = 0x3f; - assert.equal(4.600602988224807e-41, buffer.readFloatBE(0)); - assert.equal(1, buffer.readFloatLE(0)); + assert.strictEqual(4.600602988224807e-41, buffer.readFloatBE(0)); + assert.strictEqual(1, buffer.readFloatLE(0)); buffer[0] = 0; buffer[1] = 0; buffer[2] = 0; buffer[3] = 0xc0; - assert.equal(2.6904930515036488e-43, buffer.readFloatBE(0)); - assert.equal(-2, buffer.readFloatLE(0)); + assert.strictEqual(2.6904930515036488e-43, buffer.readFloatBE(0)); + assert.strictEqual(-2, buffer.readFloatLE(0)); buffer[0] = 0xff; buffer[1] = 0xff; buffer[2] = 0x7f; buffer[3] = 0x7f; assert.ok(isNaN(buffer.readFloatBE(0))); - assert.equal(3.4028234663852886e+38, buffer.readFloatLE(0)); + assert.strictEqual(3.4028234663852886e+38, buffer.readFloatLE(0)); buffer[0] = 0xab; buffer[1] = 0xaa; buffer[2] = 0xaa; buffer[3] = 0x3e; - assert.equal(-1.2126478207002966e-12, buffer.readFloatBE(0)); - assert.equal(0.3333333432674408, buffer.readFloatLE(0)); + assert.strictEqual(-1.2126478207002966e-12, buffer.readFloatBE(0)); + assert.strictEqual(0.3333333432674408, buffer.readFloatLE(0)); buffer[0] = 0; buffer[1] = 0; buffer[2] = 0; buffer[3] = 0; - assert.equal(0, buffer.readFloatBE(0)); - assert.equal(0, buffer.readFloatLE(0)); - assert.equal(false, 1 / buffer.readFloatLE(0) < 0); + assert.strictEqual(0, buffer.readFloatBE(0)); + assert.strictEqual(0, buffer.readFloatLE(0)); + assert.strictEqual(false, 1 / buffer.readFloatLE(0) < 0); buffer[3] = 0x80; - assert.equal(1.793662034335766e-43, buffer.readFloatBE(0)); - assert.equal(0, buffer.readFloatLE(0)); - assert.equal(true, 1 / buffer.readFloatLE(0) < 0); + assert.strictEqual(1.793662034335766e-43, buffer.readFloatBE(0)); + assert.strictEqual(0, buffer.readFloatLE(0)); + assert.strictEqual(true, 1 / buffer.readFloatLE(0) < 0); buffer[0] = 0; buffer[1] = 0; buffer[2] = 0x80; buffer[3] = 0x7f; - assert.equal(4.609571298396486e-41, buffer.readFloatBE(0)); - assert.equal(Infinity, buffer.readFloatLE(0)); + assert.strictEqual(4.609571298396486e-41, buffer.readFloatBE(0)); + assert.strictEqual(Infinity, buffer.readFloatLE(0)); buffer[0] = 0; buffer[1] = 0; buffer[2] = 0x80; buffer[3] = 0xff; - assert.equal(4.627507918739843e-41, buffer.readFloatBE(0)); - assert.equal(-Infinity, buffer.readFloatLE(0)); + assert.strictEqual(4.627507918739843e-41, buffer.readFloatBE(0)); + assert.strictEqual(-Infinity, buffer.readFloatLE(0)); } diff --git a/test/parallel/test-readint.js b/test/parallel/test-readint.js index 086dd4e3aa0d1a..97faa1e7d58d77 100644 --- a/test/parallel/test-readint.js +++ b/test/parallel/test-readint.js @@ -12,19 +12,19 @@ function test8(clazz) { const data = new clazz(4); data[0] = 0x23; - assert.equal(0x23, data.readInt8(0)); + assert.strictEqual(0x23, data.readInt8(0)); data[0] = 0xff; - assert.equal(-1, data.readInt8(0)); + assert.strictEqual(-1, data.readInt8(0)); data[0] = 0x87; data[1] = 0xab; data[2] = 0x7c; data[3] = 0xef; - assert.equal(-121, data.readInt8(0)); - assert.equal(-85, data.readInt8(1)); - assert.equal(124, data.readInt8(2)); - assert.equal(-17, data.readInt8(3)); + assert.strictEqual(-121, data.readInt8(0)); + assert.strictEqual(-85, data.readInt8(1)); + assert.strictEqual(124, data.readInt8(2)); + assert.strictEqual(-17, data.readInt8(3)); } @@ -33,13 +33,13 @@ function test16(clazz) { buffer[0] = 0x16; buffer[1] = 0x79; - assert.equal(0x1679, buffer.readInt16BE(0)); - assert.equal(0x7916, buffer.readInt16LE(0)); + assert.strictEqual(0x1679, buffer.readInt16BE(0)); + assert.strictEqual(0x7916, buffer.readInt16LE(0)); buffer[0] = 0xff; buffer[1] = 0x80; - assert.equal(-128, buffer.readInt16BE(0)); - assert.equal(-32513, buffer.readInt16LE(0)); + assert.strictEqual(-128, buffer.readInt16BE(0)); + assert.strictEqual(-32513, buffer.readInt16LE(0)); /* test offset with weenix */ buffer[0] = 0x77; @@ -48,16 +48,16 @@ function test16(clazz) { buffer[3] = 0x6e; buffer[4] = 0x69; buffer[5] = 0x78; - assert.equal(0x7765, buffer.readInt16BE(0)); - assert.equal(0x6565, buffer.readInt16BE(1)); - assert.equal(0x656e, buffer.readInt16BE(2)); - assert.equal(0x6e69, buffer.readInt16BE(3)); - assert.equal(0x6978, buffer.readInt16BE(4)); - assert.equal(0x6577, buffer.readInt16LE(0)); - assert.equal(0x6565, buffer.readInt16LE(1)); - assert.equal(0x6e65, buffer.readInt16LE(2)); - assert.equal(0x696e, buffer.readInt16LE(3)); - assert.equal(0x7869, buffer.readInt16LE(4)); + assert.strictEqual(0x7765, buffer.readInt16BE(0)); + assert.strictEqual(0x6565, buffer.readInt16BE(1)); + assert.strictEqual(0x656e, buffer.readInt16BE(2)); + assert.strictEqual(0x6e69, buffer.readInt16BE(3)); + assert.strictEqual(0x6978, buffer.readInt16BE(4)); + assert.strictEqual(0x6577, buffer.readInt16LE(0)); + assert.strictEqual(0x6565, buffer.readInt16LE(1)); + assert.strictEqual(0x6e65, buffer.readInt16LE(2)); + assert.strictEqual(0x696e, buffer.readInt16LE(3)); + assert.strictEqual(0x7869, buffer.readInt16LE(4)); } @@ -68,15 +68,15 @@ function test32(clazz) { buffer[1] = 0x53; buffer[2] = 0x16; buffer[3] = 0x79; - assert.equal(0x43531679, buffer.readInt32BE(0)); - assert.equal(0x79165343, buffer.readInt32LE(0)); + assert.strictEqual(0x43531679, buffer.readInt32BE(0)); + assert.strictEqual(0x79165343, buffer.readInt32LE(0)); buffer[0] = 0xff; buffer[1] = 0xfe; buffer[2] = 0xef; buffer[3] = 0xfa; - assert.equal(-69638, buffer.readInt32BE(0)); - assert.equal(-84934913, buffer.readInt32LE(0)); + assert.strictEqual(-69638, buffer.readInt32BE(0)); + assert.strictEqual(-84934913, buffer.readInt32LE(0)); buffer[0] = 0x42; buffer[1] = 0xc3; @@ -84,12 +84,12 @@ function test32(clazz) { buffer[3] = 0xa9; buffer[4] = 0x36; buffer[5] = 0x17; - assert.equal(0x42c395a9, buffer.readInt32BE(0)); - assert.equal(-1013601994, buffer.readInt32BE(1)); - assert.equal(-1784072681, buffer.readInt32BE(2)); - assert.equal(-1449802942, buffer.readInt32LE(0)); - assert.equal(917083587, buffer.readInt32LE(1)); - assert.equal(389458325, buffer.readInt32LE(2)); + assert.strictEqual(0x42c395a9, buffer.readInt32BE(0)); + assert.strictEqual(-1013601994, buffer.readInt32BE(1)); + assert.strictEqual(-1784072681, buffer.readInt32BE(2)); + assert.strictEqual(-1449802942, buffer.readInt32LE(0)); + assert.strictEqual(917083587, buffer.readInt32LE(1)); + assert.strictEqual(389458325, buffer.readInt32LE(2)); } diff --git a/test/parallel/test-readline-interface.js b/test/parallel/test-readline-interface.js index e8fc92ad1c9e27..53c132dc30ec25 100644 --- a/test/parallel/test-readline-interface.js +++ b/test/parallel/test-readline-interface.js @@ -84,7 +84,7 @@ function isWarned(emitter) { called = false; rli.on('line', function(line) { called = true; - assert.equal(line, 'asdf'); + assert.strictEqual(line, 'asdf'); }); fi.emit('data', 'asdf\n'); assert.ok(called); @@ -95,7 +95,7 @@ function isWarned(emitter) { called = false; rli.on('line', function(line) { called = true; - assert.equal(line, ''); + assert.strictEqual(line, ''); }); fi.emit('data', '\n'); assert.ok(called); @@ -117,7 +117,7 @@ function isWarned(emitter) { called = false; rli.on('line', function(line) { called = true; - assert.equal(line, 'a'); + assert.strictEqual(line, 'a'); }); fi.emit('data', 'a'); assert.ok(!called); @@ -131,11 +131,11 @@ function isWarned(emitter) { let expectedLines = ['foo', 'bar', 'baz']; let callCount = 0; rli.on('line', function(line) { - assert.equal(line, expectedLines[callCount]); + assert.strictEqual(line, expectedLines[callCount]); callCount++; }); fi.emit('data', expectedLines.join('\n') + '\n'); - assert.equal(callCount, expectedLines.length); + assert.strictEqual(callCount, expectedLines.length); rli.close(); // sending multiple newlines at once that does not end with a new line @@ -144,11 +144,11 @@ function isWarned(emitter) { expectedLines = ['foo', 'bar', 'baz', 'bat']; callCount = 0; rli.on('line', function(line) { - assert.equal(line, expectedLines[callCount]); + assert.strictEqual(line, expectedLines[callCount]); callCount++; }); fi.emit('data', expectedLines.join('\n')); - assert.equal(callCount, expectedLines.length - 1); + assert.strictEqual(callCount, expectedLines.length - 1); rli.close(); // sending multiple newlines at once that does not end with a new(empty) @@ -158,7 +158,7 @@ function isWarned(emitter) { expectedLines = ['foo', 'bar', 'baz', '']; callCount = 0; rli.on('line', function(line) { - assert.equal(line, expectedLines[callCount]); + assert.strictEqual(line, expectedLines[callCount]); callCount++; }); rli.on('close', function() { @@ -166,7 +166,7 @@ function isWarned(emitter) { }); fi.emit('data', expectedLines.join('\n')); fi.emit('end'); - assert.equal(callCount, expectedLines.length); + assert.strictEqual(callCount, expectedLines.length); rli.close(); // sending multiple newlines at once that does not end with a new line @@ -178,11 +178,11 @@ function isWarned(emitter) { expectedLines = ['foo', 'bar', 'baz', 'bat']; callCount = 0; rli.on('line', function(line) { - assert.equal(line, expectedLines[callCount]); + assert.strictEqual(line, expectedLines[callCount]); callCount++; }); fi.emit('data', expectedLines.join('\r\n')); - assert.equal(callCount, expectedLines.length - 1); + assert.strictEqual(callCount, expectedLines.length - 1); rli.close(); // \r\n should emit one line event when split across multiple writes. @@ -191,14 +191,14 @@ function isWarned(emitter) { expectedLines = ['foo', 'bar', 'baz', 'bat']; callCount = 0; rli.on('line', function(line) { - assert.equal(line, expectedLines[callCount]); + assert.strictEqual(line, expectedLines[callCount]); callCount++; }); expectedLines.forEach(function(line) { fi.emit('data', line + '\r'); fi.emit('data', '\n'); }); - assert.equal(callCount, expectedLines.length); + assert.strictEqual(callCount, expectedLines.length); rli.close(); // \r should behave like \n when alone @@ -207,11 +207,11 @@ function isWarned(emitter) { expectedLines = ['foo', 'bar', 'baz', 'bat']; callCount = 0; rli.on('line', function(line) { - assert.equal(line, expectedLines[callCount]); + assert.strictEqual(line, expectedLines[callCount]); callCount++; }); fi.emit('data', expectedLines.join('\r')); - assert.equal(callCount, expectedLines.length - 1); + assert.strictEqual(callCount, expectedLines.length - 1); rli.close(); // \r at start of input should output blank line @@ -220,11 +220,11 @@ function isWarned(emitter) { expectedLines = ['', 'foo' ]; callCount = 0; rli.on('line', function(line) { - assert.equal(line, expectedLines[callCount]); + assert.strictEqual(line, expectedLines[callCount]); callCount++; }); fi.emit('data', '\rfoo\r'); - assert.equal(callCount, expectedLines.length); + assert.strictEqual(callCount, expectedLines.length); rli.close(); // Emit two line events when the delay @@ -245,7 +245,7 @@ function isWarned(emitter) { fi.emit('data', '\r'); setTimeout(common.mustCall(() => { fi.emit('data', '\n'); - assert.equal(callCount, 2); + assert.strictEqual(callCount, 2); rli.close(); }), delay * 2); } @@ -256,7 +256,7 @@ function isWarned(emitter) { rli = new readline.Interface({ input: fi, output: fi, terminal: true }); called = false; rli.on('line', function(line) { - assert.equal(line, '\t'); + assert.strictEqual(line, '\t'); assert.strictEqual(called, false); called = true; }); @@ -278,7 +278,7 @@ function isWarned(emitter) { }); called = false; rli.on('line', function(line) { - assert.equal(line, 'foo'); + assert.strictEqual(line, 'foo'); assert.strictEqual(called, false); called = true; }); @@ -312,14 +312,14 @@ function isWarned(emitter) { callCount = 0; rli.on('line', function(line) { callCount++; - assert.equal(line, buf.toString('utf8')); + assert.strictEqual(line, buf.toString('utf8')); }); [].forEach.call(buf, function(i) { fi.emit('data', Buffer.from([i])); }); - assert.equal(callCount, 0); + assert.strictEqual(callCount, 0); fi.emit('data', '\n'); - assert.equal(callCount, 1); + assert.strictEqual(callCount, 1); rli.close(); // Regression test for repl freeze, #1968: @@ -337,7 +337,7 @@ function isWarned(emitter) { fi.emit('data', 'fooX'); } catch (e) { } fi.emit('data', 'bar'); - assert.equal(keys.join(''), 'fooXbar'); + assert.strictEqual(keys.join(''), 'fooXbar'); rli.close(); // calling readline without `new` @@ -346,7 +346,7 @@ function isWarned(emitter) { called = false; rli.on('line', function(line) { called = true; - assert.equal(line, 'asdf'); + assert.strictEqual(line, 'asdf'); }); fi.emit('data', 'asdf\n'); assert.ok(called); @@ -361,8 +361,8 @@ function isWarned(emitter) { rli.close(); }); let cursorPos = rli._getCursorPos(); - assert.equal(cursorPos.rows, 0); - assert.equal(cursorPos.cols, expectedLines[0].length); + assert.strictEqual(cursorPos.rows, 0); + assert.strictEqual(cursorPos.cols, expectedLines[0].length); rli.close(); // sending a multi-line question @@ -373,8 +373,8 @@ function isWarned(emitter) { rli.close(); }); cursorPos = rli._getCursorPos(); - assert.equal(cursorPos.rows, expectedLines.length - 1); - assert.equal(cursorPos.cols, expectedLines.slice(-1)[0].length); + assert.strictEqual(cursorPos.rows, expectedLines.length - 1); + assert.strictEqual(cursorPos.cols, expectedLines.slice(-1)[0].length); rli.close(); } @@ -384,17 +384,21 @@ function isWarned(emitter) { }); // wide characters should be treated as two columns. - assert.equal(internalReadline.isFullWidthCodePoint('a'.charCodeAt(0)), false); - assert.equal(internalReadline.isFullWidthCodePoint('あ'.charCodeAt(0)), true); - assert.equal(internalReadline.isFullWidthCodePoint('谢'.charCodeAt(0)), true); - assert.equal(internalReadline.isFullWidthCodePoint('고'.charCodeAt(0)), true); - assert.equal(internalReadline.isFullWidthCodePoint(0x1f251), true); - assert.equal(internalReadline.getStringWidth('abcde'), 5); - assert.equal(internalReadline.getStringWidth('古池や'), 6); - assert.equal(internalReadline.getStringWidth('ノード.js'), 9); - assert.equal(internalReadline.getStringWidth('你好'), 4); - assert.equal(internalReadline.getStringWidth('안녕하세요'), 10); - assert.equal(internalReadline.getStringWidth('A\ud83c\ude00BC'), 5); + assert.strictEqual(internalReadline.isFullWidthCodePoint('a'.charCodeAt(0)), + false); + assert.strictEqual(internalReadline.isFullWidthCodePoint('あ'.charCodeAt(0)), + true); + assert.strictEqual(internalReadline.isFullWidthCodePoint('谢'.charCodeAt(0)), + true); + assert.strictEqual(internalReadline.isFullWidthCodePoint('고'.charCodeAt(0)), + true); + assert.strictEqual(internalReadline.isFullWidthCodePoint(0x1f251), true); + assert.strictEqual(internalReadline.getStringWidth('abcde'), 5); + assert.strictEqual(internalReadline.getStringWidth('古池や'), 6); + assert.strictEqual(internalReadline.getStringWidth('ノード.js'), 9); + assert.strictEqual(internalReadline.getStringWidth('你好'), 4); + assert.strictEqual(internalReadline.getStringWidth('안녕하세요'), 10); + assert.strictEqual(internalReadline.getStringWidth('A\ud83c\ude00BC'), 5); // check if vt control chars are stripped assert.strictEqual( @@ -413,10 +417,13 @@ function isWarned(emitter) { internalReadline.stripVTControlCharacters('> '), '> ' ); - assert.equal(internalReadline.getStringWidth('\u001b[31m> \u001b[39m'), 2); - assert.equal(internalReadline.getStringWidth('\u001b[31m> \u001b[39m> '), 4); - assert.equal(internalReadline.getStringWidth('\u001b[31m\u001b[39m'), 0); - assert.equal(internalReadline.getStringWidth('> '), 2); + assert.strictEqual(internalReadline + .getStringWidth('\u001b[31m> \u001b[39m'), 2); + assert.strictEqual(internalReadline + .getStringWidth('\u001b[31m> \u001b[39m> '), 4); + assert.strictEqual(internalReadline + .getStringWidth('\u001b[31m\u001b[39m'), 0); + assert.strictEqual(internalReadline.getStringWidth('> '), 2); assert.deepStrictEqual(fi.listeners(terminal ? 'keypress' : 'data'), []); @@ -427,8 +434,8 @@ function isWarned(emitter) { output: process.stdout }); rl.close(); - assert.equal(isWarned(process.stdin._events), false); - assert.equal(isWarned(process.stdout._events), false); + assert.strictEqual(isWarned(process.stdin._events), false); + assert.strictEqual(isWarned(process.stdout._events), false); } //can create a new readline Interface with a null output arugument @@ -438,7 +445,7 @@ function isWarned(emitter) { called = false; rli.on('line', function(line) { called = true; - assert.equal(line, 'asdf'); + assert.strictEqual(line, 'asdf'); }); fi.emit('data', 'asdf\n'); assert.ok(called); diff --git a/test/parallel/test-readline-set-raw-mode.js b/test/parallel/test-readline-set-raw-mode.js index 78c42f5f5f627d..389f014bc3e19a 100644 --- a/test/parallel/test-readline-set-raw-mode.js +++ b/test/parallel/test-readline-set-raw-mode.js @@ -12,7 +12,7 @@ let pauseCalled = false; stream.setRawMode = function(mode) { rawModeCalled = true; - assert.equal(mode, expectedRawMode); + assert.strictEqual(mode, expectedRawMode); }; stream.resume = function() { resumeCalled = true; @@ -66,4 +66,4 @@ assert(pauseCalled); assert.deepStrictEqual(stream.listeners('keypress'), []); // one data listener for the keypress events. -assert.equal(stream.listeners('data').length, 1); +assert.strictEqual(stream.listeners('data').length, 1); diff --git a/test/parallel/test-readuint.js b/test/parallel/test-readuint.js index 0d1f79b12eabd4..d1507a81b5188a 100644 --- a/test/parallel/test-readuint.js +++ b/test/parallel/test-readuint.js @@ -20,13 +20,13 @@ function test8(clazz) { data[1] = 23; data[2] = 23; data[3] = 23; - assert.equal(23, data.readUInt8(0)); - assert.equal(23, data.readUInt8(1)); - assert.equal(23, data.readUInt8(2)); - assert.equal(23, data.readUInt8(3)); + assert.strictEqual(23, data.readUInt8(0)); + assert.strictEqual(23, data.readUInt8(1)); + assert.strictEqual(23, data.readUInt8(2)); + assert.strictEqual(23, data.readUInt8(3)); data[0] = 255; /* If it became a signed int, would be -1 */ - assert.equal(255, data.readUInt8(0)); + assert.strictEqual(255, data.readUInt8(0)); } @@ -45,17 +45,17 @@ function test16(clazz) { data[1] = 0x23; data[2] = 0x42; data[3] = 0x3f; - assert.equal(0x23, data.readUInt16BE(0)); - assert.equal(0x2342, data.readUInt16BE(1)); - assert.equal(0x423f, data.readUInt16BE(2)); - assert.equal(0x2300, data.readUInt16LE(0)); - assert.equal(0x4223, data.readUInt16LE(1)); - assert.equal(0x3f42, data.readUInt16LE(2)); + assert.strictEqual(0x23, data.readUInt16BE(0)); + assert.strictEqual(0x2342, data.readUInt16BE(1)); + assert.strictEqual(0x423f, data.readUInt16BE(2)); + assert.strictEqual(0x2300, data.readUInt16LE(0)); + assert.strictEqual(0x4223, data.readUInt16LE(1)); + assert.strictEqual(0x3f42, data.readUInt16LE(2)); data[0] = 0xfe; data[1] = 0xfe; - assert.equal(0xfefe, data.readUInt16BE(0)); - assert.equal(0xfefe, data.readUInt16LE(0)); + assert.strictEqual(0xfefe, data.readUInt16BE(0)); + assert.strictEqual(0xfefe, data.readUInt16LE(0)); } @@ -75,12 +75,12 @@ function test32(clazz) { data[3] = 0x56; data[4] = 0x23; data[5] = 0xff; - assert.equal(0x32654256, data.readUInt32BE(0)); - assert.equal(0x65425623, data.readUInt32BE(1)); - assert.equal(0x425623ff, data.readUInt32BE(2)); - assert.equal(0x56426532, data.readUInt32LE(0)); - assert.equal(0x23564265, data.readUInt32LE(1)); - assert.equal(0xff235642, data.readUInt32LE(2)); + assert.strictEqual(0x32654256, data.readUInt32BE(0)); + assert.strictEqual(0x65425623, data.readUInt32BE(1)); + assert.strictEqual(0x425623ff, data.readUInt32BE(2)); + assert.strictEqual(0x56426532, data.readUInt32LE(0)); + assert.strictEqual(0x23564265, data.readUInt32LE(1)); + assert.strictEqual(0xff235642, data.readUInt32LE(2)); } diff --git a/test/parallel/test-regress-GH-1899.js b/test/parallel/test-regress-GH-1899.js index 838391acd23b5f..a072bc551a5c4f 100644 --- a/test/parallel/test-regress-GH-1899.js +++ b/test/parallel/test-regress-GH-1899.js @@ -14,6 +14,6 @@ child.stdout.on('data', function(data) { }); child.on('exit', function(code, signal) { - assert.equal(code, 0); - assert.equal(output, 'hello, world!\n'); + assert.strictEqual(code, 0); + assert.strictEqual(output, 'hello, world!\n'); }); diff --git a/test/parallel/test-regress-GH-5051.js b/test/parallel/test-regress-GH-5051.js index a86d0943d313fe..f2562bd7eb8020 100644 --- a/test/parallel/test-regress-GH-5051.js +++ b/test/parallel/test-regress-GH-5051.js @@ -13,8 +13,8 @@ agent.maxSockets = 0; // localAddress is used when naming requests / sockets // while using the Legacy API agent.addRequest(req, 'localhost', common.PORT, '127.0.0.1'); -assert.equal(Object.keys(agent.requests).length, 1); -assert.equal( +assert.strictEqual(Object.keys(agent.requests).length, 1); +assert.strictEqual( Object.keys(agent.requests)[0], 'localhost:' + common.PORT + ':127.0.0.1'); @@ -25,7 +25,7 @@ agent.addRequest(req, { localAddress: '127.0.0.1', path: '/foo' }); -assert.equal(Object.keys(agent.requests).length, 1); -assert.equal( +assert.strictEqual(Object.keys(agent.requests).length, 1); +assert.strictEqual( Object.keys(agent.requests)[0], 'localhost:' + common.PORT + ':127.0.0.1'); diff --git a/test/parallel/test-regress-GH-5727.js b/test/parallel/test-regress-GH-5727.js index 3f52c55e7aaca6..5fe9776d9b30fc 100644 --- a/test/parallel/test-regress-GH-5727.js +++ b/test/parallel/test-regress-GH-5727.js @@ -10,7 +10,7 @@ net.Server().listen(common.PORT, function() { const address = this.address(); const key = `${address.family.slice(-1)}:${address.address}:${common.PORT}`; - assert.equal(this._connectionKey, key); + assert.strictEqual(this._connectionKey, key); this.close(); }); diff --git a/test/parallel/test-repl-.save.load.js b/test/parallel/test-repl-.save.load.js index 00d5f6791d54a5..449dd28e90d59e 100644 --- a/test/parallel/test-repl-.save.load.js +++ b/test/parallel/test-repl-.save.load.js @@ -27,7 +27,8 @@ putIn.run(testFile); putIn.run(['.save ' + saveFileName]); // the file should have what I wrote -assert.equal(fs.readFileSync(saveFileName, 'utf8'), testFile.join('\n') + '\n'); +assert.strictEqual(fs.readFileSync(saveFileName, 'utf8'), testFile.join('\n') + + '\n'); { // save .editor mode code @@ -74,7 +75,7 @@ let loadFile = join(common.tmpDir, 'file.does.not.exist'); // should not break putIn.write = function(data) { // make sure I get a failed to load message and not some crazy error - assert.equal(data, 'Failed to load:' + loadFile + '\n'); + assert.strictEqual(data, 'Failed to load:' + loadFile + '\n'); // eat me to avoid work putIn.write = function() {}; }; @@ -83,7 +84,8 @@ putIn.run(['.load ' + loadFile]); // throw error on loading directory loadFile = common.tmpDir; putIn.write = function(data) { - assert.equal(data, 'Failed to load:' + loadFile + ' is not a valid file\n'); + assert.strictEqual(data, 'Failed to load:' + loadFile + + ' is not a valid file\n'); putIn.write = function() {}; }; putIn.run(['.load ' + loadFile]); @@ -98,7 +100,7 @@ const invalidFileName = join(common.tmpDir, '\0\0\0\0\0'); // should not break putIn.write = function(data) { // make sure I get a failed to save message and not some other error - assert.equal(data, 'Failed to save:' + invalidFileName + '\n'); + assert.strictEqual(data, 'Failed to save:' + invalidFileName + '\n'); // reset to no-op putIn.write = function() {}; }; diff --git a/test/parallel/test-repl-autolibs.js b/test/parallel/test-repl-autolibs.js index e0554831cdca50..ce108ba2aa859f 100644 --- a/test/parallel/test-repl-autolibs.js +++ b/test/parallel/test-repl-autolibs.js @@ -19,9 +19,10 @@ function test1() { if (data.length) { // inspect output matches repl output - assert.equal(data, util.inspect(require('fs'), null, 2, false) + '\n'); + assert.strictEqual(data, util.inspect(require('fs'), null, 2, false) + + '\n'); // globally added lib matches required lib - assert.equal(global.fs, require('fs')); + assert.strictEqual(global.fs, require('fs')); test2(); } }; @@ -36,9 +37,9 @@ function test2() { gotWrite = true; if (data.length) { // repl response error message - assert.equal(data, '{}\n'); + assert.strictEqual(data, '{}\n'); // original value wasn't overwritten - assert.equal(val, global.url); + assert.strictEqual(val, global.url); } }; const val = {}; diff --git a/test/parallel/test-repl-end-emits-exit.js b/test/parallel/test-repl-end-emits-exit.js index 661f9f0ad0e3a4..c62a51c9626e24 100644 --- a/test/parallel/test-repl-end-emits-exit.js +++ b/test/parallel/test-repl-end-emits-exit.js @@ -45,8 +45,8 @@ function testRegularMode() { } process.on('exit', function() { - assert.equal(terminalExit, 1); - assert.equal(regularExit, 1); + assert.strictEqual(terminalExit, 1); + assert.strictEqual(regularExit, 1); }); diff --git a/test/parallel/test-repl-envvars.js b/test/parallel/test-repl-envvars.js index e8c369b244c607..bd4e1fc9afb679 100644 --- a/test/parallel/test-repl-envvars.js +++ b/test/parallel/test-repl-envvars.js @@ -50,10 +50,10 @@ function run(test) { // The REPL registers 'module' and 'require' globals common.allowGlobals(repl.context.module, repl.context.require); - assert.equal(expected.terminal, repl.terminal, - 'Expected ' + inspect(expected) + ' with ' + inspect(env)); - assert.equal(expected.useColors, repl.useColors, - 'Expected ' + inspect(expected) + ' with ' + inspect(env)); + assert.strictEqual(expected.terminal, repl.terminal, 'Expected ' + + inspect(expected) + ' with ' + inspect(env)); + assert.strictEqual(expected.useColors, repl.useColors, 'Expected ' + + inspect(expected) + ' with ' + inspect(env)); repl.close(); }); } diff --git a/test/parallel/test-repl-options.js b/test/parallel/test-repl-options.js index 79994c66d148c0..03db110aca6dbc 100644 --- a/test/parallel/test-repl-options.js +++ b/test/parallel/test-repl-options.js @@ -15,24 +15,24 @@ const r1 = repl.start({ terminal: true }); -assert.equal(r1.input, stream); -assert.equal(r1.output, stream); -assert.equal(r1.input, r1.inputStream); -assert.equal(r1.output, r1.outputStream); -assert.equal(r1.terminal, true); -assert.equal(r1.useColors, r1.terminal); -assert.equal(r1.useGlobal, false); -assert.equal(r1.ignoreUndefined, false); -assert.equal(r1.replMode, repl.REPL_MODE_SLOPPY); -assert.equal(r1.historySize, 30); +assert.strictEqual(r1.input, stream); +assert.strictEqual(r1.output, stream); +assert.strictEqual(r1.input, r1.inputStream); +assert.strictEqual(r1.output, r1.outputStream); +assert.strictEqual(r1.terminal, true); +assert.strictEqual(r1.useColors, r1.terminal); +assert.strictEqual(r1.useGlobal, false); +assert.strictEqual(r1.ignoreUndefined, false); +assert.strictEqual(r1.replMode, repl.REPL_MODE_SLOPPY); +assert.strictEqual(r1.historySize, 30); // test r1 for backwards compact -assert.equal(r1.rli.input, stream); -assert.equal(r1.rli.output, stream); -assert.equal(r1.rli.input, r1.inputStream); -assert.equal(r1.rli.output, r1.outputStream); -assert.equal(r1.rli.terminal, true); -assert.equal(r1.useColors, r1.rli.terminal); +assert.strictEqual(r1.rli.input, stream); +assert.strictEqual(r1.rli.output, stream); +assert.strictEqual(r1.rli.input, r1.inputStream); +assert.strictEqual(r1.rli.output, r1.outputStream); +assert.strictEqual(r1.rli.terminal, true); +assert.strictEqual(r1.useColors, r1.rli.terminal); // 2 function writer() {} @@ -48,23 +48,23 @@ const r2 = repl.start({ writer: writer, replMode: repl.REPL_MODE_STRICT }); -assert.equal(r2.input, stream); -assert.equal(r2.output, stream); -assert.equal(r2.input, r2.inputStream); -assert.equal(r2.output, r2.outputStream); -assert.equal(r2.terminal, false); -assert.equal(r2.useColors, true); -assert.equal(r2.useGlobal, true); -assert.equal(r2.ignoreUndefined, true); -assert.equal(r2.writer, writer); -assert.equal(r2.replMode, repl.REPL_MODE_STRICT); +assert.strictEqual(r2.input, stream); +assert.strictEqual(r2.output, stream); +assert.strictEqual(r2.input, r2.inputStream); +assert.strictEqual(r2.output, r2.outputStream); +assert.strictEqual(r2.terminal, false); +assert.strictEqual(r2.useColors, true); +assert.strictEqual(r2.useGlobal, true); +assert.strictEqual(r2.ignoreUndefined, true); +assert.strictEqual(r2.writer, writer); +assert.strictEqual(r2.replMode, repl.REPL_MODE_STRICT); // test r2 for backwards compact -assert.equal(r2.rli.input, stream); -assert.equal(r2.rli.output, stream); -assert.equal(r2.rli.input, r2.inputStream); -assert.equal(r2.rli.output, r2.outputStream); -assert.equal(r2.rli.terminal, false); +assert.strictEqual(r2.rli.input, stream); +assert.strictEqual(r2.rli.output, stream); +assert.strictEqual(r2.rli.input, r2.inputStream); +assert.strictEqual(r2.rli.output, r2.outputStream); +assert.strictEqual(r2.rli.terminal, false); // testing out "magic" replMode const r3 = repl.start({ @@ -75,8 +75,8 @@ const r3 = repl.start({ historySize: 50 }); -assert.equal(r3.replMode, repl.REPL_MODE_MAGIC); -assert.equal(r3.historySize, 50); +assert.strictEqual(r3.replMode, repl.REPL_MODE_MAGIC); +assert.strictEqual(r3.historySize, 50); // Verify that defaults are used when no arguments are provided const r4 = repl.start(); diff --git a/test/parallel/test-repl-require-cache.js b/test/parallel/test-repl-require-cache.js index 8a5d384935efd4..4ccabe473cdbe8 100644 --- a/test/parallel/test-repl-require-cache.js +++ b/test/parallel/test-repl-require-cache.js @@ -6,8 +6,8 @@ const repl = require('repl'); // https://github.com/joyent/node/issues/3226 require.cache.something = 1; -assert.equal(require.cache.something, 1); +assert.strictEqual(require.cache.something, 1); repl.start({ useGlobal: false }).close(); -assert.equal(require.cache.something, 1); +assert.strictEqual(require.cache.something, 1); diff --git a/test/parallel/test-repl-syntax-error-handling.js b/test/parallel/test-repl-syntax-error-handling.js index 6a65d53a029379..9014f9a02f22be 100644 --- a/test/parallel/test-repl-syntax-error-handling.js +++ b/test/parallel/test-repl-syntax-error-handling.js @@ -27,7 +27,7 @@ function parent() { out += c; }); child.stdout.on('end', function() { - assert.equal(out, '10\n'); + assert.strictEqual(out, '10\n'); console.log('ok - got expected output'); }); diff --git a/test/parallel/test-repl-tab.js b/test/parallel/test-repl-tab.js index 7baa7d0aace812..92168b2e1df56f 100644 --- a/test/parallel/test-repl-tab.js +++ b/test/parallel/test-repl-tab.js @@ -14,5 +14,5 @@ const testMe = repl.start('', putIn, function(cmd, context, filename, testMe._domain.on('error', common.fail); testMe.complete('', function(err, results) { - assert.equal(err, null); + assert.strictEqual(err, null); }); diff --git a/test/parallel/test-require-extensions-same-filename-as-dir-trailing-slash.js b/test/parallel/test-require-extensions-same-filename-as-dir-trailing-slash.js index aa749591eb553a..85fc7ec913482d 100644 --- a/test/parallel/test-require-extensions-same-filename-as-dir-trailing-slash.js +++ b/test/parallel/test-require-extensions-same-filename-as-dir-trailing-slash.js @@ -7,4 +7,4 @@ const content = require(common.fixturesDir + '/json-with-directory-name-module/module-stub/one-trailing-slash/two/three.js'); assert.notStrictEqual(content.rocko, 'artischocko'); -assert.equal(content, 'hello from module-stub!'); +assert.strictEqual(content, 'hello from module-stub!'); diff --git a/test/parallel/test-require-unicode.js b/test/parallel/test-require-unicode.js index 0bccf06916c326..93a8787cdfe7c8 100644 --- a/test/parallel/test-require-unicode.js +++ b/test/parallel/test-require-unicode.js @@ -12,5 +12,5 @@ fs.mkdirSync(dirname); fs.writeFileSync(path.join(dirname, 'file.js'), 'module.exports = 42;'); fs.writeFileSync(path.join(dirname, 'package.json'), JSON.stringify({ name: 'test', main: 'file.js' })); -assert.equal(require(dirname), 42); -assert.equal(require(path.join(dirname, 'file.js')), 42); +assert.strictEqual(require(dirname), 42); +assert.strictEqual(require(path.join(dirname, 'file.js')), 42); diff --git a/test/parallel/test-socket-write-after-fin-error.js b/test/parallel/test-socket-write-after-fin-error.js index f21b52d519b2ba..37d042b4c6031a 100644 --- a/test/parallel/test-socket-write-after-fin-error.js +++ b/test/parallel/test-socket-write-after-fin-error.js @@ -43,12 +43,12 @@ server.listen(0, function() { }); process.on('exit', function() { - assert.equal(clientData, ''); - assert.equal(serverData, 'hello1hello2hello3\nTHUNDERMUSCLE!'); + assert.strictEqual(clientData, ''); + assert.strictEqual(serverData, 'hello1hello2hello3\nTHUNDERMUSCLE!'); assert(gotClientEnd); assert(gotServerEnd); assert(gotServerError); - assert.equal(gotServerError.code, 'EPIPE'); + assert.strictEqual(gotServerError.code, 'EPIPE'); assert.notStrictEqual(gotServerError.message, 'write after end'); console.log('ok'); }); diff --git a/test/parallel/test-stdin-child-proc.js b/test/parallel/test-stdin-child-proc.js index 35ae0c99d3c8ff..5359edc53a42ba 100644 --- a/test/parallel/test-stdin-child-proc.js +++ b/test/parallel/test-stdin-child-proc.js @@ -9,5 +9,5 @@ const cp = child_process.spawn(process.execPath, [path.resolve(__dirname, 'test-stdin-pause-resume.js')]); cp.on('exit', common.mustCall((code) => { - assert.equal(code, 0); + assert.strictEqual(code, 0); })); diff --git a/test/parallel/test-stdin-pipe-resume.js b/test/parallel/test-stdin-pipe-resume.js index 06cce3edfe403f..e9000933a37cfa 100644 --- a/test/parallel/test-stdin-pipe-resume.js +++ b/test/parallel/test-stdin-pipe-resume.js @@ -14,7 +14,7 @@ if (process.argv[2] === 'child') { }); child.stdout.on('close', function() { const b = Buffer.concat(buffers).toString(); - assert.equal(b, 'Hello, world\n'); + assert.strictEqual(b, 'Hello, world\n'); console.log('ok'); }); child.stdin.write('Hel'); diff --git a/test/parallel/test-stdout-cannot-be-closed-child-process-pipe.js b/test/parallel/test-stdout-cannot-be-closed-child-process-pipe.js index aa1939ebe2c334..d19b522e290ba9 100644 --- a/test/parallel/test-stdout-cannot-be-closed-child-process-pipe.js +++ b/test/parallel/test-stdout-cannot-be-closed-child-process-pipe.js @@ -25,7 +25,7 @@ function parent() { child.on('close', function(code, signal) { assert(code); - assert.equal(out, 'foo'); + assert.strictEqual(out, 'foo'); assert(/process\.stdout cannot be closed/.test(err)); console.log('ok'); }); diff --git a/test/parallel/test-stdout-stderr-reading.js b/test/parallel/test-stdout-stderr-reading.js index 6aa961301349fc..11cdcc390768a3 100644 --- a/test/parallel/test-stdout-stderr-reading.js +++ b/test/parallel/test-stdout-stderr-reading.js @@ -36,7 +36,7 @@ function parent() { c1.on('close', common.mustCall(function(code, signal) { assert(!code); assert(!signal); - assert.equal(c1out, 'ok\n'); + assert.strictEqual(c1out, 'ok\n'); console.log('ok'); })); @@ -53,7 +53,7 @@ function parent() { c2.on('close', common.mustCall(function(code, signal) { assert(!code); assert(!signal); - assert.equal(c2out, 'ok\n'); + assert.strictEqual(c2out, 'ok\n'); console.log('ok'); })); } diff --git a/test/parallel/test-stream-base-no-abort.js b/test/parallel/test-stream-base-no-abort.js index 6b1cc67ee7777e..8b85acea2fb7ea 100644 --- a/test/parallel/test-stream-base-no-abort.js +++ b/test/parallel/test-stream-base-no-abort.js @@ -17,21 +17,21 @@ const providers = Object.keys(async_wrap.Providers); let flags = 0; // Make sure all asserts have run at least once. -process.on('exit', () => assert.equal(flags, 0b111)); +process.on('exit', () => assert.strictEqual(flags, 0b111)); function init(id, provider) { this._external; // Test will abort if nullptr isn't properly checked. switch (providers[provider]) { case 'TCPWRAP': - assert.equal(this.fd, uv.UV_EINVAL); + assert.strictEqual(this.fd, uv.UV_EINVAL); flags |= 0b1; break; case 'TLSWRAP': - assert.equal(this.fd, uv.UV_EINVAL); + assert.strictEqual(this.fd, uv.UV_EINVAL); flags |= 0b10; break; case 'UDPWRAP': - assert.equal(this.fd, uv.UV_EBADF); + assert.strictEqual(this.fd, uv.UV_EBADF); flags |= 0b100; break; } diff --git a/test/parallel/test-stream-push-strings.js b/test/parallel/test-stream-push-strings.js index 7bce493bbd33ce..e77d8a48c679ef 100644 --- a/test/parallel/test-stream-push-strings.js +++ b/test/parallel/test-stream-push-strings.js @@ -40,7 +40,7 @@ ms.on('readable', function() { const expect = [ 'first chunksecond to last chunk', 'last chunk' ]; process.on('exit', function() { - assert.equal(ms._chunks, -1); + assert.strictEqual(ms._chunks, -1); assert.deepStrictEqual(results, expect); console.log('ok'); }); diff --git a/test/parallel/test-stream-readable-constructor-set-methods.js b/test/parallel/test-stream-readable-constructor-set-methods.js index a5d7e48bfb3fa9..e5e3114de456db 100644 --- a/test/parallel/test-stream-readable-constructor-set-methods.js +++ b/test/parallel/test-stream-readable-constructor-set-methods.js @@ -14,6 +14,6 @@ const r = new Readable({ read: _read }); r.resume(); process.on('exit', function() { - assert.equal(r._read, _read); + assert.strictEqual(r._read, _read); assert(_readCalled); }); diff --git a/test/parallel/test-stream-readable-flow-recursion.js b/test/parallel/test-stream-readable-flow-recursion.js index b1e421a71fd15b..e29553900511c3 100644 --- a/test/parallel/test-stream-readable-flow-recursion.js +++ b/test/parallel/test-stream-readable-flow-recursion.js @@ -45,12 +45,12 @@ flow(stream, 5000, function() { }); process.on('exit', function(code) { - assert.equal(reads, 2); + assert.strictEqual(reads, 2); // we pushed up the high water mark - assert.equal(stream._readableState.highWaterMark, 8192); + assert.strictEqual(stream._readableState.highWaterMark, 8192); // length is 0 right now, because we pulled it all out. - assert.equal(stream._readableState.length, 0); + assert.strictEqual(stream._readableState.length, 0); assert(!code); - assert.equal(depth, 0); + assert.strictEqual(depth, 0); console.log('ok'); }); diff --git a/test/parallel/test-stream-transform-constructor-set-methods.js b/test/parallel/test-stream-transform-constructor-set-methods.js index 7be673c517b30b..02ef9f55cb4460 100644 --- a/test/parallel/test-stream-transform-constructor-set-methods.js +++ b/test/parallel/test-stream-transform-constructor-set-methods.js @@ -25,8 +25,8 @@ t.end(Buffer.from('blerg')); t.resume(); process.on('exit', function() { - assert.equal(t._transform, _transform); - assert.equal(t._flush, _flush); + assert.strictEqual(t._transform, _transform); + assert.strictEqual(t._flush, _flush); assert(_transformCalled); assert(_flushCalled); }); diff --git a/test/parallel/test-stream-writable-change-default-encoding.js b/test/parallel/test-stream-writable-change-default-encoding.js index 9eac52bc1aea44..c3af66ce83701c 100644 --- a/test/parallel/test-stream-writable-change-default-encoding.js +++ b/test/parallel/test-stream-writable-change-default-encoding.js @@ -19,7 +19,7 @@ MyWritable.prototype._write = function(chunk, encoding, callback) { (function defaultCondingIsUtf8() { const m = new MyWritable(function(isBuffer, type, enc) { - assert.equal(enc, 'utf8'); + assert.strictEqual(enc, 'utf8'); }, { decodeStrings: false }); m.write('foo'); m.end(); @@ -27,7 +27,7 @@ MyWritable.prototype._write = function(chunk, encoding, callback) { (function changeDefaultEncodingToAscii() { const m = new MyWritable(function(isBuffer, type, enc) { - assert.equal(enc, 'ascii'); + assert.strictEqual(enc, 'ascii'); }, { decodeStrings: false }); m.setDefaultEncoding('ascii'); m.write('bar'); @@ -44,7 +44,7 @@ assert.throws(function changeDefaultEncodingToInvalidValue() { (function checkVairableCaseEncoding() { const m = new MyWritable(function(isBuffer, type, enc) { - assert.equal(enc, 'ascii'); + assert.strictEqual(enc, 'ascii'); }, { decodeStrings: false }); m.setDefaultEncoding('AsCii'); m.write('bar'); diff --git a/test/parallel/test-stream-writable-constructor-set-methods.js b/test/parallel/test-stream-writable-constructor-set-methods.js index 9b344487f61580..a12112d1ecc266 100644 --- a/test/parallel/test-stream-writable-constructor-set-methods.js +++ b/test/parallel/test-stream-writable-constructor-set-methods.js @@ -27,9 +27,9 @@ w2.write(Buffer.from('blerg')); w2.end(); process.on('exit', function() { - assert.equal(w._write, _write); + assert.strictEqual(w._write, _write); assert(_writeCalled); - assert.equal(w2._writev, _writev); - assert.equal(dLength, 2); + assert.strictEqual(w2._writev, _writev); + assert.strictEqual(dLength, 2); assert(_writevCalled); }); diff --git a/test/parallel/test-stream-writableState-uncorked-bufferedRequestCount.js b/test/parallel/test-stream-writableState-uncorked-bufferedRequestCount.js index 3751cd9de6461d..dbd306c53f9ccb 100644 --- a/test/parallel/test-stream-writableState-uncorked-bufferedRequestCount.js +++ b/test/parallel/test-stream-writableState-uncorked-bufferedRequestCount.js @@ -7,7 +7,7 @@ const stream = require('stream'); const writable = new stream.Writable(); writable._writev = common.mustCall((chunks, cb) => { - assert.equal(chunks.length, 2, 'two chunks to write'); + assert.strictEqual(chunks.length, 2, 'two chunks to write'); cb(); }, 1); diff --git a/test/parallel/test-stream-writev.js b/test/parallel/test-stream-writev.js index 4e05d2ba8e70e8..2caaf0a7d236c1 100644 --- a/test/parallel/test-stream-writev.js +++ b/test/parallel/test-stream-writev.js @@ -33,7 +33,7 @@ function test(decode, uncork, multi, next) { return function(er) { assert.ifError(er); counter++; - assert.equal(counter, expect); + assert.strictEqual(counter, expect); }; } diff --git a/test/parallel/test-stream2-base64-single-char-read-end.js b/test/parallel/test-stream2-base64-single-char-read-end.js index da63644de099a1..6a9edbd4eaacbe 100644 --- a/test/parallel/test-stream2-base64-single-char-read-end.js +++ b/test/parallel/test-stream2-base64-single-char-read-end.js @@ -25,7 +25,7 @@ dst._write = function(chunk, enc, cb) { }; src.on('end', function() { - assert.equal(Buffer.concat(accum) + '', 'MQ=='); + assert.strictEqual(Buffer.concat(accum) + '', 'MQ=='); clearTimeout(timeout); }); diff --git a/test/parallel/test-stream2-compatibility.js b/test/parallel/test-stream2-compatibility.js index f7c980791311da..a353da8dede305 100644 --- a/test/parallel/test-stream2-compatibility.js +++ b/test/parallel/test-stream2-compatibility.js @@ -26,7 +26,7 @@ TestReader.prototype._read = function(n) { const reader = new TestReader(); setImmediate(function() { - assert.equal(ondataCalled, 1); + assert.strictEqual(ondataCalled, 1); console.log('ok'); reader.push(null); }); diff --git a/test/parallel/test-stream2-large-read-stall.js b/test/parallel/test-stream2-large-read-stall.js index 88fef4f24b6c30..36d4e0c6c9d7c9 100644 --- a/test/parallel/test-stream2-large-read-stall.js +++ b/test/parallel/test-stream2-large-read-stall.js @@ -51,5 +51,5 @@ function push() { } process.on('exit', function() { - assert.equal(pushes, PUSHCOUNT + 1); + assert.strictEqual(pushes, PUSHCOUNT + 1); }); diff --git a/test/parallel/test-stream2-objects.js b/test/parallel/test-stream2-objects.js index 6c00f1b8691364..cab838fbfc9acb 100644 --- a/test/parallel/test-stream2-objects.js +++ b/test/parallel/test-stream2-objects.js @@ -23,7 +23,7 @@ function run() { console.log('# %s', name); fn({ same: assert.deepStrictEqual, - equal: assert.equal, + equal: assert.strictEqual, end: function() { count--; run(); diff --git a/test/parallel/test-stream2-readable-from-list.js b/test/parallel/test-stream2-readable-from-list.js index f3f39507e89dab..54db1d1c182526 100644 --- a/test/parallel/test-stream2-readable-from-list.js +++ b/test/parallel/test-stream2-readable-from-list.js @@ -24,7 +24,7 @@ function run() { console.log('# %s', name); fn({ same: assert.deepStrictEqual, - equal: assert.equal, + equal: assert.strictEqual, end: function() { count--; run(); @@ -41,7 +41,7 @@ function bufferListFromArray(arr) { // ensure all tests have run process.on('exit', function() { - assert.equal(count, 0); + assert.strictEqual(count, 0); }); process.nextTick(run); diff --git a/test/parallel/test-stream2-readable-non-empty-end.js b/test/parallel/test-stream2-readable-non-empty-end.js index 66fae8274ecf3c..46481fe1dcda4c 100644 --- a/test/parallel/test-stream2-readable-non-empty-end.js +++ b/test/parallel/test-stream2-readable-non-empty-end.js @@ -45,7 +45,7 @@ function next() { // one to get the last byte let r = test.read(); assert(r); - assert.equal(r.length, 1); + assert.strictEqual(r.length, 1); r = test.read(); - assert.equal(r, null); + assert.strictEqual(r, null); } diff --git a/test/parallel/test-stream2-set-encoding.js b/test/parallel/test-stream2-set-encoding.js index fdbd81e61332b1..a207168f39a97e 100644 --- a/test/parallel/test-stream2-set-encoding.js +++ b/test/parallel/test-stream2-set-encoding.js @@ -23,7 +23,7 @@ function run() { console.log('# %s', name); fn({ same: assert.deepStrictEqual, - equal: assert.equal, + equal: assert.strictEqual, end: function() { count--; run(); @@ -33,7 +33,7 @@ function run() { // ensure all tests have run process.on('exit', function() { - assert.equal(count, 0); + assert.strictEqual(count, 0); }); process.nextTick(run); diff --git a/test/parallel/test-stream2-transform.js b/test/parallel/test-stream2-transform.js index d66f1f064375e4..2695ac21b752c4 100644 --- a/test/parallel/test-stream2-transform.js +++ b/test/parallel/test-stream2-transform.js @@ -23,7 +23,7 @@ function run() { console.log('# %s', name); fn({ same: assert.deepStrictEqual, - equal: assert.equal, + equal: assert.strictEqual, ok: assert, end: function() { count--; @@ -34,7 +34,7 @@ function run() { // ensure all tests have run process.on('exit', function() { - assert.equal(count, 0); + assert.strictEqual(count, 0); }); process.nextTick(run); diff --git a/test/parallel/test-stream2-unpipe-leak.js b/test/parallel/test-stream2-unpipe-leak.js index 1a1599ca32b4c7..8800a2bbc68e45 100644 --- a/test/parallel/test-stream2-unpipe-leak.js +++ b/test/parallel/test-stream2-unpipe-leak.js @@ -36,14 +36,14 @@ for (let i = 0; i < 10; i++) { src.unpipe(dest); } -assert.equal(src.listeners('end').length, 0); -assert.equal(src.listeners('readable').length, 0); - -assert.equal(dest.listeners('unpipe').length, 0); -assert.equal(dest.listeners('drain').length, 0); -assert.equal(dest.listeners('error').length, 0); -assert.equal(dest.listeners('close').length, 0); -assert.equal(dest.listeners('finish').length, 0); +assert.strictEqual(src.listeners('end').length, 0); +assert.strictEqual(src.listeners('readable').length, 0); + +assert.strictEqual(dest.listeners('unpipe').length, 0); +assert.strictEqual(dest.listeners('drain').length, 0); +assert.strictEqual(dest.listeners('error').length, 0); +assert.strictEqual(dest.listeners('close').length, 0); +assert.strictEqual(dest.listeners('finish').length, 0); console.error(src._readableState); process.on('exit', function() { diff --git a/test/parallel/test-stream3-cork-end.js b/test/parallel/test-stream3-cork-end.js index 230227e0b13ddb..7227f87ada7fa1 100644 --- a/test/parallel/test-stream3-cork-end.js +++ b/test/parallel/test-stream3-cork-end.js @@ -22,7 +22,7 @@ w._write = function(chunk, encoding, cb) { // stream end event is not seen before the last write assert.ok(!seenEnd); // default encoding given none was specified - assert.equal(encoding, 'buffer'); + assert.strictEqual(encoding, 'buffer'); seenChunks.push(chunk); cb(); @@ -52,7 +52,7 @@ function writeChunks(remainingChunks, callback) { // do an initial write w.write('stuff'); // the write was immediate -assert.equal(seenChunks.length, 1); +assert.strictEqual(seenChunks.length, 1); // reset the seen chunks seenChunks = []; @@ -62,7 +62,7 @@ w.cork(); // write the bufferedChunks writeChunks(inputChunks, () => { // should not have seen anything yet - assert.equal(seenChunks.length, 0); + assert.strictEqual(seenChunks.length, 0); // trigger flush and ending the stream w.end(); @@ -71,7 +71,7 @@ writeChunks(inputChunks, () => { assert.ok(!seenEnd); // buffered bytes should be seen in current tick - assert.equal(seenChunks.length, 4); + assert.strictEqual(seenChunks.length, 4); // did the chunks match for (let i = 0, l = expectedChunks.length; i < l; i++) { diff --git a/test/parallel/test-stream3-cork-uncork.js b/test/parallel/test-stream3-cork-uncork.js index 821fd22bf8b8a3..98f74a45c6624e 100644 --- a/test/parallel/test-stream3-cork-uncork.js +++ b/test/parallel/test-stream3-cork-uncork.js @@ -20,7 +20,7 @@ const w = new Writable(); // lets arrange to store the chunks w._write = function(chunk, encoding, cb) { // default encoding given none was specified - assert.equal(encoding, 'buffer'); + assert.strictEqual(encoding, 'buffer'); seenChunks.push(chunk); cb(); @@ -50,7 +50,7 @@ function writeChunks(remainingChunks, callback) { // do an initial write w.write('stuff'); // the write was immediate -assert.equal(seenChunks.length, 1); +assert.strictEqual(seenChunks.length, 1); // reset the chunks seen so far seenChunks = []; @@ -60,13 +60,13 @@ w.cork(); // write the bufferedChunks writeChunks(inputChunks, () => { // should not have seen anything yet - assert.equal(seenChunks.length, 0); + assert.strictEqual(seenChunks.length, 0); // trigger writing out the buffer w.uncork(); // buffered bytes shoud be seen in current tick - assert.equal(seenChunks.length, 4); + assert.strictEqual(seenChunks.length, 4); // did the chunks match for (let i = 0, l = expectedChunks.length; i < l; i++) { diff --git a/test/parallel/test-stream3-pause-then-read.js b/test/parallel/test-stream3-pause-then-read.js index 5a9550bcd41d7f..a1be563683c0a2 100644 --- a/test/parallel/test-stream3-pause-then-read.js +++ b/test/parallel/test-stream3-pause-then-read.js @@ -46,7 +46,7 @@ function readn(n, then) { if (!c) r.once('readable', read); else { - assert.equal(c.length, n); + assert.strictEqual(c.length, n); assert(!r._readableState.flowing); then(); } @@ -85,7 +85,7 @@ function pipeLittle() { const w = new Writable(); let written = 0; w.on('finish', function() { - assert.equal(written, 200); + assert.strictEqual(written, 200); setImmediate(read1234); }); w._write = function(chunk, encoding, cb) { @@ -138,8 +138,8 @@ function pipe() { }; w.on('finish', function() { console.error('written', written, totalPushed); - assert.equal(written, expectEndingData); - assert.equal(totalPushed, expectTotalData); + assert.strictEqual(written, expectEndingData); + assert.strictEqual(totalPushed, expectTotalData); console.log('ok'); }); r.pipe(w); diff --git a/test/parallel/test-string-decoder-end.js b/test/parallel/test-string-decoder-end.js index 2c187d60142bbf..a04972e545bf1d 100644 --- a/test/parallel/test-string-decoder-end.js +++ b/test/parallel/test-string-decoder-end.js @@ -53,6 +53,6 @@ function testBuf(encoding, buf) { console.log('expect=%j', res3); console.log('res1=%j', res1); console.log('res2=%j', res2); - assert.equal(res1, res3, 'one byte at a time should match toString'); - assert.equal(res2, res3, 'all bytes at once should match toString'); + assert.strictEqual(res1, res3, 'one byte at a time should match toString'); + assert.strictEqual(res2, res3, 'all bytes at once should match toString'); } diff --git a/test/parallel/test-stringbytes-external.js b/test/parallel/test-stringbytes-external.js index a242b943c91a4d..94b58d9c6eadf0 100644 --- a/test/parallel/test-stringbytes-external.js +++ b/test/parallel/test-stringbytes-external.js @@ -13,14 +13,14 @@ let write_str = 'a'; let b = Buffer.from(write_str, 'ucs2'); // first check latin1 let c = b.toString('latin1'); -assert.equal(b[0], 0x61); -assert.equal(b[1], 0); -assert.equal(ucs2_control, c); +assert.strictEqual(b[0], 0x61); +assert.strictEqual(b[1], 0); +assert.strictEqual(ucs2_control, c); // now check binary c = b.toString('binary'); -assert.equal(b[0], 0x61); -assert.equal(b[1], 0); -assert.equal(ucs2_control, c); +assert.strictEqual(b[0], 0x61); +assert.strictEqual(b[1], 0); +assert.strictEqual(ucs2_control, c); // now create big strings const size = 1 + (1 << 20); @@ -31,8 +31,8 @@ ucs2_control = Array(size).join(ucs2_control); b = Buffer.from(write_str, 'ucs2'); // check fist Buffer created from write string for (let i = 0; i < b.length; i += 2) { - assert.equal(b[i], 0x61); - assert.equal(b[i + 1], 0); + assert.strictEqual(b[i], 0x61); + assert.strictEqual(b[i + 1], 0); } // create another string to create an external string @@ -40,25 +40,25 @@ const b_ucs = b.toString('ucs2'); // check control against external binary string const l_bin = b.toString('latin1'); -assert.equal(ucs2_control, l_bin); +assert.strictEqual(ucs2_control, l_bin); // check control against external binary string const b_bin = b.toString('binary'); -assert.equal(ucs2_control, b_bin); +assert.strictEqual(ucs2_control, b_bin); // create buffer copy from external const c_bin = Buffer.from(l_bin, 'latin1'); const c_ucs = Buffer.from(b_ucs, 'ucs2'); // make sure they're the same length -assert.equal(c_bin.length, c_ucs.length); +assert.strictEqual(c_bin.length, c_ucs.length); // make sure Buffers from externals are the same for (let i = 0; i < c_bin.length; i++) { - assert.equal(c_bin[i], c_ucs[i]); + assert.strictEqual(c_bin[i], c_ucs[i]); } // check resultant strings -assert.equal(c_bin.toString('ucs2'), c_ucs.toString('ucs2')); -assert.equal(c_bin.toString('latin1'), ucs2_control); -assert.equal(c_ucs.toString('latin1'), ucs2_control); +assert.strictEqual(c_bin.toString('ucs2'), c_ucs.toString('ucs2')); +assert.strictEqual(c_bin.toString('latin1'), ucs2_control); +assert.strictEqual(c_ucs.toString('latin1'), ucs2_control); // now let's test BASE64 and HEX ecoding/decoding diff --git a/test/parallel/test-sync-io-option.js b/test/parallel/test-sync-io-option.js index 6166bffc0bd68c..fb0b2333e82e4c 100644 --- a/test/parallel/test-sync-io-option.js +++ b/test/parallel/test-sync-io-option.js @@ -18,14 +18,14 @@ if (process.argv[2] === 'child') { args = execArgv.concat(args); if (!args[0]) args.shift(); execFile(process.execPath, args, function(err, stdout, stderr) { - assert.equal(err, null); - assert.equal(stdout, ''); + assert.strictEqual(err, null); + assert.strictEqual(stdout, ''); if (/WARNING[\s\S]*fs\.readFileSync/.test(stderr)) cntr++; if (args[0] === '--trace-sync-io') { - assert.equal(cntr, 1); + assert.strictEqual(cntr, 1); } else if (args[0] === __filename) { - assert.equal(cntr, 0); + assert.strictEqual(cntr, 0); } else { throw new Error('UNREACHABLE'); } diff --git a/test/parallel/test-tcp-wrap.js b/test/parallel/test-tcp-wrap.js index 6b9dbd90a4c113..aee0bcc8509fdf 100644 --- a/test/parallel/test-tcp-wrap.js +++ b/test/parallel/test-tcp-wrap.js @@ -9,12 +9,12 @@ const handle = new TCP(); // Should be able to bind to the port let err = handle.bind('0.0.0.0', 0); -assert.equal(err, 0); +assert.strictEqual(err, 0); // Should not be able to bind to the same port again const out = {}; handle.getsockname(out); err = handle.bind('0.0.0.0', out.port); -assert.equal(err, uv.UV_EINVAL); +assert.strictEqual(err, uv.UV_EINVAL); handle.close(); diff --git a/test/parallel/test-timers-reset-process-domain-on-throw.js b/test/parallel/test-timers-reset-process-domain-on-throw.js index 55e7ef57dcafc4..946ae715b0e193 100644 --- a/test/parallel/test-timers-reset-process-domain-on-throw.js +++ b/test/parallel/test-timers-reset-process-domain-on-throw.js @@ -28,7 +28,7 @@ function err() { function handleDomainError(e) { // In the domain's error handler, the current active domain should be the // domain within which the error was thrown. - assert.equal(process.domain, d); + assert.strictEqual(process.domain, d); } } diff --git a/test/parallel/test-timers-unref-active.js b/test/parallel/test-timers-unref-active.js index 8b1c89673bc35f..69f6d4e9f1bce4 100644 --- a/test/parallel/test-timers-unref-active.js +++ b/test/parallel/test-timers-unref-active.js @@ -47,5 +47,5 @@ someObject._onTimeout = function _onTimeout() { timers._unrefActive(someObject); setTimeout(function() { - assert.equal(nbTimeouts, N); + assert.strictEqual(nbTimeouts, N); }, TEST_DURATION); diff --git a/test/parallel/test-timers-unref-leak.js b/test/parallel/test-timers-unref-leak.js index d970910b24abe6..8eef00dd4ffe92 100644 --- a/test/parallel/test-timers-unref-leak.js +++ b/test/parallel/test-timers-unref-leak.js @@ -22,6 +22,6 @@ setTimeout(function() { }, 50); process.on('exit', function() { - assert.equal(called, 1); - assert.equal(closed, 1); + assert.strictEqual(called, 1); + assert.strictEqual(closed, 1); }); diff --git a/test/parallel/test-timers.js b/test/parallel/test-timers.js index 33f1706e3d399a..64a33515b1660c 100644 --- a/test/parallel/test-timers.js +++ b/test/parallel/test-timers.js @@ -46,7 +46,7 @@ inputs.forEach(function(value, index) { process.on('exit', function() { // assert that all timers have run inputs.forEach(function(value, index) { - assert.equal(true, timeouts[index]); - assert.equal(true, intervals[index]); + assert.strictEqual(true, timeouts[index]); + assert.strictEqual(true, intervals[index]); }); }); diff --git a/test/parallel/test-tls-cipher-list.js b/test/parallel/test-tls-cipher-list.js index 4acb30bc1c74bf..1533900f861177 100644 --- a/test/parallel/test-tls-cipher-list.js +++ b/test/parallel/test-tls-cipher-list.js @@ -21,7 +21,7 @@ function doCheck(arg, check) { .stdout.on('data', function(chunk) { out += chunk; }).on('end', function() { - assert.equal(out.trim(), check); + assert.strictEqual(out.trim(), check); }).on('error', common.fail); } diff --git a/test/parallel/test-tls-client-default-ciphers.js b/test/parallel/test-tls-client-default-ciphers.js index 618178d4a497ad..30095197b1c807 100644 --- a/test/parallel/test-tls-client-default-ciphers.js +++ b/test/parallel/test-tls-client-default-ciphers.js @@ -23,6 +23,6 @@ function test1() { } catch (e) { assert(e instanceof Done); } - assert.equal(ciphers, tls.DEFAULT_CIPHERS); + assert.strictEqual(ciphers, tls.DEFAULT_CIPHERS); } test1(); diff --git a/test/parallel/test-tls-client-getephemeralkeyinfo.js b/test/parallel/test-tls-client-getephemeralkeyinfo.js index b49d7131c47cf9..7d68046de9baae 100644 --- a/test/parallel/test-tls-client-getephemeralkeyinfo.js +++ b/test/parallel/test-tls-client-getephemeralkeyinfo.js @@ -93,6 +93,6 @@ function testECDHE512() { testNOT_PFS(); process.on('exit', function() { - assert.equal(ntests, nsuccess); - assert.equal(ntests, 5); + assert.strictEqual(ntests, nsuccess); + assert.strictEqual(ntests, 5); }); diff --git a/test/parallel/test-tls-client-mindhsize.js b/test/parallel/test-tls-client-mindhsize.js index 76e1034621f031..6bbf90030e85c2 100644 --- a/test/parallel/test-tls-client-mindhsize.js +++ b/test/parallel/test-tls-client-mindhsize.js @@ -88,6 +88,6 @@ assert.throws(() => test(512, true, common.fail), }); process.on('exit', function() { - assert.equal(nsuccess, 1); - assert.equal(nerror, 1); + assert.strictEqual(nsuccess, 1); + assert.strictEqual(nerror, 1); }); diff --git a/test/parallel/test-tls-client-verify.js b/test/parallel/test-tls-client-verify.js index 70d96ef1545ede..33d6c95fde50d3 100644 --- a/test/parallel/test-tls-client-verify.js +++ b/test/parallel/test-tls-client-verify.js @@ -130,5 +130,5 @@ runTest(0); process.on('exit', function() { console.log('successful tests: %d', successfulTests); - assert.equal(successfulTests, testCases.length); + assert.strictEqual(successfulTests, testCases.length); }); diff --git a/test/parallel/test-tls-delayed-attach.js b/test/parallel/test-tls-delayed-attach.js index d757ca756c3a09..9d2aca6a7d6c6f 100644 --- a/test/parallel/test-tls-delayed-attach.js +++ b/test/parallel/test-tls-delayed-attach.js @@ -44,5 +44,5 @@ const server = net.createServer(function(c) { }); process.on('exit', function() { - assert.equal(received, sent); + assert.strictEqual(received, sent); }); diff --git a/test/parallel/test-tls-dhe.js b/test/parallel/test-tls-dhe.js index 4bc81af6e1f8a2..1f3f73557a6a2a 100644 --- a/test/parallel/test-tls-dhe.js +++ b/test/parallel/test-tls-dhe.js @@ -90,6 +90,6 @@ function testError() { test1024(); process.on('exit', function() { - assert.equal(ntests, nsuccess); - assert.equal(ntests, 3); + assert.strictEqual(ntests, nsuccess); + assert.strictEqual(ntests, 3); }); diff --git a/test/parallel/test-tls-env-bad-extra-ca.js b/test/parallel/test-tls-env-bad-extra-ca.js index cb6c4ba489fcd6..9b42bbbbd5558e 100644 --- a/test/parallel/test-tls-env-bad-extra-ca.js +++ b/test/parallel/test-tls-env-bad-extra-ca.js @@ -30,7 +30,7 @@ let stderr = ''; fork(__filename, opts) .on('exit', common.mustCall(function(status) { - assert.equal(status, 0, 'client did not succeed in connecting'); + assert.strictEqual(status, 0, 'client did not succeed in connecting'); })) .on('close', common.mustCall(function() { assert(stderr.match(new RegExp( diff --git a/test/parallel/test-tls-env-extra-ca.js b/test/parallel/test-tls-env-extra-ca.js index 12e3272bd401a2..89f1b3a6c040d1 100644 --- a/test/parallel/test-tls-env-extra-ca.js +++ b/test/parallel/test-tls-env-extra-ca.js @@ -40,6 +40,6 @@ const server = tls.createServer(options, function(s) { }; fork(__filename, {env: env}).on('exit', common.mustCall(function(status) { - assert.equal(status, 0, 'client did not succeed in connecting'); + assert.strictEqual(status, 0, 'client did not succeed in connecting'); })); })); diff --git a/test/parallel/test-tls-honorcipherorder.js b/test/parallel/test-tls-honorcipherorder.js index f7894e46706da9..fdfc303146c1fa 100644 --- a/test/parallel/test-tls-honorcipherorder.js +++ b/test/parallel/test-tls-honorcipherorder.js @@ -17,7 +17,7 @@ const SSL_Method = 'TLSv1_2_method'; const localhost = '127.0.0.1'; process.on('exit', function() { - assert.equal(nconns, 6); + assert.strictEqual(nconns, 6); }); function test(honorCipherOrder, clientCipher, expectedCipher, cb) { @@ -50,7 +50,7 @@ function test(honorCipherOrder, clientCipher, expectedCipher, cb) { const cipher = client.getCipher(); client.end(); server.close(); - assert.equal(cipher.name, expectedCipher); + assert.strictEqual(cipher.name, expectedCipher); if (cb) cb(); }); }); diff --git a/test/parallel/test-tls-js-stream.js b/test/parallel/test-tls-js-stream.js index e1b580da303f8d..4e7cf618701173 100644 --- a/test/parallel/test-tls-js-stream.js +++ b/test/parallel/test-tls-js-stream.js @@ -71,6 +71,6 @@ const server = tls.createServer({ }); process.once('exit', function() { - assert.equal(connected.client, 1); - assert.equal(connected.server, 1); + assert.strictEqual(connected.client, 1); + assert.strictEqual(connected.server, 1); }); diff --git a/test/parallel/test-tls-no-rsa-key.js b/test/parallel/test-tls-no-rsa-key.js index 233d8453db1318..ed5c941b2d33ba 100644 --- a/test/parallel/test-tls-no-rsa-key.js +++ b/test/parallel/test-tls-no-rsa-key.js @@ -27,7 +27,7 @@ const server = tls.createServer(options, function(conn) { })); c.on('data', function(data) { - assert.equal(data, 'ok'); + assert.strictEqual(data.toString(), 'ok'); }); const cert = c.getPeerCertificate(); diff --git a/test/parallel/test-tls-npn-server-client.js b/test/parallel/test-tls-npn-server-client.js index 1b622cc8f72c20..3c69204d680d7c 100644 --- a/test/parallel/test-tls-npn-server-client.js +++ b/test/parallel/test-tls-npn-server-client.js @@ -98,10 +98,10 @@ function startTest() { } process.on('exit', function() { - assert.equal(serverResults[0], clientsResults[0]); - assert.equal(serverResults[1], clientsResults[1]); - assert.equal(serverResults[2], 'http/1.1'); - assert.equal(clientsResults[2], false); - assert.equal(serverResults[3], 'first-priority-unsupported'); - assert.equal(clientsResults[3], false); + assert.strictEqual(serverResults[0], clientsResults[0]); + assert.strictEqual(serverResults[1], clientsResults[1]); + assert.strictEqual(serverResults[2], 'http/1.1'); + assert.strictEqual(clientsResults[2], false); + assert.strictEqual(serverResults[3], 'first-priority-unsupported'); + assert.strictEqual(clientsResults[3], false); }); diff --git a/test/parallel/test-tls-over-http-tunnel.js b/test/parallel/test-tls-over-http-tunnel.js index 4e03bcaf537f26..a37913907b5b19 100644 --- a/test/parallel/test-tls-over-http-tunnel.js +++ b/test/parallel/test-tls-over-http-tunnel.js @@ -39,11 +39,12 @@ const proxy = net.createServer(function(clientSocket) { clientSocket.on('data', function(chunk) { if (!serverSocket) { // Verify the CONNECT request - assert.equal(`CONNECT localhost:${server.address().port} HTTP/1.1\r\n` + - 'Proxy-Connections: keep-alive\r\n' + - `Host: localhost:${proxy.address().port}\r\n` + - 'Connection: close\r\n\r\n', - chunk); + assert.strictEqual(`CONNECT localhost:${server.address().port} ` + + 'HTTP/1.1\r\n' + + 'Proxy-Connections: keep-alive\r\n' + + `Host: localhost:${proxy.address().port}\r\n` + + 'Connection: close\r\n\r\n', + chunk.toString()); console.log('PROXY: got CONNECT request'); console.log('PROXY: creating a tunnel'); @@ -107,7 +108,7 @@ proxy.listen(0, function() { } function onConnect(res, socket, header) { - assert.equal(200, res.statusCode); + assert.strictEqual(200, res.statusCode); console.log('CLIENT: got CONNECT response'); // detach the socket @@ -130,10 +131,10 @@ proxy.listen(0, function() { agent: false, rejectUnauthorized: false }, function(res) { - assert.equal(200, res.statusCode); + assert.strictEqual(200, res.statusCode); res.on('data', function(chunk) { - assert.equal('hello world\n', chunk); + assert.strictEqual('hello world\n', chunk.toString()); console.log('CLIENT: got HTTPS response'); gotRequest = true; }); diff --git a/test/parallel/test-tls-pause.js b/test/parallel/test-tls-pause.js index 911ea7097b1e70..c5b96b96dd675f 100644 --- a/test/parallel/test-tls-pause.js +++ b/test/parallel/test-tls-pause.js @@ -69,5 +69,5 @@ server.listen(0, function() { }); process.on('exit', function() { - assert.equal(sent, received); + assert.strictEqual(sent, received); }); diff --git a/test/parallel/test-tls-peer-certificate-encoding.js b/test/parallel/test-tls-peer-certificate-encoding.js index 545caf403e103c..1ae30974aeda83 100644 --- a/test/parallel/test-tls-peer-certificate-encoding.js +++ b/test/parallel/test-tls-peer-certificate-encoding.js @@ -29,7 +29,7 @@ server.listen(0, common.mustCall(function() { const peerCert = socket.getPeerCertificate(); console.error(util.inspect(peerCert)); - assert.equal(peerCert.subject.CN, 'Ádám Lippai'); + assert.strictEqual(peerCert.subject.CN, 'Ádám Lippai'); server.close(); })); socket.end('Hello'); diff --git a/test/parallel/test-tls-server-verify.js b/test/parallel/test-tls-server-verify.js index 58a58324fb383f..3b297dd4cea4d7 100644 --- a/test/parallel/test-tls-server-verify.js +++ b/test/parallel/test-tls-server-verify.js @@ -216,7 +216,7 @@ function runClient(prefix, port, options, cb) { //client.stdout.pipe(process.stdout); client.on('exit', function(code) { - //assert.equal(0, code, prefix + options.name + + //assert.strictEqual(0, code, prefix + options.name + // ": s_client exited with error code " + code); if (options.shouldReject) { assert.strictEqual(true, rejected, prefix + options.name + diff --git a/test/parallel/test-tls-session-cache.js b/test/parallel/test-tls-session-cache.js index 5e3ae5128ecfaf..0b2942215141e3 100644 --- a/test/parallel/test-tls-session-cache.js +++ b/test/parallel/test-tls-session-cache.js @@ -63,7 +63,7 @@ function doTest(testOptions, callback) { server.on('resumeSession', function(id, callback) { ++resumeCount; assert.ok(session); - assert.equal(session.id.toString('hex'), id.toString('hex')); + assert.strictEqual(session.id.toString('hex'), id.toString('hex')); // Just to check that async really works there setTimeout(function() { @@ -107,7 +107,7 @@ function doTest(testOptions, callback) { } common.fail(`code: ${code}, signal: ${signal}, output: ${err}`); } - assert.equal(code, 0); + assert.strictEqual(code, 0); server.close(common.mustCall(function() { setTimeout(callback, 100); })); @@ -119,13 +119,13 @@ function doTest(testOptions, callback) { process.on('exit', function() { if (testOptions.tickets) { - assert.equal(requestCount, 6); - assert.equal(resumeCount, 0); + assert.strictEqual(requestCount, 6); + assert.strictEqual(resumeCount, 0); } else { // initial request + reconnect requests (5 times) assert.ok(session); - assert.equal(requestCount, 6); - assert.equal(resumeCount, 5); + assert.strictEqual(requestCount, 6); + assert.strictEqual(resumeCount, 5); } }); } diff --git a/test/parallel/test-tls-socket-default-options.js b/test/parallel/test-tls-socket-default-options.js index 5c325570643225..dd62a41090c88e 100644 --- a/test/parallel/test-tls-socket-default-options.js +++ b/test/parallel/test-tls-socket-default-options.js @@ -28,7 +28,7 @@ function testSocketOptions(socket, socketOptions) { s.on('end', function() { server.close(); s.destroy(); - assert.equal(received, sent); + assert.strictEqual(received, sent); setImmediate(runTests); }); }).listen(0, function() { diff --git a/test/parallel/test-umask.js b/test/parallel/test-umask.js index 1c870893a3bced..7e4827a4cfc47d 100644 --- a/test/parallel/test-umask.js +++ b/test/parallel/test-umask.js @@ -12,10 +12,10 @@ if (common.isWindows) { const old = process.umask(mask); -assert.equal(parseInt(mask, 8), process.umask(old)); +assert.strictEqual(parseInt(mask, 8), process.umask(old)); // confirm reading the umask does not modify it. // 1. If the test fails, this call will succeed, but the mask will be set to 0 -assert.equal(old, process.umask()); +assert.strictEqual(old, process.umask()); // 2. If the test fails, process.umask() will return 0 -assert.equal(old, process.umask()); +assert.strictEqual(old, process.umask()); diff --git a/test/parallel/test-url.js b/test/parallel/test-url.js index 3a8c06c3ee4637..fa43e1fd5f1330 100644 --- a/test/parallel/test-url.js +++ b/test/parallel/test-url.js @@ -921,8 +921,8 @@ for (const u in parseTests) { expected = parseTests[u].href; actual = url.format(parseTests[u]); - assert.equal(actual, expected, - 'format(' + u + ') == ' + u + '\nactual:' + actual); + assert.strictEqual(actual, expected, + 'format(' + u + ') == ' + u + '\nactual:' + actual); } function createWithNoPrototype(properties = []) { @@ -1299,8 +1299,8 @@ const relativeTests = [ relativeTests.forEach(function(relativeTest) { const a = url.resolve(relativeTest[0], relativeTest[1]); const e = relativeTest[2]; - assert.equal(a, e, - 'resolve(' + [relativeTest[0], relativeTest[1]] + ') == ' + e + + assert.strictEqual(a, e, + 'resolve(' + [relativeTest[0], relativeTest[1]] + ') == ' + e + '\n actual=' + a); }); @@ -1631,8 +1631,8 @@ const relativeTests2 = [ relativeTests2.forEach(function(relativeTest) { const a = url.resolve(relativeTest[1], relativeTest[0]); const e = url.format(relativeTest[2]); - assert.equal(a, e, - 'resolve(' + [relativeTest[1], relativeTest[0]] + ') == ' + e + + assert.strictEqual(a, e, + 'resolve(' + [relativeTest[1], relativeTest[0]] + ') == ' + e + '\n actual=' + a); }); @@ -1650,8 +1650,8 @@ relativeTests.forEach(function(relativeTest) { expected = relativeTest[2]; actual = url.format(actual); - assert.equal(actual, expected, - 'format(' + actual + ') == ' + expected + '\nactual:' + actual); + assert.strictEqual(actual, expected, + 'format(' + actual + ') == ' + expected + '\nactual:' + actual); }); //format: [to, from, result] @@ -1681,8 +1681,8 @@ relativeTests2.forEach(function(relativeTest) { expected = url.format(relativeTest[2]); actual = url.format(actual); - assert.equal(actual, expected, - 'format(' + relativeTest[1] + ') == ' + expected + + assert.strictEqual(actual, expected, + 'format(' + relativeTest[1] + ') == ' + expected + '\nactual:' + actual); }); diff --git a/test/parallel/test-utf8-scripts.js b/test/parallel/test-utf8-scripts.js index 484d3bdefe5eda..e9d141d58abab0 100644 --- a/test/parallel/test-utf8-scripts.js +++ b/test/parallel/test-utf8-scripts.js @@ -6,4 +6,4 @@ const assert = require('assert'); console.log('Σὲ γνωρίζω ἀπὸ τὴν κόψη'); -assert.equal(true, /Hellö Wörld/.test('Hellö Wörld')); +assert.strictEqual(true, /Hellö Wörld/.test('Hellö Wörld')); diff --git a/test/parallel/test-util-log.js b/test/parallel/test-util-log.js index d45ebf2fc0b729..3604b42820063e 100644 --- a/test/parallel/test-util-log.js +++ b/test/parallel/test-util-log.js @@ -32,7 +32,7 @@ tests.forEach(function(test) { const re = (/[0-9]{1,2} [A-Z][a-z]{2} [0-9]{2}:[0-9]{2}:[0-9]{2} - (.+)$/); const match = re.exec(result); assert.ok(match); - assert.equal(match[1], test.output); + assert.strictEqual(match[1], test.output); }); global.process.stdout.write = stdout_write; diff --git a/test/parallel/test-util.js b/test/parallel/test-util.js index 0f5ee28e37b59c..3b7e78ea1e464e 100644 --- a/test/parallel/test-util.js +++ b/test/parallel/test-util.js @@ -5,78 +5,78 @@ const util = require('util'); const context = require('vm').runInNewContext; // isArray -assert.equal(true, util.isArray([])); -assert.equal(true, util.isArray(Array())); -assert.equal(true, util.isArray(new Array())); -assert.equal(true, util.isArray(new Array(5))); -assert.equal(true, util.isArray(new Array('with', 'some', 'entries'))); -assert.equal(true, util.isArray(context('Array')())); -assert.equal(false, util.isArray({})); -assert.equal(false, util.isArray({ push: function() {} })); -assert.equal(false, util.isArray(/regexp/)); -assert.equal(false, util.isArray(new Error())); -assert.equal(false, util.isArray(Object.create(Array.prototype))); +assert.strictEqual(true, util.isArray([])); +assert.strictEqual(true, util.isArray(Array())); +assert.strictEqual(true, util.isArray(new Array())); +assert.strictEqual(true, util.isArray(new Array(5))); +assert.strictEqual(true, util.isArray(new Array('with', 'some', 'entries'))); +assert.strictEqual(true, util.isArray(context('Array')())); +assert.strictEqual(false, util.isArray({})); +assert.strictEqual(false, util.isArray({ push: function() {} })); +assert.strictEqual(false, util.isArray(/regexp/)); +assert.strictEqual(false, util.isArray(new Error())); +assert.strictEqual(false, util.isArray(Object.create(Array.prototype))); // isRegExp -assert.equal(true, util.isRegExp(/regexp/)); -assert.equal(true, util.isRegExp(RegExp())); -assert.equal(true, util.isRegExp(new RegExp())); -assert.equal(true, util.isRegExp(context('RegExp')())); -assert.equal(false, util.isRegExp({})); -assert.equal(false, util.isRegExp([])); -assert.equal(false, util.isRegExp(new Date())); -assert.equal(false, util.isRegExp(Object.create(RegExp.prototype))); +assert.strictEqual(true, util.isRegExp(/regexp/)); +assert.strictEqual(true, util.isRegExp(RegExp())); +assert.strictEqual(true, util.isRegExp(new RegExp())); +assert.strictEqual(true, util.isRegExp(context('RegExp')())); +assert.strictEqual(false, util.isRegExp({})); +assert.strictEqual(false, util.isRegExp([])); +assert.strictEqual(false, util.isRegExp(new Date())); +assert.strictEqual(false, util.isRegExp(Object.create(RegExp.prototype))); // isDate -assert.equal(true, util.isDate(new Date())); -assert.equal(true, util.isDate(new Date(0))); +assert.strictEqual(true, util.isDate(new Date())); +assert.strictEqual(true, util.isDate(new Date(0))); // eslint-disable-next-line new-parens -assert.equal(true, util.isDate(new (context('Date')))); -assert.equal(false, util.isDate(Date())); -assert.equal(false, util.isDate({})); -assert.equal(false, util.isDate([])); -assert.equal(false, util.isDate(new Error())); -assert.equal(false, util.isDate(Object.create(Date.prototype))); +assert.strictEqual(true, util.isDate(new (context('Date')))); +assert.strictEqual(false, util.isDate(Date())); +assert.strictEqual(false, util.isDate({})); +assert.strictEqual(false, util.isDate([])); +assert.strictEqual(false, util.isDate(new Error())); +assert.strictEqual(false, util.isDate(Object.create(Date.prototype))); // isError -assert.equal(true, util.isError(new Error())); -assert.equal(true, util.isError(new TypeError())); -assert.equal(true, util.isError(new SyntaxError())); +assert.strictEqual(true, util.isError(new Error())); +assert.strictEqual(true, util.isError(new TypeError())); +assert.strictEqual(true, util.isError(new SyntaxError())); /* eslint-disable new-parens */ -assert.equal(true, util.isError(new (context('Error')))); -assert.equal(true, util.isError(new (context('TypeError')))); -assert.equal(true, util.isError(new (context('SyntaxError')))); +assert.strictEqual(true, util.isError(new (context('Error')))); +assert.strictEqual(true, util.isError(new (context('TypeError')))); +assert.strictEqual(true, util.isError(new (context('SyntaxError')))); /* eslint-enable */ -assert.equal(false, util.isError({})); -assert.equal(false, util.isError({ name: 'Error', message: '' })); -assert.equal(false, util.isError([])); -assert.equal(true, util.isError(Object.create(Error.prototype))); +assert.strictEqual(false, util.isError({})); +assert.strictEqual(false, util.isError({ name: 'Error', message: '' })); +assert.strictEqual(false, util.isError([])); +assert.strictEqual(true, util.isError(Object.create(Error.prototype))); // isObject assert.ok(util.isObject({}) === true); // isPrimitive -assert.equal(false, util.isPrimitive({})); -assert.equal(false, util.isPrimitive(new Error())); -assert.equal(false, util.isPrimitive(new Date())); -assert.equal(false, util.isPrimitive([])); -assert.equal(false, util.isPrimitive(/regexp/)); -assert.equal(false, util.isPrimitive(function() {})); -assert.equal(false, util.isPrimitive(new Number(1))); -assert.equal(false, util.isPrimitive(new String('bla'))); -assert.equal(false, util.isPrimitive(new Boolean(true))); -assert.equal(true, util.isPrimitive(1)); -assert.equal(true, util.isPrimitive('bla')); -assert.equal(true, util.isPrimitive(true)); -assert.equal(true, util.isPrimitive(undefined)); -assert.equal(true, util.isPrimitive(null)); -assert.equal(true, util.isPrimitive(Infinity)); -assert.equal(true, util.isPrimitive(NaN)); -assert.equal(true, util.isPrimitive(Symbol('symbol'))); +assert.strictEqual(false, util.isPrimitive({})); +assert.strictEqual(false, util.isPrimitive(new Error())); +assert.strictEqual(false, util.isPrimitive(new Date())); +assert.strictEqual(false, util.isPrimitive([])); +assert.strictEqual(false, util.isPrimitive(/regexp/)); +assert.strictEqual(false, util.isPrimitive(function() {})); +assert.strictEqual(false, util.isPrimitive(new Number(1))); +assert.strictEqual(false, util.isPrimitive(new String('bla'))); +assert.strictEqual(false, util.isPrimitive(new Boolean(true))); +assert.strictEqual(true, util.isPrimitive(1)); +assert.strictEqual(true, util.isPrimitive('bla')); +assert.strictEqual(true, util.isPrimitive(true)); +assert.strictEqual(true, util.isPrimitive(undefined)); +assert.strictEqual(true, util.isPrimitive(null)); +assert.strictEqual(true, util.isPrimitive(Infinity)); +assert.strictEqual(true, util.isPrimitive(NaN)); +assert.strictEqual(true, util.isPrimitive(Symbol('symbol'))); // isBuffer -assert.equal(false, util.isBuffer('foo')); -assert.equal(true, util.isBuffer(Buffer.from('foo'))); +assert.strictEqual(false, util.isBuffer('foo')); +assert.strictEqual(true, util.isBuffer(Buffer.from('foo'))); // _extend assert.deepStrictEqual(util._extend({a: 1}), {a: 1}); diff --git a/test/parallel/test-v8-stats.js b/test/parallel/test-v8-stats.js index 5b756f35962525..02182e2816bbc7 100644 --- a/test/parallel/test-v8-stats.js +++ b/test/parallel/test-v8-stats.js @@ -16,7 +16,7 @@ const keys = [ 'used_heap_size']; assert.deepStrictEqual(Object.keys(s).sort(), keys); keys.forEach(function(key) { - assert.equal(typeof s[key], 'number'); + assert.strictEqual(typeof s[key], 'number'); }); diff --git a/test/parallel/test-vm-cached-data.js b/test/parallel/test-vm-cached-data.js index 35ab236ae1eb98..3f74f398b814ca 100644 --- a/test/parallel/test-vm-cached-data.js +++ b/test/parallel/test-vm-cached-data.js @@ -32,7 +32,7 @@ function produce(source, count) { console.log(data); `, source]); - assert.equal(out.status, 0, out.stderr + ''); + assert.strictEqual(out.status, 0, out.stderr + ''); return Buffer.from(out.stdout.toString(), 'base64'); } @@ -47,7 +47,7 @@ function testProduceConsume() { cachedData: data }); assert(!script.cachedDataRejected); - assert.equal(script.runInThisContext()(), 'original'); + assert.strictEqual(script.runInThisContext()(), 'original'); } testProduceConsume(); @@ -68,7 +68,7 @@ function testRejectInvalid() { cachedData: data }); assert(script.cachedDataRejected); - assert.equal(script.runInThisContext()(), 'invalid_1'); + assert.strictEqual(script.runInThisContext()(), 'invalid_1'); } testRejectInvalid(); diff --git a/test/parallel/test-vm-context.js b/test/parallel/test-vm-context.js index e4f6960259abe2..7056ce7be35d05 100644 --- a/test/parallel/test-vm-context.js +++ b/test/parallel/test-vm-context.js @@ -9,18 +9,18 @@ let script = new Script('"passed";'); console.error('run in a new empty context'); let context = vm.createContext(); let result = script.runInContext(context); -assert.equal('passed', result); +assert.strictEqual('passed', result); console.error('create a new pre-populated context'); context = vm.createContext({'foo': 'bar', 'thing': 'lala'}); -assert.equal('bar', context.foo); -assert.equal('lala', context.thing); +assert.strictEqual('bar', context.foo); +assert.strictEqual('lala', context.thing); console.error('test updating context'); script = new Script('foo = 3;'); result = script.runInContext(context); -assert.equal(3, context.foo); -assert.equal('lala', context.thing); +assert.strictEqual(3, context.foo); +assert.strictEqual('lala', context.thing); // Issue GH-227: assert.throws(function() { @@ -58,7 +58,7 @@ script = vm.createScript('delete b'); let ctx = {}; Object.defineProperty(ctx, 'b', { configurable: false }); ctx = vm.createContext(ctx); -assert.equal(script.runInContext(ctx), false); +assert.strictEqual(script.runInContext(ctx), false); // Error on the first line of a module should // have the correct line and column number diff --git a/test/parallel/test-vm-create-and-run-in-context.js b/test/parallel/test-vm-create-and-run-in-context.js index a0026102b578f8..7fd3f1d70436ad 100644 --- a/test/parallel/test-vm-create-and-run-in-context.js +++ b/test/parallel/test-vm-create-and-run-in-context.js @@ -8,17 +8,17 @@ const vm = require('vm'); console.error('run in a new empty context'); let context = vm.createContext(); let result = vm.runInContext('"passed";', context); -assert.equal('passed', result); +assert.strictEqual('passed', result); console.error('create a new pre-populated context'); context = vm.createContext({'foo': 'bar', 'thing': 'lala'}); -assert.equal('bar', context.foo); -assert.equal('lala', context.thing); +assert.strictEqual('bar', context.foo); +assert.strictEqual('lala', context.thing); console.error('test updating context'); result = vm.runInContext('var foo = 3;', context); -assert.equal(3, context.foo); -assert.equal('lala', context.thing); +assert.strictEqual(3, context.foo); +assert.strictEqual('lala', context.thing); // https://github.com/nodejs/node/issues/5768 console.error('run in contextified sandbox without referencing the context'); diff --git a/test/parallel/test-vm-create-context-circular-reference.js b/test/parallel/test-vm-create-context-circular-reference.js index 13680c4c4e11ef..1d7be0db9fdaf4 100644 --- a/test/parallel/test-vm-create-context-circular-reference.js +++ b/test/parallel/test-vm-create-context-circular-reference.js @@ -10,4 +10,4 @@ sbx = vm.createContext(sbx); sbx.test = 123; -assert.equal(sbx.window.window.window.window.window.test, 123); +assert.strictEqual(sbx.window.window.window.window.window.test, 123); diff --git a/test/parallel/test-vm-function-declaration.js b/test/parallel/test-vm-function-declaration.js index 9f27723a0421a9..668b29885c44cf 100644 --- a/test/parallel/test-vm-function-declaration.js +++ b/test/parallel/test-vm-function-declaration.js @@ -18,10 +18,10 @@ code += '(function(){return this})().b;\n'; const res = vm.runInContext(code, o, 'test'); -assert.equal(typeof res, 'function', 'result should be function'); -assert.equal(res.name, 'b', 'res should be named b'); -assert.equal(typeof o.a, 'function', 'a should be function'); -assert.equal(typeof o.b, 'function', 'b should be function'); -assert.equal(res, o.b, 'result should be global b function'); +assert.strictEqual(typeof res, 'function', 'result should be function'); +assert.strictEqual(res.name, 'b', 'res should be named b'); +assert.strictEqual(typeof o.a, 'function', 'a should be function'); +assert.strictEqual(typeof o.b, 'function', 'b should be function'); +assert.strictEqual(res, o.b, 'result should be global b function'); console.log('ok'); diff --git a/test/parallel/test-vm-global-define-property.js b/test/parallel/test-vm-global-define-property.js index 62a714615ddc31..83f6073d1ceaf1 100644 --- a/test/parallel/test-vm-global-define-property.js +++ b/test/parallel/test-vm-global-define-property.js @@ -20,7 +20,7 @@ const o = vm.createContext({ console: console, x: x }); const res = vm.runInContext(code, o, 'test'); assert(res); -assert.equal(typeof res, 'object'); -assert.equal(res, x); -assert.equal(o.f, res); +assert.strictEqual(typeof res, 'object'); +assert.strictEqual(res, x); +assert.strictEqual(o.f, res); assert.deepStrictEqual(Object.keys(o), ['console', 'x', 'g', 'f']); diff --git a/test/parallel/test-vm-new-script-new-context.js b/test/parallel/test-vm-new-script-new-context.js index a02627668f6db7..693a041138602f 100644 --- a/test/parallel/test-vm-new-script-new-context.js +++ b/test/parallel/test-vm-new-script-new-context.js @@ -10,8 +10,8 @@ let script = new Script('\'passed\';'); console.error('script created'); const result1 = script.runInNewContext(); const result2 = script.runInNewContext(); -assert.equal('passed', result1); -assert.equal('passed', result2); +assert.strictEqual('passed', result1); +assert.strictEqual('passed', result2); console.error('thrown error'); script = new Script('throw new Error(\'test\');'); @@ -30,7 +30,7 @@ assert.throws(function() { global.hello = 5; script = new Script('hello = 2'); script.runInNewContext(); -assert.equal(5, global.hello); +assert.strictEqual(5, global.hello); console.error('pass values in and out'); @@ -43,21 +43,21 @@ script = new Script(global.code); /* eslint-disable no-unused-vars */ const baz = script.runInNewContext(global.obj); /* eslint-enable no-unused-vars */ -assert.equal(1, global.obj.foo); -assert.equal(2, global.obj.bar); -assert.equal(2, global.foo); +assert.strictEqual(1, global.obj.foo); +assert.strictEqual(2, global.obj.bar); +assert.strictEqual(2, global.foo); console.error('call a function by reference'); script = new Script('f()'); function changeFoo() { global.foo = 100; } script.runInNewContext({ f: changeFoo }); -assert.equal(global.foo, 100); +assert.strictEqual(global.foo, 100); console.error('modify an object by reference'); script = new Script('f.a = 2'); const f = { a: 1 }; script.runInNewContext({ f: f }); -assert.equal(f.a, 2); +assert.strictEqual(f.a, 2); assert.throws(function() { script.runInNewContext(); diff --git a/test/parallel/test-vm-new-script-this-context.js b/test/parallel/test-vm-new-script-this-context.js index fb7e2719855174..3df5dc1b5020d5 100644 --- a/test/parallel/test-vm-new-script-this-context.js +++ b/test/parallel/test-vm-new-script-this-context.js @@ -8,7 +8,7 @@ common.globalCheck = false; console.error('run a string'); let script = new Script('\'passed\';'); const result = script.runInThisContext(script); -assert.equal('passed', result); +assert.strictEqual('passed', result); console.error('thrown error'); script = new Script('throw new Error(\'test\');'); @@ -19,7 +19,7 @@ assert.throws(function() { global.hello = 5; script = new Script('hello = 2'); script.runInThisContext(script); -assert.equal(2, global.hello); +assert.strictEqual(2, global.hello); console.error('pass values'); @@ -30,12 +30,12 @@ global.foo = 2; global.obj = { foo: 0, baz: 3 }; script = new Script(global.code); script.runInThisContext(script); -assert.equal(0, global.obj.foo); -assert.equal(2, global.bar); -assert.equal(1, global.foo); +assert.strictEqual(0, global.obj.foo); +assert.strictEqual(2, global.bar); +assert.strictEqual(1, global.foo); console.error('call a function'); global.f = function() { global.foo = 100; }; script = new Script('f()'); script.runInThisContext(script); -assert.equal(100, global.foo); +assert.strictEqual(100, global.foo); diff --git a/test/parallel/test-vm-run-in-new-context.js b/test/parallel/test-vm-run-in-new-context.js index b00e5a973e0d25..7b096ffc3fdc5f 100644 --- a/test/parallel/test-vm-run-in-new-context.js +++ b/test/parallel/test-vm-run-in-new-context.js @@ -5,13 +5,14 @@ const common = require('../common'); const assert = require('assert'); const vm = require('vm'); -assert.equal(typeof global.gc, 'function', 'Run this test with --expose-gc'); +assert.strictEqual(typeof global.gc, 'function', + 'Run this test with --expose-gc'); common.globalCheck = false; console.error('run a string'); const result = vm.runInNewContext('\'passed\';'); -assert.equal('passed', result); +assert.strictEqual('passed', result); console.error('thrown error'); assert.throws(function() { @@ -20,7 +21,7 @@ assert.throws(function() { global.hello = 5; vm.runInNewContext('hello = 2'); -assert.equal(5, global.hello); +assert.strictEqual(5, global.hello); console.error('pass values in and out'); @@ -32,19 +33,19 @@ global.obj = { foo: 0, baz: 3 }; /* eslint-disable no-unused-vars */ const baz = vm.runInNewContext(global.code, global.obj); /* eslint-enable no-unused-vars */ -assert.equal(1, global.obj.foo); -assert.equal(2, global.obj.bar); -assert.equal(2, global.foo); +assert.strictEqual(1, global.obj.foo); +assert.strictEqual(2, global.obj.bar); +assert.strictEqual(2, global.foo); console.error('call a function by reference'); function changeFoo() { global.foo = 100; } vm.runInNewContext('f()', { f: changeFoo }); -assert.equal(global.foo, 100); +assert.strictEqual(global.foo, 100); console.error('modify an object by reference'); const f = { a: 1 }; vm.runInNewContext('f.a = 2', { f: f }); -assert.equal(f.a, 2); +assert.strictEqual(f.a, 2); console.error('use function in context without referencing context'); const fn = vm.runInNewContext('(function() { obj.p = {}; })', { obj: {} }); diff --git a/test/parallel/test-vm-syntax-error-message.js b/test/parallel/test-vm-syntax-error-message.js index 1a97393d6d97a7..c0a00d06aa54f8 100644 --- a/test/parallel/test-vm-syntax-error-message.js +++ b/test/parallel/test-vm-syntax-error-message.js @@ -22,5 +22,5 @@ p.stdout.on('data', function(data) { }); process.on('exit', function() { - assert.equal(output.replace(/[\r\n]+/g, ''), 'boo'); + assert.strictEqual(output.replace(/[\r\n]+/g, ''), 'boo'); }); diff --git a/test/parallel/test-whatwg-url-setters.js b/test/parallel/test-whatwg-url-setters.js index dfaeb6e4ac2fd0..8cd9fc51d52ae8 100644 --- a/test/parallel/test-whatwg-url-setters.js +++ b/test/parallel/test-whatwg-url-setters.js @@ -24,8 +24,9 @@ for (const attr in attrs) { const url = new URL(test.href); url[attr] = test.new_value; for (const test_attr in test.expected) { - assert.equal(test.expected[test_attr], url[test_attr], - `${n} ${attr} ${test_attr} ${test.href} ${test.comment}`); + assert.strictEqual(test.expected[test_attr], url[test_attr], + `${n} ${attr} ${test_attr} ` + + `${test.href} ${test.comment}`); } } } diff --git a/test/parallel/test-writedouble.js b/test/parallel/test-writedouble.js index 935f9e7ae08ffd..fa9c94022d419b 100644 --- a/test/parallel/test-writedouble.js +++ b/test/parallel/test-writedouble.js @@ -10,140 +10,140 @@ function test(clazz) { buffer.writeDoubleBE(2.225073858507201e-308, 0); buffer.writeDoubleLE(2.225073858507201e-308, 8); - assert.equal(0x00, buffer[0]); - assert.equal(0x0f, buffer[1]); - assert.equal(0xff, buffer[2]); - assert.equal(0xff, buffer[3]); - assert.equal(0xff, buffer[4]); - assert.equal(0xff, buffer[5]); - assert.equal(0xff, buffer[6]); - assert.equal(0xff, buffer[7]); - assert.equal(0xff, buffer[8]); - assert.equal(0xff, buffer[9]); - assert.equal(0xff, buffer[10]); - assert.equal(0xff, buffer[11]); - assert.equal(0xff, buffer[12]); - assert.equal(0xff, buffer[13]); - assert.equal(0x0f, buffer[14]); - assert.equal(0x00, buffer[15]); + assert.strictEqual(0x00, buffer[0]); + assert.strictEqual(0x0f, buffer[1]); + assert.strictEqual(0xff, buffer[2]); + assert.strictEqual(0xff, buffer[3]); + assert.strictEqual(0xff, buffer[4]); + assert.strictEqual(0xff, buffer[5]); + assert.strictEqual(0xff, buffer[6]); + assert.strictEqual(0xff, buffer[7]); + assert.strictEqual(0xff, buffer[8]); + assert.strictEqual(0xff, buffer[9]); + assert.strictEqual(0xff, buffer[10]); + assert.strictEqual(0xff, buffer[11]); + assert.strictEqual(0xff, buffer[12]); + assert.strictEqual(0xff, buffer[13]); + assert.strictEqual(0x0f, buffer[14]); + assert.strictEqual(0x00, buffer[15]); buffer.writeDoubleBE(1.0000000000000004, 0); buffer.writeDoubleLE(1.0000000000000004, 8); - assert.equal(0x3f, buffer[0]); - assert.equal(0xf0, buffer[1]); - assert.equal(0x00, buffer[2]); - assert.equal(0x00, buffer[3]); - assert.equal(0x00, buffer[4]); - assert.equal(0x00, buffer[5]); - assert.equal(0x00, buffer[6]); - assert.equal(0x02, buffer[7]); - assert.equal(0x02, buffer[8]); - assert.equal(0x00, buffer[9]); - assert.equal(0x00, buffer[10]); - assert.equal(0x00, buffer[11]); - assert.equal(0x00, buffer[12]); - assert.equal(0x00, buffer[13]); - assert.equal(0xf0, buffer[14]); - assert.equal(0x3f, buffer[15]); + assert.strictEqual(0x3f, buffer[0]); + assert.strictEqual(0xf0, buffer[1]); + assert.strictEqual(0x00, buffer[2]); + assert.strictEqual(0x00, buffer[3]); + assert.strictEqual(0x00, buffer[4]); + assert.strictEqual(0x00, buffer[5]); + assert.strictEqual(0x00, buffer[6]); + assert.strictEqual(0x02, buffer[7]); + assert.strictEqual(0x02, buffer[8]); + assert.strictEqual(0x00, buffer[9]); + assert.strictEqual(0x00, buffer[10]); + assert.strictEqual(0x00, buffer[11]); + assert.strictEqual(0x00, buffer[12]); + assert.strictEqual(0x00, buffer[13]); + assert.strictEqual(0xf0, buffer[14]); + assert.strictEqual(0x3f, buffer[15]); buffer.writeDoubleBE(-2, 0); buffer.writeDoubleLE(-2, 8); - assert.equal(0xc0, buffer[0]); - assert.equal(0x00, buffer[1]); - assert.equal(0x00, buffer[2]); - assert.equal(0x00, buffer[3]); - assert.equal(0x00, buffer[4]); - assert.equal(0x00, buffer[5]); - assert.equal(0x00, buffer[6]); - assert.equal(0x00, buffer[7]); - assert.equal(0x00, buffer[8]); - assert.equal(0x00, buffer[9]); - assert.equal(0x00, buffer[10]); - assert.equal(0x00, buffer[11]); - assert.equal(0x00, buffer[12]); - assert.equal(0x00, buffer[13]); - assert.equal(0x00, buffer[14]); - assert.equal(0xc0, buffer[15]); + assert.strictEqual(0xc0, buffer[0]); + assert.strictEqual(0x00, buffer[1]); + assert.strictEqual(0x00, buffer[2]); + assert.strictEqual(0x00, buffer[3]); + assert.strictEqual(0x00, buffer[4]); + assert.strictEqual(0x00, buffer[5]); + assert.strictEqual(0x00, buffer[6]); + assert.strictEqual(0x00, buffer[7]); + assert.strictEqual(0x00, buffer[8]); + assert.strictEqual(0x00, buffer[9]); + assert.strictEqual(0x00, buffer[10]); + assert.strictEqual(0x00, buffer[11]); + assert.strictEqual(0x00, buffer[12]); + assert.strictEqual(0x00, buffer[13]); + assert.strictEqual(0x00, buffer[14]); + assert.strictEqual(0xc0, buffer[15]); buffer.writeDoubleBE(1.7976931348623157e+308, 0); buffer.writeDoubleLE(1.7976931348623157e+308, 8); - assert.equal(0x7f, buffer[0]); - assert.equal(0xef, buffer[1]); - assert.equal(0xff, buffer[2]); - assert.equal(0xff, buffer[3]); - assert.equal(0xff, buffer[4]); - assert.equal(0xff, buffer[5]); - assert.equal(0xff, buffer[6]); - assert.equal(0xff, buffer[7]); - assert.equal(0xff, buffer[8]); - assert.equal(0xff, buffer[9]); - assert.equal(0xff, buffer[10]); - assert.equal(0xff, buffer[11]); - assert.equal(0xff, buffer[12]); - assert.equal(0xff, buffer[13]); - assert.equal(0xef, buffer[14]); - assert.equal(0x7f, buffer[15]); + assert.strictEqual(0x7f, buffer[0]); + assert.strictEqual(0xef, buffer[1]); + assert.strictEqual(0xff, buffer[2]); + assert.strictEqual(0xff, buffer[3]); + assert.strictEqual(0xff, buffer[4]); + assert.strictEqual(0xff, buffer[5]); + assert.strictEqual(0xff, buffer[6]); + assert.strictEqual(0xff, buffer[7]); + assert.strictEqual(0xff, buffer[8]); + assert.strictEqual(0xff, buffer[9]); + assert.strictEqual(0xff, buffer[10]); + assert.strictEqual(0xff, buffer[11]); + assert.strictEqual(0xff, buffer[12]); + assert.strictEqual(0xff, buffer[13]); + assert.strictEqual(0xef, buffer[14]); + assert.strictEqual(0x7f, buffer[15]); buffer.writeDoubleBE(0 * -1, 0); buffer.writeDoubleLE(0 * -1, 8); - assert.equal(0x80, buffer[0]); - assert.equal(0x00, buffer[1]); - assert.equal(0x00, buffer[2]); - assert.equal(0x00, buffer[3]); - assert.equal(0x00, buffer[4]); - assert.equal(0x00, buffer[5]); - assert.equal(0x00, buffer[6]); - assert.equal(0x00, buffer[7]); - assert.equal(0x00, buffer[8]); - assert.equal(0x00, buffer[9]); - assert.equal(0x00, buffer[10]); - assert.equal(0x00, buffer[11]); - assert.equal(0x00, buffer[12]); - assert.equal(0x00, buffer[13]); - assert.equal(0x00, buffer[14]); - assert.equal(0x80, buffer[15]); + assert.strictEqual(0x80, buffer[0]); + assert.strictEqual(0x00, buffer[1]); + assert.strictEqual(0x00, buffer[2]); + assert.strictEqual(0x00, buffer[3]); + assert.strictEqual(0x00, buffer[4]); + assert.strictEqual(0x00, buffer[5]); + assert.strictEqual(0x00, buffer[6]); + assert.strictEqual(0x00, buffer[7]); + assert.strictEqual(0x00, buffer[8]); + assert.strictEqual(0x00, buffer[9]); + assert.strictEqual(0x00, buffer[10]); + assert.strictEqual(0x00, buffer[11]); + assert.strictEqual(0x00, buffer[12]); + assert.strictEqual(0x00, buffer[13]); + assert.strictEqual(0x00, buffer[14]); + assert.strictEqual(0x80, buffer[15]); buffer.writeDoubleBE(Infinity, 0); buffer.writeDoubleLE(Infinity, 8); - assert.equal(0x7F, buffer[0]); - assert.equal(0xF0, buffer[1]); - assert.equal(0x00, buffer[2]); - assert.equal(0x00, buffer[3]); - assert.equal(0x00, buffer[4]); - assert.equal(0x00, buffer[5]); - assert.equal(0x00, buffer[6]); - assert.equal(0x00, buffer[7]); - assert.equal(0x00, buffer[8]); - assert.equal(0x00, buffer[9]); - assert.equal(0x00, buffer[10]); - assert.equal(0x00, buffer[11]); - assert.equal(0x00, buffer[12]); - assert.equal(0x00, buffer[13]); - assert.equal(0xF0, buffer[14]); - assert.equal(0x7F, buffer[15]); - assert.equal(Infinity, buffer.readDoubleBE(0)); - assert.equal(Infinity, buffer.readDoubleLE(8)); + assert.strictEqual(0x7F, buffer[0]); + assert.strictEqual(0xF0, buffer[1]); + assert.strictEqual(0x00, buffer[2]); + assert.strictEqual(0x00, buffer[3]); + assert.strictEqual(0x00, buffer[4]); + assert.strictEqual(0x00, buffer[5]); + assert.strictEqual(0x00, buffer[6]); + assert.strictEqual(0x00, buffer[7]); + assert.strictEqual(0x00, buffer[8]); + assert.strictEqual(0x00, buffer[9]); + assert.strictEqual(0x00, buffer[10]); + assert.strictEqual(0x00, buffer[11]); + assert.strictEqual(0x00, buffer[12]); + assert.strictEqual(0x00, buffer[13]); + assert.strictEqual(0xF0, buffer[14]); + assert.strictEqual(0x7F, buffer[15]); + assert.strictEqual(Infinity, buffer.readDoubleBE(0)); + assert.strictEqual(Infinity, buffer.readDoubleLE(8)); buffer.writeDoubleBE(-Infinity, 0); buffer.writeDoubleLE(-Infinity, 8); - assert.equal(0xFF, buffer[0]); - assert.equal(0xF0, buffer[1]); - assert.equal(0x00, buffer[2]); - assert.equal(0x00, buffer[3]); - assert.equal(0x00, buffer[4]); - assert.equal(0x00, buffer[5]); - assert.equal(0x00, buffer[6]); - assert.equal(0x00, buffer[7]); - assert.equal(0x00, buffer[8]); - assert.equal(0x00, buffer[9]); - assert.equal(0x00, buffer[10]); - assert.equal(0x00, buffer[11]); - assert.equal(0x00, buffer[12]); - assert.equal(0x00, buffer[13]); - assert.equal(0xF0, buffer[14]); - assert.equal(0xFF, buffer[15]); - assert.equal(-Infinity, buffer.readDoubleBE(0)); - assert.equal(-Infinity, buffer.readDoubleLE(8)); + assert.strictEqual(0xFF, buffer[0]); + assert.strictEqual(0xF0, buffer[1]); + assert.strictEqual(0x00, buffer[2]); + assert.strictEqual(0x00, buffer[3]); + assert.strictEqual(0x00, buffer[4]); + assert.strictEqual(0x00, buffer[5]); + assert.strictEqual(0x00, buffer[6]); + assert.strictEqual(0x00, buffer[7]); + assert.strictEqual(0x00, buffer[8]); + assert.strictEqual(0x00, buffer[9]); + assert.strictEqual(0x00, buffer[10]); + assert.strictEqual(0x00, buffer[11]); + assert.strictEqual(0x00, buffer[12]); + assert.strictEqual(0x00, buffer[13]); + assert.strictEqual(0xF0, buffer[14]); + assert.strictEqual(0xFF, buffer[15]); + assert.strictEqual(-Infinity, buffer.readDoubleBE(0)); + assert.strictEqual(-Infinity, buffer.readDoubleLE(8)); buffer.writeDoubleBE(NaN, 0); buffer.writeDoubleLE(NaN, 8); diff --git a/test/parallel/test-writefloat.js b/test/parallel/test-writefloat.js index 113e97c6d333b7..aeb62c8c022484 100644 --- a/test/parallel/test-writefloat.js +++ b/test/parallel/test-writefloat.js @@ -10,86 +10,86 @@ function test(clazz) { buffer.writeFloatBE(1, 0); buffer.writeFloatLE(1, 4); - assert.equal(0x3f, buffer[0]); - assert.equal(0x80, buffer[1]); - assert.equal(0x00, buffer[2]); - assert.equal(0x00, buffer[3]); - assert.equal(0x00, buffer[4]); - assert.equal(0x00, buffer[5]); - assert.equal(0x80, buffer[6]); - assert.equal(0x3f, buffer[7]); + assert.strictEqual(0x3f, buffer[0]); + assert.strictEqual(0x80, buffer[1]); + assert.strictEqual(0x00, buffer[2]); + assert.strictEqual(0x00, buffer[3]); + assert.strictEqual(0x00, buffer[4]); + assert.strictEqual(0x00, buffer[5]); + assert.strictEqual(0x80, buffer[6]); + assert.strictEqual(0x3f, buffer[7]); buffer.writeFloatBE(1 / 3, 0); buffer.writeFloatLE(1 / 3, 4); - assert.equal(0x3e, buffer[0]); - assert.equal(0xaa, buffer[1]); - assert.equal(0xaa, buffer[2]); - assert.equal(0xab, buffer[3]); - assert.equal(0xab, buffer[4]); - assert.equal(0xaa, buffer[5]); - assert.equal(0xaa, buffer[6]); - assert.equal(0x3e, buffer[7]); + assert.strictEqual(0x3e, buffer[0]); + assert.strictEqual(0xaa, buffer[1]); + assert.strictEqual(0xaa, buffer[2]); + assert.strictEqual(0xab, buffer[3]); + assert.strictEqual(0xab, buffer[4]); + assert.strictEqual(0xaa, buffer[5]); + assert.strictEqual(0xaa, buffer[6]); + assert.strictEqual(0x3e, buffer[7]); buffer.writeFloatBE(3.4028234663852886e+38, 0); buffer.writeFloatLE(3.4028234663852886e+38, 4); - assert.equal(0x7f, buffer[0]); - assert.equal(0x7f, buffer[1]); - assert.equal(0xff, buffer[2]); - assert.equal(0xff, buffer[3]); - assert.equal(0xff, buffer[4]); - assert.equal(0xff, buffer[5]); - assert.equal(0x7f, buffer[6]); - assert.equal(0x7f, buffer[7]); + assert.strictEqual(0x7f, buffer[0]); + assert.strictEqual(0x7f, buffer[1]); + assert.strictEqual(0xff, buffer[2]); + assert.strictEqual(0xff, buffer[3]); + assert.strictEqual(0xff, buffer[4]); + assert.strictEqual(0xff, buffer[5]); + assert.strictEqual(0x7f, buffer[6]); + assert.strictEqual(0x7f, buffer[7]); buffer.writeFloatLE(1.1754943508222875e-38, 0); buffer.writeFloatBE(1.1754943508222875e-38, 4); - assert.equal(0x00, buffer[0]); - assert.equal(0x00, buffer[1]); - assert.equal(0x80, buffer[2]); - assert.equal(0x00, buffer[3]); - assert.equal(0x00, buffer[4]); - assert.equal(0x80, buffer[5]); - assert.equal(0x00, buffer[6]); - assert.equal(0x00, buffer[7]); + assert.strictEqual(0x00, buffer[0]); + assert.strictEqual(0x00, buffer[1]); + assert.strictEqual(0x80, buffer[2]); + assert.strictEqual(0x00, buffer[3]); + assert.strictEqual(0x00, buffer[4]); + assert.strictEqual(0x80, buffer[5]); + assert.strictEqual(0x00, buffer[6]); + assert.strictEqual(0x00, buffer[7]); buffer.writeFloatBE(0 * -1, 0); buffer.writeFloatLE(0 * -1, 4); - assert.equal(0x80, buffer[0]); - assert.equal(0x00, buffer[1]); - assert.equal(0x00, buffer[2]); - assert.equal(0x00, buffer[3]); - assert.equal(0x00, buffer[4]); - assert.equal(0x00, buffer[5]); - assert.equal(0x00, buffer[6]); - assert.equal(0x80, buffer[7]); + assert.strictEqual(0x80, buffer[0]); + assert.strictEqual(0x00, buffer[1]); + assert.strictEqual(0x00, buffer[2]); + assert.strictEqual(0x00, buffer[3]); + assert.strictEqual(0x00, buffer[4]); + assert.strictEqual(0x00, buffer[5]); + assert.strictEqual(0x00, buffer[6]); + assert.strictEqual(0x80, buffer[7]); buffer.writeFloatBE(Infinity, 0); buffer.writeFloatLE(Infinity, 4); - assert.equal(0x7F, buffer[0]); - assert.equal(0x80, buffer[1]); - assert.equal(0x00, buffer[2]); - assert.equal(0x00, buffer[3]); - assert.equal(0x00, buffer[4]); - assert.equal(0x00, buffer[5]); - assert.equal(0x80, buffer[6]); - assert.equal(0x7F, buffer[7]); - assert.equal(Infinity, buffer.readFloatBE(0)); - assert.equal(Infinity, buffer.readFloatLE(4)); + assert.strictEqual(0x7F, buffer[0]); + assert.strictEqual(0x80, buffer[1]); + assert.strictEqual(0x00, buffer[2]); + assert.strictEqual(0x00, buffer[3]); + assert.strictEqual(0x00, buffer[4]); + assert.strictEqual(0x00, buffer[5]); + assert.strictEqual(0x80, buffer[6]); + assert.strictEqual(0x7F, buffer[7]); + assert.strictEqual(Infinity, buffer.readFloatBE(0)); + assert.strictEqual(Infinity, buffer.readFloatLE(4)); buffer.writeFloatBE(-Infinity, 0); buffer.writeFloatLE(-Infinity, 4); // Darwin ia32 does the other kind of NaN. // Compiler bug. No one really cares. assert(0xFF === buffer[0] || 0x7F === buffer[0]); - assert.equal(0x80, buffer[1]); - assert.equal(0x00, buffer[2]); - assert.equal(0x00, buffer[3]); - assert.equal(0x00, buffer[4]); - assert.equal(0x00, buffer[5]); - assert.equal(0x80, buffer[6]); - assert.equal(0xFF, buffer[7]); - assert.equal(-Infinity, buffer.readFloatBE(0)); - assert.equal(-Infinity, buffer.readFloatLE(4)); + assert.strictEqual(0x80, buffer[1]); + assert.strictEqual(0x00, buffer[2]); + assert.strictEqual(0x00, buffer[3]); + assert.strictEqual(0x00, buffer[4]); + assert.strictEqual(0x00, buffer[5]); + assert.strictEqual(0x80, buffer[6]); + assert.strictEqual(0xFF, buffer[7]); + assert.strictEqual(-Infinity, buffer.readFloatBE(0)); + assert.strictEqual(-Infinity, buffer.readFloatLE(4)); buffer.writeFloatBE(NaN, 0); buffer.writeFloatLE(NaN, 4); diff --git a/test/parallel/test-writeint.js b/test/parallel/test-writeint.js index 838b1ce4798b75..70599dc17750d7 100644 --- a/test/parallel/test-writeint.js +++ b/test/parallel/test-writeint.js @@ -12,8 +12,8 @@ function test8(clazz) { buffer.writeInt8(0x23, 0); buffer.writeInt8(-5, 1); - assert.equal(0x23, buffer[0]); - assert.equal(0xfb, buffer[1]); + assert.strictEqual(0x23, buffer[0]); + assert.strictEqual(0xfb, buffer[1]); /* Make sure we handle truncation correctly */ assert.throws(function() { @@ -27,8 +27,8 @@ function test8(clazz) { buffer.writeInt8(0x7f, 0); buffer.writeInt8(-0x80, 1); - assert.equal(0x7f, buffer[0]); - assert.equal(0x80, buffer[1]); + assert.strictEqual(0x7f, buffer[0]); + assert.strictEqual(0x80, buffer[1]); assert.throws(function() { buffer.writeInt8(0x7f + 1, 0); }, errorOutOfBounds); @@ -43,32 +43,32 @@ function test16(clazz) { buffer.writeInt16BE(0x0023, 0); buffer.writeInt16LE(0x0023, 2); - assert.equal(0x00, buffer[0]); - assert.equal(0x23, buffer[1]); - assert.equal(0x23, buffer[2]); - assert.equal(0x00, buffer[3]); + assert.strictEqual(0x00, buffer[0]); + assert.strictEqual(0x23, buffer[1]); + assert.strictEqual(0x23, buffer[2]); + assert.strictEqual(0x00, buffer[3]); buffer.writeInt16BE(-5, 0); buffer.writeInt16LE(-5, 2); - assert.equal(0xff, buffer[0]); - assert.equal(0xfb, buffer[1]); - assert.equal(0xfb, buffer[2]); - assert.equal(0xff, buffer[3]); + assert.strictEqual(0xff, buffer[0]); + assert.strictEqual(0xfb, buffer[1]); + assert.strictEqual(0xfb, buffer[2]); + assert.strictEqual(0xff, buffer[3]); buffer.writeInt16BE(-1679, 1); buffer.writeInt16LE(-1679, 3); - assert.equal(0xf9, buffer[1]); - assert.equal(0x71, buffer[2]); - assert.equal(0x71, buffer[3]); - assert.equal(0xf9, buffer[4]); + assert.strictEqual(0xf9, buffer[1]); + assert.strictEqual(0x71, buffer[2]); + assert.strictEqual(0x71, buffer[3]); + assert.strictEqual(0xf9, buffer[4]); /* Make sure we handle min/max correctly */ buffer.writeInt16BE(0x7fff, 0); buffer.writeInt16BE(-0x8000, 2); - assert.equal(0x7f, buffer[0]); - assert.equal(0xff, buffer[1]); - assert.equal(0x80, buffer[2]); - assert.equal(0x00, buffer[3]); + assert.strictEqual(0x7f, buffer[0]); + assert.strictEqual(0xff, buffer[1]); + assert.strictEqual(0x80, buffer[2]); + assert.strictEqual(0x00, buffer[3]); assert.throws(function() { buffer.writeInt16BE(0x7fff + 1, 0); }, errorOutOfBounds); @@ -78,10 +78,10 @@ function test16(clazz) { buffer.writeInt16LE(0x7fff, 0); buffer.writeInt16LE(-0x8000, 2); - assert.equal(0xff, buffer[0]); - assert.equal(0x7f, buffer[1]); - assert.equal(0x00, buffer[2]); - assert.equal(0x80, buffer[3]); + assert.strictEqual(0xff, buffer[0]); + assert.strictEqual(0x7f, buffer[1]); + assert.strictEqual(0x00, buffer[2]); + assert.strictEqual(0x80, buffer[3]); assert.throws(function() { buffer.writeInt16LE(0x7fff + 1, 0); }, errorOutOfBounds); @@ -96,48 +96,48 @@ function test32(clazz) { buffer.writeInt32BE(0x23, 0); buffer.writeInt32LE(0x23, 4); - assert.equal(0x00, buffer[0]); - assert.equal(0x00, buffer[1]); - assert.equal(0x00, buffer[2]); - assert.equal(0x23, buffer[3]); - assert.equal(0x23, buffer[4]); - assert.equal(0x00, buffer[5]); - assert.equal(0x00, buffer[6]); - assert.equal(0x00, buffer[7]); + assert.strictEqual(0x00, buffer[0]); + assert.strictEqual(0x00, buffer[1]); + assert.strictEqual(0x00, buffer[2]); + assert.strictEqual(0x23, buffer[3]); + assert.strictEqual(0x23, buffer[4]); + assert.strictEqual(0x00, buffer[5]); + assert.strictEqual(0x00, buffer[6]); + assert.strictEqual(0x00, buffer[7]); buffer.writeInt32BE(-5, 0); buffer.writeInt32LE(-5, 4); - assert.equal(0xff, buffer[0]); - assert.equal(0xff, buffer[1]); - assert.equal(0xff, buffer[2]); - assert.equal(0xfb, buffer[3]); - assert.equal(0xfb, buffer[4]); - assert.equal(0xff, buffer[5]); - assert.equal(0xff, buffer[6]); - assert.equal(0xff, buffer[7]); + assert.strictEqual(0xff, buffer[0]); + assert.strictEqual(0xff, buffer[1]); + assert.strictEqual(0xff, buffer[2]); + assert.strictEqual(0xfb, buffer[3]); + assert.strictEqual(0xfb, buffer[4]); + assert.strictEqual(0xff, buffer[5]); + assert.strictEqual(0xff, buffer[6]); + assert.strictEqual(0xff, buffer[7]); buffer.writeInt32BE(-805306713, 0); buffer.writeInt32LE(-805306713, 4); - assert.equal(0xcf, buffer[0]); - assert.equal(0xff, buffer[1]); - assert.equal(0xfe, buffer[2]); - assert.equal(0xa7, buffer[3]); - assert.equal(0xa7, buffer[4]); - assert.equal(0xfe, buffer[5]); - assert.equal(0xff, buffer[6]); - assert.equal(0xcf, buffer[7]); + assert.strictEqual(0xcf, buffer[0]); + assert.strictEqual(0xff, buffer[1]); + assert.strictEqual(0xfe, buffer[2]); + assert.strictEqual(0xa7, buffer[3]); + assert.strictEqual(0xa7, buffer[4]); + assert.strictEqual(0xfe, buffer[5]); + assert.strictEqual(0xff, buffer[6]); + assert.strictEqual(0xcf, buffer[7]); /* Make sure we handle min/max correctly */ buffer.writeInt32BE(0x7fffffff, 0); buffer.writeInt32BE(-0x80000000, 4); - assert.equal(0x7f, buffer[0]); - assert.equal(0xff, buffer[1]); - assert.equal(0xff, buffer[2]); - assert.equal(0xff, buffer[3]); - assert.equal(0x80, buffer[4]); - assert.equal(0x00, buffer[5]); - assert.equal(0x00, buffer[6]); - assert.equal(0x00, buffer[7]); + assert.strictEqual(0x7f, buffer[0]); + assert.strictEqual(0xff, buffer[1]); + assert.strictEqual(0xff, buffer[2]); + assert.strictEqual(0xff, buffer[3]); + assert.strictEqual(0x80, buffer[4]); + assert.strictEqual(0x00, buffer[5]); + assert.strictEqual(0x00, buffer[6]); + assert.strictEqual(0x00, buffer[7]); assert.throws(function() { buffer.writeInt32BE(0x7fffffff + 1, 0); }, errorOutOfBounds); @@ -147,14 +147,14 @@ function test32(clazz) { buffer.writeInt32LE(0x7fffffff, 0); buffer.writeInt32LE(-0x80000000, 4); - assert.equal(0xff, buffer[0]); - assert.equal(0xff, buffer[1]); - assert.equal(0xff, buffer[2]); - assert.equal(0x7f, buffer[3]); - assert.equal(0x00, buffer[4]); - assert.equal(0x00, buffer[5]); - assert.equal(0x00, buffer[6]); - assert.equal(0x80, buffer[7]); + assert.strictEqual(0xff, buffer[0]); + assert.strictEqual(0xff, buffer[1]); + assert.strictEqual(0xff, buffer[2]); + assert.strictEqual(0x7f, buffer[3]); + assert.strictEqual(0x00, buffer[4]); + assert.strictEqual(0x00, buffer[5]); + assert.strictEqual(0x00, buffer[6]); + assert.strictEqual(0x80, buffer[7]); assert.throws(function() { buffer.writeInt32LE(0x7fffffff + 1, 0); }, errorOutOfBounds); diff --git a/test/parallel/test-writeuint.js b/test/parallel/test-writeuint.js index bddb954d248633..e91e1d256d0261 100644 --- a/test/parallel/test-writeuint.js +++ b/test/parallel/test-writeuint.js @@ -19,25 +19,25 @@ function test8(clazz) { data.writeUInt8(23, 1); data.writeUInt8(23, 2); data.writeUInt8(23, 3); - assert.equal(23, data[0]); - assert.equal(23, data[1]); - assert.equal(23, data[2]); - assert.equal(23, data[3]); + assert.strictEqual(23, data[0]); + assert.strictEqual(23, data[1]); + assert.strictEqual(23, data[2]); + assert.strictEqual(23, data[3]); data.writeUInt8(23, 0); data.writeUInt8(23, 1); data.writeUInt8(23, 2); data.writeUInt8(23, 3); - assert.equal(23, data[0]); - assert.equal(23, data[1]); - assert.equal(23, data[2]); - assert.equal(23, data[3]); + assert.strictEqual(23, data[0]); + assert.strictEqual(23, data[1]); + assert.strictEqual(23, data[2]); + assert.strictEqual(23, data[3]); data.writeUInt8(255, 0); - assert.equal(255, data[0]); + assert.strictEqual(255, data[0]); data.writeUInt8(255, 0); - assert.equal(255, data[0]); + assert.strictEqual(255, data[0]); } @@ -46,37 +46,37 @@ function test16(clazz) { const data = new clazz(4); data.writeUInt16BE(value, 0); - assert.equal(0x23, data[0]); - assert.equal(0x43, data[1]); + assert.strictEqual(0x23, data[0]); + assert.strictEqual(0x43, data[1]); data.writeUInt16BE(value, 1); - assert.equal(0x23, data[1]); - assert.equal(0x43, data[2]); + assert.strictEqual(0x23, data[1]); + assert.strictEqual(0x43, data[2]); data.writeUInt16BE(value, 2); - assert.equal(0x23, data[2]); - assert.equal(0x43, data[3]); + assert.strictEqual(0x23, data[2]); + assert.strictEqual(0x43, data[3]); data.writeUInt16LE(value, 0); - assert.equal(0x23, data[1]); - assert.equal(0x43, data[0]); + assert.strictEqual(0x23, data[1]); + assert.strictEqual(0x43, data[0]); data.writeUInt16LE(value, 1); - assert.equal(0x23, data[2]); - assert.equal(0x43, data[1]); + assert.strictEqual(0x23, data[2]); + assert.strictEqual(0x43, data[1]); data.writeUInt16LE(value, 2); - assert.equal(0x23, data[3]); - assert.equal(0x43, data[2]); + assert.strictEqual(0x23, data[3]); + assert.strictEqual(0x43, data[2]); value = 0xff80; data.writeUInt16LE(value, 0); - assert.equal(0xff, data[1]); - assert.equal(0x80, data[0]); + assert.strictEqual(0xff, data[1]); + assert.strictEqual(0x80, data[0]); data.writeUInt16BE(value, 0); - assert.equal(0xff, data[0]); - assert.equal(0x80, data[1]); + assert.strictEqual(0xff, data[0]); + assert.strictEqual(0x80, data[1]); } @@ -85,40 +85,40 @@ function test32(clazz) { const value = 0xe7f90a6d; data.writeUInt32BE(value, 0); - assert.equal(0xe7, data[0]); - assert.equal(0xf9, data[1]); - assert.equal(0x0a, data[2]); - assert.equal(0x6d, data[3]); + assert.strictEqual(0xe7, data[0]); + assert.strictEqual(0xf9, data[1]); + assert.strictEqual(0x0a, data[2]); + assert.strictEqual(0x6d, data[3]); data.writeUInt32BE(value, 1); - assert.equal(0xe7, data[1]); - assert.equal(0xf9, data[2]); - assert.equal(0x0a, data[3]); - assert.equal(0x6d, data[4]); + assert.strictEqual(0xe7, data[1]); + assert.strictEqual(0xf9, data[2]); + assert.strictEqual(0x0a, data[3]); + assert.strictEqual(0x6d, data[4]); data.writeUInt32BE(value, 2); - assert.equal(0xe7, data[2]); - assert.equal(0xf9, data[3]); - assert.equal(0x0a, data[4]); - assert.equal(0x6d, data[5]); + assert.strictEqual(0xe7, data[2]); + assert.strictEqual(0xf9, data[3]); + assert.strictEqual(0x0a, data[4]); + assert.strictEqual(0x6d, data[5]); data.writeUInt32LE(value, 0); - assert.equal(0xe7, data[3]); - assert.equal(0xf9, data[2]); - assert.equal(0x0a, data[1]); - assert.equal(0x6d, data[0]); + assert.strictEqual(0xe7, data[3]); + assert.strictEqual(0xf9, data[2]); + assert.strictEqual(0x0a, data[1]); + assert.strictEqual(0x6d, data[0]); data.writeUInt32LE(value, 1); - assert.equal(0xe7, data[4]); - assert.equal(0xf9, data[3]); - assert.equal(0x0a, data[2]); - assert.equal(0x6d, data[1]); + assert.strictEqual(0xe7, data[4]); + assert.strictEqual(0xf9, data[3]); + assert.strictEqual(0x0a, data[2]); + assert.strictEqual(0x6d, data[1]); data.writeUInt32LE(value, 2); - assert.equal(0xe7, data[5]); - assert.equal(0xf9, data[4]); - assert.equal(0x0a, data[3]); - assert.equal(0x6d, data[2]); + assert.strictEqual(0xe7, data[5]); + assert.strictEqual(0xf9, data[4]); + assert.strictEqual(0x0a, data[3]); + assert.strictEqual(0x6d, data[2]); } diff --git a/test/parallel/test-zlib-const.js b/test/parallel/test-zlib-const.js index cafa4f8caaf28a..ba6bb5fb8a26b4 100644 --- a/test/parallel/test-zlib-const.js +++ b/test/parallel/test-zlib-const.js @@ -4,14 +4,14 @@ const assert = require('assert'); const zlib = require('zlib'); -assert.equal(zlib.constants.Z_OK, 0, 'Z_OK should be 0'); +assert.strictEqual(zlib.constants.Z_OK, 0, 'Z_OK should be 0'); zlib.constants.Z_OK = 1; -assert.equal(zlib.constants.Z_OK, 0, 'Z_OK should be 0'); +assert.strictEqual(zlib.constants.Z_OK, 0, 'Z_OK should be 0'); -assert.equal(zlib.codes.Z_OK, 0, 'Z_OK should be 0'); +assert.strictEqual(zlib.codes.Z_OK, 0, 'Z_OK should be 0'); zlib.codes.Z_OK = 1; -assert.equal(zlib.codes.Z_OK, 0, 'zlib.codes.Z_OK should be 0'); +assert.strictEqual(zlib.codes.Z_OK, 0, 'zlib.codes.Z_OK should be 0'); zlib.codes = {Z_OK: 1}; -assert.equal(zlib.codes.Z_OK, 0, 'zlib.codes.Z_OK should be 0'); +assert.strictEqual(zlib.codes.Z_OK, 0, 'zlib.codes.Z_OK should be 0'); assert.ok(Object.isFrozen(zlib.codes), 'zlib.codes should be frozen'); diff --git a/test/parallel/test-zlib-convenience-methods.js b/test/parallel/test-zlib-convenience-methods.js index b67b65d7d0b689..9b9419c7bfaf47 100644 --- a/test/parallel/test-zlib-convenience-methods.js +++ b/test/parallel/test-zlib-convenience-methods.js @@ -22,8 +22,8 @@ const opts = { zlib[method[0]](expect, opts, function(err, result) { zlib[method[1]](result, opts, function(err, result) { - assert.equal(result, expect, - 'Should get original string after ' + + assert.strictEqual(result.toString(), expect, + 'Should get original string after ' + method[0] + '/' + method[1] + ' with options.'); hadRun++; }); @@ -31,8 +31,8 @@ const opts = { zlib[method[0]](expect, function(err, result) { zlib[method[1]](result, function(err, result) { - assert.equal(result, expect, - 'Should get original string after ' + + assert.strictEqual(result.toString(), expect, + 'Should get original string after ' + method[0] + '/' + method[1] + ' without options.'); hadRun++; }); @@ -40,20 +40,20 @@ const opts = { let result = zlib[method[0] + 'Sync'](expect, opts); result = zlib[method[1] + 'Sync'](result, opts); - assert.equal(result, expect, - 'Should get original string after ' + + assert.strictEqual(result.toString(), expect, + 'Should get original string after ' + method[0] + '/' + method[1] + ' with options.'); hadRun++; result = zlib[method[0] + 'Sync'](expect); result = zlib[method[1] + 'Sync'](result); - assert.equal(result, expect, - 'Should get original string after ' + + assert.strictEqual(result.toString(), expect, + 'Should get original string after ' + method[0] + '/' + method[1] + ' without options.'); hadRun++; }); process.on('exit', function() { - assert.equal(hadRun, 16, 'expect 16 compressions'); + assert.strictEqual(hadRun, 16, 'expect 16 compressions'); }); diff --git a/test/parallel/test-zlib-flush-drain.js b/test/parallel/test-zlib-flush-drain.js index afa4194ac6d453..d446f048b06586 100644 --- a/test/parallel/test-zlib-flush-drain.js +++ b/test/parallel/test-zlib-flush-drain.js @@ -37,12 +37,12 @@ deflater.on('drain', function() { }); process.once('exit', function() { - assert.equal(beforeFlush, true, - 'before calling flush, writable stream should need to drain'); - assert.equal(afterFlush, false, - 'after calling flush, writable stream should not need to drain'); - assert.equal(drainCount, 1, - 'the deflater should have emitted a single drain event'); - assert.equal(flushCount, 2, - 'flush should be called twice'); + assert.strictEqual(beforeFlush, true, 'before calling flush, writable ' + + 'stream should need to drain'); + assert.strictEqual(afterFlush, false, 'after calling flush, writable ' + + 'stream should not need to drain'); + assert.strictEqual(drainCount, 1, + 'the deflater should have emitted a single drain event'); + assert.strictEqual(flushCount, 2, + 'flush should be called twice'); }); diff --git a/test/parallel/test-zlib-from-concatenated-gzip.js b/test/parallel/test-zlib-from-concatenated-gzip.js index 998a086eb76514..f59b6796357e3b 100644 --- a/test/parallel/test-zlib-from-concatenated-gzip.js +++ b/test/parallel/test-zlib-from-concatenated-gzip.js @@ -15,16 +15,18 @@ const data = Buffer.concat([ defEncoded ]); -assert.equal(zlib.gunzipSync(data).toString(), 'abcdef'); +assert.strictEqual(zlib.gunzipSync(data).toString(), 'abcdef'); zlib.gunzip(data, common.mustCall((err, result) => { assert.ifError(err); - assert.equal(result, 'abcdef', 'result should match original string'); + assert.strictEqual(result.toString(), 'abcdef', + 'result should match original string'); })); zlib.unzip(data, common.mustCall((err, result) => { assert.ifError(err); - assert.equal(result, 'abcdef', 'result should match original string'); + assert.strictEqual(result.toString(), 'abcdef', + 'result should match original string'); })); // Multi-member support does not apply to zlib inflate/deflate. @@ -33,7 +35,8 @@ zlib.unzip(Buffer.concat([ zlib.deflateSync('def') ]), common.mustCall((err, result) => { assert.ifError(err); - assert.equal(result, 'abc', 'result should match contents of first "member"'); + assert.strictEqual(result.toString(), 'abc', + 'result should match contents of first "member"'); })); // files that have the "right" magic bytes for starting a new gzip member diff --git a/test/parallel/test-zlib-from-gzip.js b/test/parallel/test-zlib-from-gzip.js index 3c7e96cef92a0a..ac01fc03d11c6f 100644 --- a/test/parallel/test-zlib-from-gzip.js +++ b/test/parallel/test-zlib-from-gzip.js @@ -23,8 +23,8 @@ const out = fs.createWriteStream(outputFile); inp.pipe(gunzip).pipe(out); out.on('close', function() { const actual = fs.readFileSync(outputFile); - assert.equal(actual.length, expect.length, 'length should match'); + assert.strictEqual(actual.length, expect.length, 'length should match'); for (let i = 0, l = actual.length; i < l; i++) { - assert.equal(actual[i], expect[i], 'byte[' + i + ']'); + assert.strictEqual(actual[i], expect[i], 'byte[' + i + ']'); } }); diff --git a/test/parallel/test-zlib-from-string.js b/test/parallel/test-zlib-from-string.js index 0f885ac80ecbe6..ab2f7d023d8bc8 100644 --- a/test/parallel/test-zlib-from-string.js +++ b/test/parallel/test-zlib-from-string.js @@ -34,8 +34,8 @@ const expectedBase64Gzip = 'H4sIAAAAAAAAA11RS05DMQy8yhzg6d2BPSAkJPZu4laWkjiN4' + 'sHnHNzRtagj5AQAA'; zlib.deflate(inputString, function(err, buffer) { - assert.equal(buffer.toString('base64'), expectedBase64Deflate, - 'deflate encoded string should match'); + assert.strictEqual(buffer.toString('base64'), expectedBase64Deflate, + 'deflate encoded string should match'); }); zlib.gzip(inputString, function(err, buffer) { @@ -46,19 +46,19 @@ zlib.gzip(inputString, function(err, buffer) { // result that we're expecting, and this should match what we get // from inflating the known valid deflate data. zlib.gunzip(buffer, function(err, gunzipped) { - assert.equal(gunzipped.toString(), inputString, - 'Should get original string after gzip/gunzip'); + assert.strictEqual(gunzipped.toString(), inputString, + 'Should get original string after gzip/gunzip'); }); }); let buffer = Buffer.from(expectedBase64Deflate, 'base64'); zlib.unzip(buffer, function(err, buffer) { - assert.equal(buffer.toString(), inputString, - 'decoded inflated string should match'); + assert.strictEqual(buffer.toString(), inputString, + 'decoded inflated string should match'); }); buffer = Buffer.from(expectedBase64Gzip, 'base64'); zlib.unzip(buffer, function(err, buffer) { - assert.equal(buffer.toString(), inputString, - 'decoded gunzipped string should match'); + assert.strictEqual(buffer.toString(), inputString, + 'decoded gunzipped string should match'); }); diff --git a/test/parallel/test-zlib-random-byte-pipes.js b/test/parallel/test-zlib-random-byte-pipes.js index 83855ebd1f2c0a..d4cd4319f93c21 100644 --- a/test/parallel/test-zlib-random-byte-pipes.js +++ b/test/parallel/test-zlib-random-byte-pipes.js @@ -154,5 +154,5 @@ out.on('data', function(c) { out.on('data', common.mustCall(function(c) { console.error('hash=%s', c); - assert.equal(c, inp._hash, 'hashes should match'); + assert.strictEqual(c, inp._hash, 'hashes should match'); })); diff --git a/test/parallel/test-zlib-write-after-flush.js b/test/parallel/test-zlib-write-after-flush.js index 342c9143ba4643..e0e962218269dd 100644 --- a/test/parallel/test-zlib-write-after-flush.js +++ b/test/parallel/test-zlib-write-after-flush.js @@ -16,10 +16,10 @@ gunz.on('data', function(c) { }); process.on('exit', function() { - assert.equal(output, input); + assert.strictEqual(output, input); // Make sure that the flush flag was set back to normal - assert.equal(gzip._flushFlag, zlib.constants.Z_NO_FLUSH); + assert.strictEqual(gzip._flushFlag, zlib.constants.Z_NO_FLUSH); console.log('ok'); }); diff --git a/test/pummel/test-crypto-dh.js b/test/pummel/test-crypto-dh.js index d441e80926df45..64c2800f16ae8d 100644 --- a/test/pummel/test-crypto-dh.js +++ b/test/pummel/test-crypto-dh.js @@ -35,8 +35,8 @@ for (const name in hashes) { const hash1 = hashes[name]; const hash2 = crypto.createHash('sha1') .update(private_key.toUpperCase()).digest('hex'); - assert.equal(hash1, hash2); - assert.equal(group.getGenerator('hex'), '02'); + assert.strictEqual(hash1, hash2); + assert.strictEqual(group.getGenerator('hex'), '02'); } for (const name in hashes) { diff --git a/test/pummel/test-dtrace-jsstack.js b/test/pummel/test-dtrace-jsstack.js index d1615a3855af43..6c8423c2c9c83b 100644 --- a/test/pummel/test-dtrace-jsstack.js +++ b/test/pummel/test-dtrace-jsstack.js @@ -71,11 +71,12 @@ dtrace.on('exit', function(code) { const frame = line.substr(line.indexOf(sentinel) + sentinel.length); const top = frames.shift(); - assert.equal(frame.indexOf(top), 0, 'unexpected frame where ' + + assert.strictEqual(frame.indexOf(top), 0, 'unexpected frame where ' + top + ' was expected'); } - assert.equal(frames.length, 0, 'did not find expected frame ' + frames[0]); + assert.strictEqual(frames.length, 0, + 'did not find expected frame ' + frames[0]); process.exit(0); }); diff --git a/test/pummel/test-fs-watch-file-slow.js b/test/pummel/test-fs-watch-file-slow.js index 78c36152ecd315..1e9b5eb1f219ff 100644 --- a/test/pummel/test-fs-watch-file-slow.js +++ b/test/pummel/test-fs-watch-file-slow.js @@ -19,14 +19,14 @@ fs.watchFile(FILENAME, {interval: TIMEOUT - 250}, function(curr, prev) { console.log([curr, prev]); switch (++nevents) { case 1: - assert.equal(common.fileExists(FILENAME), false); + assert.strictEqual(common.fileExists(FILENAME), false); break; case 2: case 3: - assert.equal(common.fileExists(FILENAME), true); + assert.strictEqual(common.fileExists(FILENAME), true); break; case 4: - assert.equal(common.fileExists(FILENAME), false); + assert.strictEqual(common.fileExists(FILENAME), false); fs.unwatchFile(FILENAME); break; default: @@ -35,7 +35,7 @@ fs.watchFile(FILENAME, {interval: TIMEOUT - 250}, function(curr, prev) { }); process.on('exit', function() { - assert.equal(nevents, 4); + assert.strictEqual(nevents, 4); }); setTimeout(createFile, TIMEOUT); diff --git a/test/pummel/test-fs-watch-file.js b/test/pummel/test-fs-watch-file.js index 7713fe74ed99aa..3fda41040486df 100644 --- a/test/pummel/test-fs-watch-file.js +++ b/test/pummel/test-fs-watch-file.js @@ -27,10 +27,10 @@ process.on('exit', function() { fs.unlinkSync(filepathTwoAbs); fs.unlinkSync(filenameThree); fs.unlinkSync(filenameFour); - assert.equal(1, watchSeenOne); - assert.equal(2, watchSeenTwo); - assert.equal(1, watchSeenThree); - assert.equal(1, watchSeenFour); + assert.strictEqual(1, watchSeenOne); + assert.strictEqual(2, watchSeenTwo); + assert.strictEqual(1, watchSeenThree); + assert.strictEqual(1, watchSeenFour); }); @@ -122,7 +122,7 @@ assert.doesNotThrow( function() { function a() { ++watchSeenFour; - assert.equal(1, watchSeenFour); + assert.strictEqual(1, watchSeenFour); fs.unwatchFile('.' + path.sep + filenameFour, a); } fs.watchFile(filenameFour, a); diff --git a/test/pummel/test-http-many-keep-alive-connections.js b/test/pummel/test-http-many-keep-alive-connections.js index e465c02a90161c..ee616e1d918e66 100644 --- a/test/pummel/test-http-many-keep-alive-connections.js +++ b/test/pummel/test-http-many-keep-alive-connections.js @@ -10,7 +10,7 @@ let connection; const server = http.Server(function(req, res) { requests++; - assert.equal(req.connection, connection); + assert.strictEqual(req.connection, connection); res.writeHead(200); res.end('hello world\n'); }); @@ -43,6 +43,6 @@ server.listen(common.PORT, function connect() { }); process.on('exit', function() { - assert.equal(expected, responses); - assert.equal(expected, requests); + assert.strictEqual(expected, responses); + assert.strictEqual(expected, requests); }); diff --git a/test/pummel/test-https-ci-reneg-attack.js b/test/pummel/test-https-ci-reneg-attack.js index 850e0949c4a64a..6113ee54ce904b 100644 --- a/test/pummel/test-https-ci-reneg-attack.js +++ b/test/pummel/test-https-ci-reneg-attack.js @@ -71,7 +71,7 @@ function test(next) { }); child.on('exit', function() { - assert.equal(renegs, tls.CLIENT_RENEG_LIMIT + 1); + assert.strictEqual(renegs, tls.CLIENT_RENEG_LIMIT + 1); server.close(); process.nextTick(next); }); @@ -83,7 +83,7 @@ function test(next) { case 'EPIPE': break; default: - assert.equal(err.code, 'ECONNRESET'); + assert.strictEqual(err.code, 'ECONNRESET'); break; } closed = true; diff --git a/test/pummel/test-net-connect-econnrefused.js b/test/pummel/test-net-connect-econnrefused.js index 30da36d983e4f7..4ac55da40553e0 100644 --- a/test/pummel/test-net-connect-econnrefused.js +++ b/test/pummel/test-net-connect-econnrefused.js @@ -18,7 +18,7 @@ function pummel() { let pending; for (pending = 0; pending < ATTEMPTS_PER_ROUND; pending++) { net.createConnection(common.PORT).on('error', function(err) { - assert.equal(err.code, 'ECONNREFUSED'); + assert.strictEqual(err.code, 'ECONNREFUSED'); if (--pending > 0) return; if (rounds === ROUNDS) return check(); rounds++; @@ -30,15 +30,15 @@ function pummel() { function check() { setTimeout(function() { - assert.equal(process._getActiveRequests().length, 0); - assert.equal(process._getActiveHandles().length, 1); // the timer + assert.strictEqual(process._getActiveRequests().length, 0); + assert.strictEqual(process._getActiveHandles().length, 1); // the timer check_called = true; }, 0); } let check_called = false; process.on('exit', function() { - assert.equal(rounds, ROUNDS); - assert.equal(reqs, ROUNDS * ATTEMPTS_PER_ROUND); + assert.strictEqual(rounds, ROUNDS); + assert.strictEqual(reqs, ROUNDS * ATTEMPTS_PER_ROUND); assert(check_called); }); diff --git a/test/pummel/test-net-many-clients.js b/test/pummel/test-net-many-clients.js index a92ae033a09a17..fdcdf1198f8df2 100644 --- a/test/pummel/test-net-many-clients.js +++ b/test/pummel/test-net-many-clients.js @@ -49,8 +49,8 @@ function runClient(callback) { client.on('close', function(had_error) { console.log('.'); - assert.equal(false, had_error); - assert.equal(bytes, client.recved.length); + assert.strictEqual(false, had_error); + assert.strictEqual(bytes, client.recved.length); if (client.fd) { console.log(client.fd); @@ -75,6 +75,6 @@ server.listen(common.PORT, function() { }); process.on('exit', function() { - assert.equal(connections_per_client * concurrency, total_connections); + assert.strictEqual(connections_per_client * concurrency, total_connections); console.log('\nokay!'); }); diff --git a/test/pummel/test-net-pause.js b/test/pummel/test-net-pause.js index db426edbe9c507..6a701d56869afb 100644 --- a/test/pummel/test-net-pause.js +++ b/test/pummel/test-net-pause.js @@ -31,11 +31,11 @@ server.on('listening', function() { setTimeout(function() { chars_recved = recv.length; console.log('pause at: ' + chars_recved); - assert.equal(true, chars_recved > 1); + assert.strictEqual(true, chars_recved > 1); client.pause(); setTimeout(function() { console.log('resume at: ' + chars_recved); - assert.equal(chars_recved, recv.length); + assert.strictEqual(chars_recved, recv.length); client.resume(); setTimeout(function() { @@ -45,7 +45,7 @@ server.on('listening', function() { setTimeout(function() { console.log('resume at: ' + chars_recved); - assert.equal(chars_recved, recv.length); + assert.strictEqual(chars_recved, recv.length); client.resume(); }, 500); @@ -64,6 +64,6 @@ server.on('listening', function() { server.listen(common.PORT); process.on('exit', function() { - assert.equal(N, recv.length); + assert.strictEqual(N, recv.length); console.error('Exit'); }); diff --git a/test/pummel/test-net-pingpong-delay.js b/test/pummel/test-net-pingpong-delay.js index 9a598435d1bd28..2236ba83a88f02 100644 --- a/test/pummel/test-net-pingpong-delay.js +++ b/test/pummel/test-net-pingpong-delay.js @@ -14,30 +14,30 @@ function pingPongTest(port, host, on_complete) { socket.on('data', function(data) { console.log(data); - assert.equal('PING', data); - assert.equal('open', socket.readyState); - assert.equal(true, count <= N); + assert.strictEqual('PING', data); + assert.strictEqual('open', socket.readyState); + assert.strictEqual(true, count <= N); setTimeout(function() { - assert.equal('open', socket.readyState); + assert.strictEqual('open', socket.readyState); socket.write('PONG'); }, DELAY); }); socket.on('timeout', function() { console.error('server-side timeout!!'); - assert.equal(false, true); + assert.strictEqual(false, true); }); socket.on('end', function() { console.log('server-side socket EOF'); - assert.equal('writeOnly', socket.readyState); + assert.strictEqual('writeOnly', socket.readyState); socket.end(); }); socket.on('close', function(had_error) { console.log('server-side socket.end'); - assert.equal(false, had_error); - assert.equal('closed', socket.readyState); + assert.strictEqual(false, had_error); + assert.strictEqual('closed', socket.readyState); socket.server.close(); }); }); @@ -48,17 +48,17 @@ function pingPongTest(port, host, on_complete) { client.setEncoding('utf8'); client.on('connect', function() { - assert.equal('open', client.readyState); + assert.strictEqual('open', client.readyState); client.write('PING'); }); client.on('data', function(data) { console.log(data); - assert.equal('PONG', data); - assert.equal('open', client.readyState); + assert.strictEqual('PONG', data); + assert.strictEqual('open', client.readyState); setTimeout(function() { - assert.equal('open', client.readyState); + assert.strictEqual('open', client.readyState); if (count++ < N) { client.write('PING'); } else { @@ -71,12 +71,12 @@ function pingPongTest(port, host, on_complete) { client.on('timeout', function() { console.error('client-side timeout!!'); - assert.equal(false, true); + assert.strictEqual(false, true); }); client.on('close', common.mustCall(function() { console.log('client.end'); - assert.equal(N + 1, count); + assert.strictEqual(N + 1, count); assert.ok(client_ended); if (on_complete) on_complete(); })); diff --git a/test/pummel/test-net-pingpong.js b/test/pummel/test-net-pingpong.js index 6ede6f9fcb2763..5e0950285739a1 100644 --- a/test/pummel/test-net-pingpong.js +++ b/test/pummel/test-net-pingpong.js @@ -11,16 +11,16 @@ function pingPongTest(port, host, on_complete) { let sent_final_ping = false; const server = net.createServer({ allowHalfOpen: true }, function(socket) { - assert.equal(true, socket.remoteAddress !== null); - assert.equal(true, socket.remoteAddress !== undefined); + assert.strictEqual(true, socket.remoteAddress !== null); + assert.strictEqual(true, socket.remoteAddress !== undefined); const address = socket.remoteAddress; if (host === '127.0.0.1') { - assert.equal(address, '127.0.0.1'); + assert.strictEqual(address, '127.0.0.1'); } else if (host == null || host === 'localhost') { assert(address === '127.0.0.1' || address === '::ffff:127.0.0.1'); } else { console.log('host = ' + host + ', remoteAddress = ' + address); - assert.equal(address, '::1'); + assert.strictEqual(address, '::1'); } socket.setEncoding('utf8'); @@ -29,21 +29,21 @@ function pingPongTest(port, host, on_complete) { socket.on('data', function(data) { console.log('server got: ' + JSON.stringify(data)); - assert.equal('open', socket.readyState); - assert.equal(true, count <= N); + assert.strictEqual('open', socket.readyState); + assert.strictEqual(true, count <= N); if (/PING/.exec(data)) { socket.write('PONG'); } }); socket.on('end', function() { - assert.equal('writeOnly', socket.readyState); + assert.strictEqual('writeOnly', socket.readyState); socket.end(); }); socket.on('close', function(had_error) { - assert.equal(false, had_error); - assert.equal('closed', socket.readyState); + assert.strictEqual(false, had_error); + assert.strictEqual('closed', socket.readyState); socket.server.close(); }); }); @@ -54,21 +54,21 @@ function pingPongTest(port, host, on_complete) { client.setEncoding('utf8'); client.on('connect', function() { - assert.equal('open', client.readyState); + assert.strictEqual('open', client.readyState); client.write('PING'); }); client.on('data', function(data) { console.log('client got: ' + data); - assert.equal('PONG', data); + assert.strictEqual('PONG', data); count += 1; if (sent_final_ping) { - assert.equal('readOnly', client.readyState); + assert.strictEqual('readOnly', client.readyState); return; } else { - assert.equal('open', client.readyState); + assert.strictEqual('open', client.readyState); } if (count < N) { @@ -81,8 +81,8 @@ function pingPongTest(port, host, on_complete) { }); client.on('close', function() { - assert.equal(N + 1, count); - assert.equal(true, sent_final_ping); + assert.strictEqual(N + 1, count); + assert.strictEqual(true, sent_final_ping); if (on_complete) on_complete(); tests_run += 1; }); @@ -97,5 +97,5 @@ pingPongTest(common.PORT + 1, null); if (!common.isSunOS) pingPongTest(common.PORT + 2, '::1'); process.on('exit', function() { - assert.equal(common.isSunOS ? 2 : 3, tests_run); + assert.strictEqual(common.isSunOS ? 2 : 3, tests_run); }); diff --git a/test/pummel/test-net-throttle.js b/test/pummel/test-net-throttle.js index 23f05f4d5eaeaa..c222d0bb17ccfa 100644 --- a/test/pummel/test-net-throttle.js +++ b/test/pummel/test-net-throttle.js @@ -16,7 +16,7 @@ console.log('start server on port ' + common.PORT); const server = net.createServer(function(connection) { connection.write(body.slice(0, part_N)); connection.write(body.slice(part_N, 2 * part_N)); - assert.equal(false, connection.write(body.slice(2 * part_N, N))); + assert.strictEqual(false, connection.write(body.slice(2 * part_N, N))); console.log('bufferSize: ' + connection.bufferSize, 'expecting', N); assert.ok(0 <= connection.bufferSize && connection._writableState.length <= N); @@ -37,7 +37,7 @@ server.listen(common.PORT, function() { console.log('pause'); const x = chars_recved; setTimeout(function() { - assert.equal(chars_recved, x); + assert.strictEqual(chars_recved, x); client.resume(); console.log('resume'); paused = false; @@ -53,6 +53,6 @@ server.listen(common.PORT, function() { process.on('exit', function() { - assert.equal(N, chars_recved); - assert.equal(true, npauses > 2); + assert.strictEqual(N, chars_recved); + assert.strictEqual(true, npauses > 2); }); diff --git a/test/pummel/test-net-timeout.js b/test/pummel/test-net-timeout.js index d6dd8e489cc116..faec443a007f20 100644 --- a/test/pummel/test-net-timeout.js +++ b/test/pummel/test-net-timeout.js @@ -45,7 +45,7 @@ echo_server.listen(common.PORT, function() { }); client.on('data', function(chunk) { - assert.equal('hello\r\n', chunk); + assert.strictEqual('hello\r\n', chunk); if (exchanges++ < 5) { setTimeout(function() { console.log('client write "hello"'); diff --git a/test/pummel/test-net-write-callbacks.js b/test/pummel/test-net-write-callbacks.js index 6c3c1f202a81c3..b29ae6ef808292 100644 --- a/test/pummel/test-net-write-callbacks.js +++ b/test/pummel/test-net-write-callbacks.js @@ -45,5 +45,5 @@ server.listen(common.PORT, function() { }); process.on('exit', function() { - assert.equal(N, cbcount); + assert.strictEqual(N, cbcount); }); diff --git a/test/pummel/test-regress-GH-892.js b/test/pummel/test-regress-GH-892.js index 0619fd84de3b5e..3ec44dfa12bb5b 100644 --- a/test/pummel/test-regress-GH-892.js +++ b/test/pummel/test-regress-GH-892.js @@ -42,7 +42,7 @@ function makeRequest() { child.on('exit', function(code) { assert.ok(/DONE/.test(stderrBuffer)); - assert.equal(0, code); + assert.strictEqual(0, code); }); // The following two lines forward the stdio from the child @@ -78,7 +78,7 @@ const server = https.Server(serverOptions, function(req, res) { }); req.on('end', function() { - assert.equal(bytesExpected, uploadCount); + assert.strictEqual(bytesExpected, uploadCount); res.writeHead(200, {'content-type': 'text/plain'}); res.end('successful upload\n'); }); @@ -91,5 +91,5 @@ server.listen(common.PORT, function() { process.on('exit', function() { console.error('got %d bytes', uploadCount); - assert.equal(uploadCount, bytesExpected); + assert.strictEqual(uploadCount, bytesExpected); }); diff --git a/test/pummel/test-stream-pipe-multi.js b/test/pummel/test-stream-pipe-multi.js index e1e5e011020fe2..478b61c822d4e0 100644 --- a/test/pummel/test-stream-pipe-multi.js +++ b/test/pummel/test-stream-pipe-multi.js @@ -45,8 +45,8 @@ FakeStream.prototype.close = function() { // expect all streams to close properly. process.on('exit', function() { - assert.equal(cnt, wclosed, 'writable streams closed'); - assert.equal(cnt, rclosed, 'readable streams closed'); + assert.strictEqual(cnt, wclosed, 'writable streams closed'); + assert.strictEqual(cnt, rclosed, 'readable streams closed'); }); for (let i = 0; i < chunkSize; i++) { diff --git a/test/pummel/test-stream2-basic.js b/test/pummel/test-stream2-basic.js index 073c1d8e35ad36..0e2bf3e8e302ce 100644 --- a/test/pummel/test-stream2-basic.js +++ b/test/pummel/test-stream2-basic.js @@ -87,7 +87,7 @@ function run() { fn({ same: assert.deepStrictEqual, ok: assert, - equal: assert.equal, + equal: assert.strictEqual, end: function() { count--; run(); @@ -97,7 +97,7 @@ function run() { // ensure all tests have run process.on('exit', function() { - assert.equal(count, 0); + assert.strictEqual(count, 0); }); process.nextTick(run); @@ -314,7 +314,7 @@ test('back pressure respected', function(t) { const w1 = new R(); w1.write = function(chunk) { console.error('w1.emit("close")'); - assert.equal(chunk[0], 'one'); + assert.strictEqual(chunk[0], 'one'); w1.emit('close'); process.nextTick(function() { r.pipe(w2); @@ -330,8 +330,8 @@ test('back pressure respected', function(t) { const w2 = new R(); w2.write = function(chunk) { console.error('w2 write', chunk, counter); - assert.equal(chunk[0], expected.shift()); - assert.equal(counter, 0); + assert.strictEqual(chunk[0], expected.shift()); + assert.strictEqual(counter, 0); counter++; @@ -352,8 +352,8 @@ test('back pressure respected', function(t) { const w3 = new R(); w3.write = function(chunk) { console.error('w3 write', chunk, counter); - assert.equal(chunk[0], expected.shift()); - assert.equal(counter, 1); + assert.strictEqual(chunk[0], expected.shift()); + assert.strictEqual(counter, 1); counter++; @@ -370,8 +370,8 @@ test('back pressure respected', function(t) { return false; }; w3.end = function() { - assert.equal(counter, 2); - assert.equal(expected.length, 0); + assert.strictEqual(counter, 2); + assert.strictEqual(expected.length, 0); t.end(); }; }); @@ -387,19 +387,19 @@ test('read(0) for ended streams', function(t) { const v = r.read(0); - assert.equal(v, null); + assert.strictEqual(v, null); const w = new R(); w.write = function(buffer) { written = true; - assert.equal(ended, false); - assert.equal(buffer.toString(), 'foo'); + assert.strictEqual(ended, false); + assert.strictEqual(buffer.toString(), 'foo'); }; w.end = function() { ended = true; - assert.equal(written, true); + assert.strictEqual(written, true); t.end(); }; @@ -420,7 +420,7 @@ test('sync _read ending', function(t) { r.read(); process.nextTick(function() { - assert.equal(called, true); + assert.strictEqual(called, true); t.end(); }); }); diff --git a/test/pummel/test-timers.js b/test/pummel/test-timers.js index 4555582371b9ff..600b7ce35b0913 100644 --- a/test/pummel/test-timers.js +++ b/test/pummel/test-timers.js @@ -10,7 +10,7 @@ let interval_count = 0; clearTimeout(null); clearInterval(null); -assert.equal(true, setTimeout instanceof Function); +assert.strictEqual(true, setTimeout instanceof Function); const starttime = new Date(); setTimeout(common.mustCall(function() { const endtime = new Date(); @@ -19,11 +19,11 @@ setTimeout(common.mustCall(function() { assert.ok(diff > 0); console.error('diff: ' + diff); - assert.equal(true, 1000 - WINDOW < diff && diff < 1000 + WINDOW); + assert.strictEqual(true, 1000 - WINDOW < diff && diff < 1000 + WINDOW); }), 1000); // this timer shouldn't execute -const id = setTimeout(function() { assert.equal(true, false); }, 500); +const id = setTimeout(function() { assert.strictEqual(true, false); }, 500); clearTimeout(id); setInterval(function() { @@ -36,9 +36,9 @@ setInterval(function() { const t = interval_count * 1000; - assert.equal(true, t - WINDOW < diff && diff < t + WINDOW); + assert.strictEqual(true, t - WINDOW < diff && diff < t + WINDOW); - assert.equal(true, interval_count <= 3); + assert.strictEqual(true, interval_count <= 3); if (interval_count === 3) clearInterval(this); }, 1000); @@ -46,13 +46,13 @@ setInterval(function() { // Single param: setTimeout(function(param) { - assert.equal('test param', param); + assert.strictEqual('test param', param); }, 1000, 'test param'); let interval_count2 = 0; setInterval(function(param) { ++interval_count2; - assert.equal('test param', param); + assert.strictEqual('test param', param); if (interval_count2 === 3) clearInterval(this); @@ -61,15 +61,15 @@ setInterval(function(param) { // Multiple param setTimeout(function(param1, param2) { - assert.equal('param1', param1); - assert.equal('param2', param2); + assert.strictEqual('param1', param1); + assert.strictEqual('param2', param2); }, 1000, 'param1', 'param2'); let interval_count3 = 0; setInterval(function(param1, param2) { ++interval_count3; - assert.equal('param1', param1); - assert.equal('param2', param2); + assert.strictEqual('param1', param1); + assert.strictEqual('param2', param2); if (interval_count3 === 3) clearInterval(this); @@ -99,7 +99,8 @@ clearTimeout(y); process.on('exit', function() { - assert.equal(3, interval_count); - assert.equal(11, count4); - assert.equal(0, expectedTimeouts, 'clearTimeout cleared too many timeouts'); + assert.strictEqual(3, interval_count); + assert.strictEqual(11, count4); + assert.strictEqual(0, expectedTimeouts, + 'clearTimeout cleared too many timeouts'); }); diff --git a/test/pummel/test-tls-ci-reneg-attack.js b/test/pummel/test-tls-ci-reneg-attack.js index dd2b43ed60278f..9c2d3da5c3f6b1 100644 --- a/test/pummel/test-tls-ci-reneg-attack.js +++ b/test/pummel/test-tls-ci-reneg-attack.js @@ -69,7 +69,7 @@ function test(next) { }); child.on('exit', function() { - assert.equal(renegs, tls.CLIENT_RENEG_LIMIT + 1); + assert.strictEqual(renegs, tls.CLIENT_RENEG_LIMIT + 1); server.close(); process.nextTick(next); }); @@ -81,7 +81,7 @@ function test(next) { case 'EPIPE': break; default: - assert.equal(err.code, 'ECONNRESET'); + assert.strictEqual(err.code, 'ECONNRESET'); break; } closed = true; diff --git a/test/pummel/test-tls-securepair-client.js b/test/pummel/test-tls-securepair-client.js index 75e7b400592191..cd9299cb790958 100644 --- a/test/pummel/test-tls-securepair-client.js +++ b/test/pummel/test-tls-securepair-client.js @@ -31,9 +31,10 @@ function test1() { function test2() { function check(pair) { // "TLS Web Client Authentication" - assert.equal(pair.cleartext.getPeerCertificate().ext_key_usage.length, 1); - assert.equal(pair.cleartext.getPeerCertificate().ext_key_usage[0], - '1.3.6.1.5.5.7.3.2'); + assert.strictEqual(pair.cleartext.getPeerCertificate().ext_key_usage.length, + 1); + assert.strictEqual(pair.cleartext.getPeerCertificate().ext_key_usage[0], + '1.3.6.1.5.5.7.3.2'); } test('keys/agent4-key.pem', 'keys/agent4-cert.pem', check); } @@ -158,8 +159,8 @@ function test(keyfn, certfn, check, next) { process.on('exit', function() { - assert.equal(0, serverExitCode); - assert.equal('WAIT-SERVER-CLOSE', state); + assert.strictEqual(0, serverExitCode); + assert.strictEqual('WAIT-SERVER-CLOSE', state); assert.ok(gotWriteCallback); }); } diff --git a/test/pummel/test-tls-server-large-request.js b/test/pummel/test-tls-server-large-request.js index f02eb51a2f6742..41393120fcd1e2 100644 --- a/test/pummel/test-tls-server-large-request.js +++ b/test/pummel/test-tls-server-large-request.js @@ -30,7 +30,7 @@ Mediator.prototype._write = function _write(data, enc, cb) { setTimeout(cb, 0); if (this.buf.length >= request.length) { - assert.equal(this.buf, request.toString()); + assert.strictEqual(this.buf, request.toString()); server.close(); } }; diff --git a/test/pummel/test-tls-throttle.js b/test/pummel/test-tls-throttle.js index 574a83b18f2846..e427e0bf89f877 100644 --- a/test/pummel/test-tls-throttle.js +++ b/test/pummel/test-tls-throttle.js @@ -63,5 +63,5 @@ const timeout = setTimeout(displayCounts, 10 * 1000); process.on('exit', function() { displayCounts(); - assert.equal(body.length, recvCount); + assert.strictEqual(body.length, recvCount); }); diff --git a/test/sequential/test-child-process-fork-getconnections.js b/test/sequential/test-child-process-fork-getconnections.js index 4d6b1a25ef16cc..355a45913c8699 100644 --- a/test/sequential/test-child-process-fork-getconnections.js +++ b/test/sequential/test-child-process-fork-getconnections.js @@ -20,7 +20,7 @@ if (process.argv[2] === 'child') { } if (m.cmd === 'close') { - assert.equal(socket, undefined); + assert.strictEqual(socket, undefined); if (sockets[m.id].destroyed) { // Workaround for https://github.com/nodejs/node/issues/2610 sendClosed(m.id); @@ -92,8 +92,8 @@ if (process.argv[2] === 'child') { server.listen(common.PORT, '127.0.0.1'); process.on('exit', function() { - assert.equal(sent, count); - assert.equal(disconnected, count); + assert.strictEqual(sent, count); + assert.strictEqual(disconnected, count); assert.ok(closeEmitted); console.log('ok'); }); diff --git a/test/sequential/test-deprecation-flags.js b/test/sequential/test-deprecation-flags.js index eb5c1a3ae6261f..3bd2e99033beb1 100644 --- a/test/sequential/test-deprecation-flags.js +++ b/test/sequential/test-deprecation-flags.js @@ -20,24 +20,24 @@ const traceDep = ['--trace-deprecation', depmod]; execFile(node, normal, function(er, stdout, stderr) { console.error('normal: show deprecation warning'); - assert.equal(er, null); - assert.equal(stdout, ''); + assert.strictEqual(er, null); + assert.strictEqual(stdout, ''); assert(/util\.debug is deprecated/.test(stderr)); console.log('normal ok'); }); execFile(node, noDep, function(er, stdout, stderr) { console.error('--no-deprecation: silence deprecations'); - assert.equal(er, null); - assert.equal(stdout, ''); - assert.equal(stderr, 'DEBUG: This is deprecated\n'); + assert.strictEqual(er, null); + assert.strictEqual(stdout, ''); + assert.strictEqual(stderr, 'DEBUG: This is deprecated\n'); console.log('silent ok'); }); execFile(node, traceDep, function(er, stdout, stderr) { console.error('--trace-deprecation: show stack'); - assert.equal(er, null); - assert.equal(stdout, ''); + assert.strictEqual(er, null); + assert.strictEqual(stdout, ''); const stack = stderr.trim().split('\n'); // just check the top and bottom. assert(/util.debug is deprecated. Use console.error instead./.test(stack[1])); @@ -47,8 +47,8 @@ execFile(node, traceDep, function(er, stdout, stderr) { execFile(node, [depUserlandFunction], function(er, stdout, stderr) { console.error('normal: testing deprecated userland function'); - assert.equal(er, null); - assert.equal(stdout, ''); + assert.strictEqual(er, null); + assert.strictEqual(stdout, ''); assert(/deprecatedFunction is deprecated/.test(stderr)); console.error('normal: ok'); }); diff --git a/test/sequential/test-http-regr-gh-2928.js b/test/sequential/test-http-regr-gh-2928.js index 190966083e3f97..55e3a93bc98eaa 100644 --- a/test/sequential/test-http-regr-gh-2928.js +++ b/test/sequential/test-http-regr-gh-2928.js @@ -59,5 +59,5 @@ const server = net.createServer(function(c) { }).listen(common.PORT, execAndClose); process.on('exit', function() { - assert.equal(gotResponses, COUNT); + assert.strictEqual(gotResponses, COUNT); }); diff --git a/test/sequential/test-process-warnings.js b/test/sequential/test-process-warnings.js index 1e8b2b13a20a78..d4894f8bffeb36 100644 --- a/test/sequential/test-process-warnings.js +++ b/test/sequential/test-process-warnings.js @@ -12,22 +12,22 @@ const traceWarn = ['--trace-warnings', warnmod]; execFile(node, normal, function(er, stdout, stderr) { // Show Process Warnings - assert.equal(er, null); - assert.equal(stdout, ''); + assert.strictEqual(er, null); + assert.strictEqual(stdout, ''); assert(/^\(.+\)\sWarning: a bad practice warning/.test(stderr)); }); execFile(node, noWarn, function(er, stdout, stderr) { // Hide Process Warnings - assert.equal(er, null); - assert.equal(stdout, ''); + assert.strictEqual(er, null); + assert.strictEqual(stdout, ''); assert(!/^\(.+\)\sWarning: a bad practice warning/.test(stderr)); }); execFile(node, traceWarn, function(er, stdout, stderr) { // Show Warning Trace - assert.equal(er, null); - assert.equal(stdout, ''); + assert.strictEqual(er, null); + assert.strictEqual(stdout, ''); assert(/^\(.+\)\sWarning: a bad practice warning/.test(stderr)); assert(/at Object\.\s\(.+warnings.js:3:9\)/.test(stderr)); }); diff --git a/test/sequential/test-regress-GH-4027.js b/test/sequential/test-regress-GH-4027.js index 87a8861ac35477..8d9c6bb1ad795a 100644 --- a/test/sequential/test-regress-GH-4027.js +++ b/test/sequential/test-regress-GH-4027.js @@ -11,7 +11,7 @@ fs.writeFileSync(filename, 'quis custodiet ipsos custodes'); setTimeout(fs.unlinkSync, 100, filename); fs.watchFile(filename, { interval: 50 }, common.mustCall(function(curr, prev) { - assert.equal(prev.nlink, 1); - assert.equal(curr.nlink, 0); + assert.strictEqual(prev.nlink, 1); + assert.strictEqual(curr.nlink, 0); fs.unwatchFile(filename); })); diff --git a/test/sequential/test-regress-GH-784.js b/test/sequential/test-regress-GH-784.js index c9b630b0c81755..0bfa407ec10dc3 100644 --- a/test/sequential/test-regress-GH-784.js +++ b/test/sequential/test-regress-GH-784.js @@ -21,7 +21,7 @@ const server = http.createServer(function(req, res) { }); req.on('end', function() { - assert.equal('PING', body); + assert.strictEqual('PING', body); res.writeHead(200); res.end('PONG'); }); @@ -96,7 +96,7 @@ function ping() { }); res.on('end', function() { - assert.equal('PONG', body); + assert.strictEqual('PONG', body); assert.ok(!hadError); gotEnd = true; afterPing('success'); @@ -128,5 +128,5 @@ process.on('exit', function() { console.error("process.on('exit')"); console.error(responses); - assert.equal(8, responses.length); + assert.strictEqual(8, responses.length); }); diff --git a/test/sequential/test-regress-GH-877.js b/test/sequential/test-regress-GH-877.js index 06c839aa483fa8..1a0d7a48e5758c 100644 --- a/test/sequential/test-regress-GH-877.js +++ b/test/sequential/test-regress-GH-877.js @@ -31,7 +31,7 @@ server.listen(common.PORT, '127.0.0.1', function() { res.resume(); }); - assert.equal(req.agent, agent); + assert.strictEqual(req.agent, agent); console.log('Socket: ' + agent.sockets[addrString].length + '/' + agent.maxSockets + ' queued: ' + (agent.requests[addrString] ? diff --git a/test/sequential/test-require-cache-without-stat.js b/test/sequential/test-require-cache-without-stat.js index b591f1746b62d4..d90bbd2b7bb71f 100644 --- a/test/sequential/test-require-cache-without-stat.js +++ b/test/sequential/test-require-cache-without-stat.js @@ -49,4 +49,4 @@ for (let i = 0; i < 100; i++) { console.log('counterAfter = %d', counter); const counterAfter = counter; -assert.equal(counterBefore, counterAfter); +assert.strictEqual(counterBefore, counterAfter); diff --git a/test/sequential/test-stream2-fs.js b/test/sequential/test-stream2-fs.js index 2891335c813562..58a66ef99df9cf 100644 --- a/test/sequential/test-stream2-fs.js +++ b/test/sequential/test-stream2-fs.js @@ -39,7 +39,7 @@ const w = new TestWriter(); w.on('results', function(res) { console.error(res, w.length); - assert.equal(w.length, size); + assert.strictEqual(w.length, size); assert.deepStrictEqual(res.map(function(c) { return c.length; }), expectLengths); diff --git a/test/sequential/test-stream2-stderr-sync.js b/test/sequential/test-stream2-stderr-sync.js index e37a5f2cd1b38e..08f35e597ce357 100644 --- a/test/sequential/test-stream2-stderr-sync.js +++ b/test/sequential/test-stream2-stderr-sync.js @@ -16,7 +16,7 @@ function parent() { }); child.on('close', function() { - assert.equal(err, 'child ' + c + '\nfoo\nbar\nbaz\n'); + assert.strictEqual(err, 'child ' + c + '\nfoo\nbar\nbaz\n'); console.log('ok %d child #%d', ++i, c); if (i === children.length) console.log('1..' + i); From c217b438f2793cbc9c85ae4bf9ba981fcb8f1f5a Mon Sep 17 00:00:00 2001 From: Gibson Fahnestock Date: Sun, 8 Jan 2017 23:23:34 +0000 Subject: [PATCH 197/291] assert, tools: enforce strict (not)equal in eslint MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Extend no-restricted-properties to catch use of assert.equal() and assert.notEqual() and require assert.strictEqual() or assert.notStrictEqual() instead. Also update the eslint-ignore in lib/assert.js to avoid assert.equal/notEqual linter errors in their definitions. PR-URL: https://github.com/nodejs/node/pull/10698 Reviewed-By: James M Snell Reviewed-By: Colin Ihrig Reviewed-By: Michael Dawson Reviewed-By: Sakthipriyan Vairamani Reviewed-By: Michaël Zasso Reviewed-By: Teddy Katz --- .eslintrc.yaml | 28 ++++++++++++++++------------ lib/assert.js | 3 +-- 2 files changed, 17 insertions(+), 14 deletions(-) diff --git a/.eslintrc.yaml b/.eslintrc.yaml index cf1f36c86bcbdc..4f691caefd3a78 100644 --- a/.eslintrc.yaml +++ b/.eslintrc.yaml @@ -62,17 +62,21 @@ rules: no-new-require: 2 no-path-concat: 2 no-restricted-modules: [2, sys, _linklist] - no-restricted-properties: [2, { - object: assert, - property: deepEqual, - message: Please use assert.deepStrictEqual(). - }, { - property: __defineGetter__, - message: __defineGetter__ is deprecated. - }, { - property: __defineSetter__, - message: __defineSetter__ is deprecated. - }] + no-restricted-properties: + - 2 + - object: assert + property: deepEqual + message: Use assert.deepStrictEqual(). + - object: assert + property: equal + message: Use assert.strictEqual() rather than assert.equal(). + - object: assert + property: notEqual + message: Use assert.notStrictEqual() rather than assert.notEqual(). + - property: __defineGetter__ + message: __defineGetter__ is deprecated. + - property: __defineSetter__, + message: __defineSetter__ is deprecated. # Stylistic Issues # http://eslint.org/docs/rules/#stylistic-issues @@ -86,7 +90,7 @@ rules: func-name-matching: 2 indent: [2, 2, {ArrayExpression: first, CallExpression: {arguments: first}, - MemberExpression: 1, + MemberExpression: 1, ObjectExpression: first, SwitchCase: 1}] key-spacing: [2, {mode: minimum}] diff --git a/lib/assert.js b/lib/assert.js index 892df6d9a0f4e2..7f69ba0c60e476 100644 --- a/lib/assert.js +++ b/lib/assert.js @@ -109,7 +109,7 @@ assert.ok = ok; // The equality assertion tests shallow, coercive equality with // ==. // assert.equal(actual, expected, message_opt); - +/* eslint-disable no-restricted-properties */ assert.equal = function equal(actual, expected, message) { if (actual != expected) fail(actual, expected, message, '==', assert.equal); }; @@ -127,7 +127,6 @@ assert.notEqual = function notEqual(actual, expected, message) { // The equivalence assertion tests a deep equality relation. // assert.deepEqual(actual, expected, message_opt); -/* eslint-disable no-restricted-properties */ assert.deepEqual = function deepEqual(actual, expected, message) { if (!_deepEqual(actual, expected, false)) { fail(actual, expected, message, 'deepEqual', assert.deepEqual); From c6618df2cc7b8ca237b471dd2a937979c6c682af Mon Sep 17 00:00:00 2001 From: Adrian Estrada Date: Sun, 8 Jan 2017 22:36:59 -0500 Subject: [PATCH 198/291] test: improve test stream transform constructor * new test for the error when a transform function is not specified * use let instead of var * use assert.strictEqual instead of assert.equal * use arrow functions PR-URL: https://github.com/nodejs/node/pull/10699 Reviewed-By: James M Snell Reviewed-By: Colin Ihrig --- ...test-stream-transform-constructor-set-methods.js | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/test/parallel/test-stream-transform-constructor-set-methods.js b/test/parallel/test-stream-transform-constructor-set-methods.js index 02ef9f55cb4460..1423f4de10942d 100644 --- a/test/parallel/test-stream-transform-constructor-set-methods.js +++ b/test/parallel/test-stream-transform-constructor-set-methods.js @@ -21,12 +21,19 @@ const t = new Transform({ flush: _flush }); +const t2 = new Transform({}); + t.end(Buffer.from('blerg')); t.resume(); -process.on('exit', function() { +assert.throws(() => { + t2.end(Buffer.from('blerg')); +}, /^Error: _transform\(\) is not implemented$/); + + +process.on('exit', () => { assert.strictEqual(t._transform, _transform); assert.strictEqual(t._flush, _flush); - assert(_transformCalled); - assert(_flushCalled); + assert.strictEqual(_transformCalled, true); + assert.strictEqual(_flushCalled, true); }); From 825842c18559aeab2f1d74707e41ae91616d9e10 Mon Sep 17 00:00:00 2001 From: Sam Roberts Date: Wed, 21 Dec 2016 10:16:19 -0800 Subject: [PATCH 199/291] test: getgroups() may contain duplicate GIDs Some systems may have multiple group names with the same group ID, in which case getgroups() returns duplicate values, where `id -G` will filter the duplicates. Unique and sort the arrays so they can be compared. PR-URL: https://github.com/nodejs/node/pull/10389 Reviewed-By: James M Snell Reviewed-By: Gibson Fahnestock Reviewed-By: Michael Dawson --- test/parallel/test-process-getgroups.js | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/test/parallel/test-process-getgroups.js b/test/parallel/test-process-getgroups.js index 2d7a93c9a32c75..390f188cf5bf4d 100644 --- a/test/parallel/test-process-getgroups.js +++ b/test/parallel/test-process-getgroups.js @@ -1,21 +1,23 @@ 'use strict'; const common = require('../common'); -const assert = require('assert'); -const exec = require('child_process').exec; + +// Check `id -G` and `process.getgroups()` return same groups. if (common.isOSX) { common.skip('Output of `id -G` is unreliable on Darwin.'); return; } +const assert = require('assert'); +const exec = require('child_process').exec; if (typeof process.getgroups === 'function') { - const groups = process.getgroups(); + const groups = unique(process.getgroups()); assert(Array.isArray(groups)); assert(groups.length > 0); exec('id -G', function(err, stdout) { assert.ifError(err); - const real_groups = stdout.match(/\d+/g).map(Number); - assert.strictEqual(groups.length, real_groups.length); + const real_groups = unique(stdout.match(/\d+/g).map(Number)); + assert.deepStrictEqual(groups, real_groups); check(groups, real_groups); check(real_groups, groups); }); @@ -24,3 +26,7 @@ if (typeof process.getgroups === 'function') { function check(a, b) { for (let i = 0; i < a.length; ++i) assert.notStrictEqual(b.indexOf(a[i]), -1); } + +function unique(groups) { + return [...new Set(groups)].sort(); +} From 78a495e1a4505592cdd1cb8ac40dcd2535ab3bea Mon Sep 17 00:00:00 2001 From: Sam Roberts Date: Thu, 12 Jan 2017 11:32:53 -0800 Subject: [PATCH 200/291] eslint: remove dangling eslint symlink Reapplication of https://github.com/nodejs/node/pull/9299 since the symlink was re-added in f44969a5a. PR-URL: https://github.com/nodejs/node/pull/10771 Reviewed-By: Colin Ihrig Reviewed-By: Anna Henningsen --- tools/eslint/node_modules/.bin/eslint | 1 - 1 file changed, 1 deletion(-) delete mode 120000 tools/eslint/node_modules/.bin/eslint diff --git a/tools/eslint/node_modules/.bin/eslint b/tools/eslint/node_modules/.bin/eslint deleted file mode 120000 index 810e4bcb32af34..00000000000000 --- a/tools/eslint/node_modules/.bin/eslint +++ /dev/null @@ -1 +0,0 @@ -../eslint/bin/eslint.js \ No newline at end of file From 4a7bb5b4d1ef1f7e60904eb297e714f72f8c4eb8 Mon Sep 17 00:00:00 2001 From: Adrian Estrada Date: Thu, 12 Jan 2017 09:14:14 -0500 Subject: [PATCH 201/291] test: improve the code in test-crypto-dh * validate the errors for all assert.throws * use arrow functions PR-URL: https://github.com/nodejs/node/pull/10734 Reviewed-By: James M Snell Reviewed-By: Colin Ihrig Reviewed-By: Luigi Pinca Reviewed-By: Michael Dawson --- test/parallel/test-crypto-dh.js | 70 +++++++++++++++++++-------------- 1 file changed, 41 insertions(+), 29 deletions(-) diff --git a/test/parallel/test-crypto-dh.js b/test/parallel/test-crypto-dh.js index b76e188bc6f0d6..95a6df6fee58bb 100644 --- a/test/parallel/test-crypto-dh.js +++ b/test/parallel/test-crypto-dh.js @@ -19,25 +19,28 @@ let key2 = dh2.generateKeys('hex'); let secret1 = dh1.computeSecret(key2, 'hex', 'base64'); let secret2 = dh2.computeSecret(key1, 'latin1', 'buffer'); -assert.strictEqual(secret1, secret2.toString('base64')); +assert.strictEqual(secret2.toString('base64'), secret1); assert.strictEqual(dh1.verifyError, 0); assert.strictEqual(dh2.verifyError, 0); -assert.throws(function() { +const argumentsError = + /^TypeError: First argument should be number, string or Buffer$/; + +assert.throws(() => { crypto.createDiffieHellman([0x1, 0x2]); -}); +}, argumentsError); -assert.throws(function() { - crypto.createDiffieHellman(function() { }); -}); +assert.throws(() => { + crypto.createDiffieHellman(() => { }); +}, argumentsError); -assert.throws(function() { +assert.throws(() => { crypto.createDiffieHellman(/abc/); -}); +}, argumentsError); -assert.throws(function() { +assert.throws(() => { crypto.createDiffieHellman({}); -}); +}, argumentsError); // Create "another dh1" using generated keys from dh1, // and compute secret again @@ -56,21 +59,29 @@ const secret3 = dh3.computeSecret(key2, 'hex', 'base64'); assert.strictEqual(secret1, secret3); +const wrongBlockLength = + new RegExp('^Error: error:0606506D:digital envelope' + + ' routines:EVP_DecryptFinal_ex:wrong final block length$'); + // Run this one twice to make sure that the dh3 clears its error properly { const c = crypto.createDecipheriv('aes-128-ecb', crypto.randomBytes(16), ''); - assert.throws(function() { c.final('utf8'); }, /wrong final block length/); + assert.throws(() => { + c.final('utf8'); + }, wrongBlockLength); } -assert.throws(function() { - dh3.computeSecret(''); -}, /key is too small/i); - { const c = crypto.createDecipheriv('aes-128-ecb', crypto.randomBytes(16), ''); - assert.throws(function() { c.final('utf8'); }, /wrong final block length/); + assert.throws(() => { + c.final('utf8'); + }, wrongBlockLength); } +assert.throws(() => { + dh3.computeSecret(''); +}, /^Error: Supplied key is too small$/); + // Create a shared using a DH group. const alice = crypto.createDiffieHellmanGroup('modp5'); const bob = crypto.createDiffieHellmanGroup('modp5'); @@ -176,9 +187,9 @@ assert(firstByte === 6 || firstByte === 7); const ecdh3 = crypto.createECDH('secp256k1'); const key3 = ecdh3.generateKeys(); -assert.throws(function() { +assert.throws(() => { ecdh2.computeSecret(key3, 'latin1', 'buffer'); -}); +}, /^Error: Failed to translate Buffer to a EC_POINT$/); // ECDH should allow .setPrivateKey()/.setPublicKey() const ecdh4 = crypto.createECDH('prime256v1'); @@ -186,20 +197,21 @@ const ecdh4 = crypto.createECDH('prime256v1'); ecdh4.setPrivateKey(ecdh1.getPrivateKey()); ecdh4.setPublicKey(ecdh1.getPublicKey()); -assert.throws(function() { +assert.throws(() => { ecdh4.setPublicKey(ecdh3.getPublicKey()); -}, /Failed to convert Buffer to EC_POINT/); +}, /^Error: Failed to convert Buffer to EC_POINT$/); // Verify that we can use ECDH without having to use newly generated keys. const ecdh5 = crypto.createECDH('secp256k1'); // Verify errors are thrown when retrieving keys from an uninitialized object. -assert.throws(function() { +assert.throws(() => { ecdh5.getPublicKey(); -}, /Failed to get ECDH public key/); -assert.throws(function() { +}, /^Error: Failed to get ECDH public key$/); + +assert.throws(() => { ecdh5.getPrivateKey(); -}, /Failed to get ECDH private key/); +}, /^Error: Failed to get ECDH private key$/); // A valid private key for the secp256k1 curve. const cafebabeKey = 'cafebabe'.repeat(8); @@ -245,10 +257,10 @@ assert.strictEqual(ecdh5.getPublicKey('hex', 'compressed'), cafebabePubPtComp); // Show why allowing the public key to be set on this type does not make sense. ecdh5.setPublicKey(peerPubPtComp, 'hex'); assert.strictEqual(ecdh5.getPublicKey('hex'), peerPubPtUnComp); -assert.throws(function() { +assert.throws(() => { // Error because the public key does not match the private key anymore. ecdh5.computeSecret(peerPubPtComp, 'hex', 'hex'); -}, /Invalid key pair/); +}, /^Error: Invalid key pair$/); // Set to a valid key to show that later attempts to set an invalid key are // rejected. @@ -258,10 +270,10 @@ ecdh5.setPrivateKey(cafebabeKey, 'hex'); '0000000000000000000000000000000000000000000000000000000000000000', 'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141', 'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF', -].forEach(function(element, index, object) { - assert.throws(function() { +].forEach((element) => { + assert.throws(() => { ecdh5.setPrivateKey(element, 'hex'); - }, /Private key is not valid for specified curve/); + }, /^Error: Private key is not valid for specified curve.$/); // Verify object state did not change. assert.strictEqual(ecdh5.getPrivateKey('hex'), cafebabeKey); }); From d751afae0fa05586a66cb5bea3e99b58862ee712 Mon Sep 17 00:00:00 2001 From: cjihrig Date: Wed, 11 Jan 2017 15:30:55 -0500 Subject: [PATCH 202/291] cluster: refactor module into multiple files This commit splits the existing cluster module into several internal modules. More specifically, the cluster master and worker implementations are separated, and the various data structures are separated. PR-URL: https://github.com/nodejs/node/pull/10746 Reviewed-By: James M Snell Reviewed-By: Sam Roberts --- lib/cluster.js | 769 +----------------- lib/internal/cluster.js | 4 - lib/internal/cluster/child.js | 224 +++++ lib/internal/cluster/master.js | 367 +++++++++ lib/internal/cluster/round_robin_handle.js | 115 +++ lib/internal/cluster/shared_handle.js | 48 ++ lib/internal/cluster/utils.js | 44 + lib/internal/cluster/worker.js | 63 ++ node.gyp | 7 +- .../test-cluster-disconnect-handles.js | 2 +- 10 files changed, 871 insertions(+), 772 deletions(-) delete mode 100644 lib/internal/cluster.js create mode 100644 lib/internal/cluster/child.js create mode 100644 lib/internal/cluster/master.js create mode 100644 lib/internal/cluster/round_robin_handle.js create mode 100644 lib/internal/cluster/shared_handle.js create mode 100644 lib/internal/cluster/utils.js create mode 100644 lib/internal/cluster/worker.js diff --git a/lib/cluster.js b/lib/cluster.js index a12b83cd0c34c0..02bf3d8f600776 100644 --- a/lib/cluster.js +++ b/lib/cluster.js @@ -1,768 +1,5 @@ 'use strict'; -const EventEmitter = require('events'); -const assert = require('assert'); -const dgram = require('dgram'); -const fork = require('child_process').fork; -const net = require('net'); -const util = require('util'); -const internalUtil = require('internal/util'); -const SCHED_NONE = 1; -const SCHED_RR = 2; - -const uv = process.binding('uv'); - -const cluster = new EventEmitter(); -module.exports = cluster; -cluster.Worker = Worker; -cluster.isWorker = ('NODE_UNIQUE_ID' in process.env); -cluster.isMaster = (cluster.isWorker === false); - - -function Worker(options) { - if (!(this instanceof Worker)) - return new Worker(options); - - EventEmitter.call(this); - - if (options === null || typeof options !== 'object') - options = {}; - - this.exitedAfterDisconnect = undefined; - - Object.defineProperty(this, 'suicide', { - get: internalUtil.deprecate( - () => this.exitedAfterDisconnect, - 'worker.suicide is deprecated. Please use worker.exitedAfterDisconnect.'), - set: internalUtil.deprecate( - (val) => { this.exitedAfterDisconnect = val; }, - 'worker.suicide is deprecated. Please use worker.exitedAfterDisconnect.'), - enumerable: true - }); - - this.state = options.state || 'none'; - this.id = options.id | 0; - - if (options.process) { - this.process = options.process; - this.process.on('error', (code, signal) => - this.emit('error', code, signal) - ); - this.process.on('message', (message, handle) => - this.emit('message', message, handle) - ); - } -} -util.inherits(Worker, EventEmitter); - -Worker.prototype.kill = function() { - this.destroy.apply(this, arguments); -}; - -Worker.prototype.send = function() { - return this.process.send.apply(this.process, arguments); -}; - -Worker.prototype.isDead = function isDead() { - return this.process.exitCode != null || this.process.signalCode != null; -}; - -Worker.prototype.isConnected = function isConnected() { - return this.process.connected; -}; - -// Master/worker specific methods are defined in the *Init() functions. - -function SharedHandle(key, address, port, addressType, fd, flags) { - this.key = key; - this.workers = []; - this.handle = null; - this.errno = 0; - - // FIXME(bnoordhuis) Polymorphic return type for lack of a better solution. - var rval; - if (addressType === 'udp4' || addressType === 'udp6') - rval = dgram._createSocketHandle(address, port, addressType, fd, flags); - else - rval = net._createServerHandle(address, port, addressType, fd); - - if (typeof rval === 'number') - this.errno = rval; - else - this.handle = rval; -} - -SharedHandle.prototype.add = function(worker, send) { - assert(this.workers.indexOf(worker) === -1); - this.workers.push(worker); - send(this.errno, null, this.handle); -}; - -SharedHandle.prototype.remove = function(worker) { - var index = this.workers.indexOf(worker); - if (index === -1) return false; // The worker wasn't sharing this handle. - this.workers.splice(index, 1); - if (this.workers.length !== 0) return false; - this.handle.close(); - this.handle = null; - return true; -}; - - -// Start a round-robin server. Master accepts connections and distributes -// them over the workers. -function RoundRobinHandle(key, address, port, addressType, fd) { - this.key = key; - this.all = {}; - this.free = []; - this.handles = []; - this.handle = null; - this.server = net.createServer(assert.fail); - - if (fd >= 0) - this.server.listen({ fd: fd }); - else if (port >= 0) - this.server.listen(port, address); - else - this.server.listen(address); // UNIX socket path. - - this.server.once('listening', () => { - this.handle = this.server._handle; - this.handle.onconnection = (err, handle) => this.distribute(err, handle); - this.server._handle = null; - this.server = null; - }); -} - -RoundRobinHandle.prototype.add = function(worker, send) { - assert(worker.id in this.all === false); - this.all[worker.id] = worker; - - const done = () => { - if (this.handle.getsockname) { - var out = {}; - this.handle.getsockname(out); - // TODO(bnoordhuis) Check err. - send(null, { sockname: out }, null); - } else { - send(null, null, null); // UNIX socket. - } - this.handoff(worker); // In case there are connections pending. - }; - - if (this.server === null) return done(); - // Still busy binding. - this.server.once('listening', done); - this.server.once('error', function(err) { - // Hack: translate 'EADDRINUSE' error string back to numeric error code. - // It works but ideally we'd have some backchannel between the net and - // cluster modules for stuff like this. - var errno = uv['UV_' + err.errno]; - send(errno, null); - }); -}; - -RoundRobinHandle.prototype.remove = function(worker) { - if (worker.id in this.all === false) return false; - delete this.all[worker.id]; - var index = this.free.indexOf(worker); - if (index !== -1) this.free.splice(index, 1); - if (Object.getOwnPropertyNames(this.all).length !== 0) return false; - for (var handle; handle = this.handles.shift(); handle.close()); - this.handle.close(); - this.handle = null; - return true; -}; - -RoundRobinHandle.prototype.distribute = function(err, handle) { - this.handles.push(handle); - var worker = this.free.shift(); - if (worker) this.handoff(worker); -}; - -RoundRobinHandle.prototype.handoff = function(worker) { - if (worker.id in this.all === false) { - return; // Worker is closing (or has closed) the server. - } - var handle = this.handles.shift(); - if (handle === undefined) { - this.free.push(worker); // Add to ready queue again. - return; - } - var message = { act: 'newconn', key: this.key }; - - sendHelper(worker.process, message, handle, (reply) => { - if (reply.accepted) - handle.close(); - else - this.distribute(0, handle); // Worker is shutting down. Send to another. - this.handoff(worker); - }); -}; - - -if (cluster.isMaster) - masterInit(); -else - workerInit(); - -function masterInit() { - cluster.workers = {}; - - var intercom = new EventEmitter(); - cluster.settings = {}; - - // XXX(bnoordhuis) Fold cluster.schedulingPolicy into cluster.settings? - var schedulingPolicy = { - 'none': SCHED_NONE, - 'rr': SCHED_RR - }[process.env.NODE_CLUSTER_SCHED_POLICY]; - - if (schedulingPolicy === undefined) { - // FIXME Round-robin doesn't perform well on Windows right now due to the - // way IOCP is wired up. Bert is going to fix that, eventually. - schedulingPolicy = (process.platform === 'win32') ? SCHED_NONE : SCHED_RR; - } - - cluster.schedulingPolicy = schedulingPolicy; - cluster.SCHED_NONE = SCHED_NONE; // Leave it to the operating system. - cluster.SCHED_RR = SCHED_RR; // Master distributes connections. - - // Keyed on address:port:etc. When a worker dies, we walk over the handles - // and remove() the worker from each one. remove() may do a linear scan - // itself so we might end up with an O(n*m) operation. Ergo, FIXME. - const handles = require('internal/cluster').handles; - - var initialized = false; - cluster.setupMaster = function(options) { - var settings = { - args: process.argv.slice(2), - exec: process.argv[1], - execArgv: process.execArgv, - silent: false - }; - settings = util._extend(settings, cluster.settings); - settings = util._extend(settings, options || {}); - // Tell V8 to write profile data for each process to a separate file. - // Without --logfile=v8-%p.log, everything ends up in a single, unusable - // file. (Unusable because what V8 logs are memory addresses and each - // process has its own memory mappings.) - if (settings.execArgv.some((s) => s.startsWith('--prof')) && - !settings.execArgv.some((s) => s.startsWith('--logfile='))) { - settings.execArgv = settings.execArgv.concat(['--logfile=v8-%p.log']); - } - cluster.settings = settings; - if (initialized === true) - return process.nextTick(setupSettingsNT, settings); - initialized = true; - schedulingPolicy = cluster.schedulingPolicy; // Freeze policy. - assert(schedulingPolicy === SCHED_NONE || schedulingPolicy === SCHED_RR, - 'Bad cluster.schedulingPolicy: ' + schedulingPolicy); - - var hasDebugArg = process.execArgv.some(function(argv) { - return /^(--debug|--debug-brk)(=\d+)?$/.test(argv); - }); - - process.nextTick(setupSettingsNT, settings); - - // Send debug signal only if not started in debug mode, this helps a lot - // on windows, because RegisterDebugHandler is not called when node starts - // with --debug.* arg. - if (hasDebugArg) - return; - - process.on('internalMessage', function(message) { - if (message.cmd !== 'NODE_DEBUG_ENABLED') return; - var key; - for (key in cluster.workers) { - var worker = cluster.workers[key]; - if (worker.state === 'online' || worker.state === 'listening') { - process._debugProcess(worker.process.pid); - } else { - worker.once('online', function() { - process._debugProcess(this.process.pid); - }); - } - } - }); - }; - - function setupSettingsNT(settings) { - cluster.emit('setup', settings); - } - - var debugPortOffset = 1; - - function createWorkerProcess(id, env) { - var workerEnv = util._extend({}, process.env); - var execArgv = cluster.settings.execArgv.slice(); - var debugPort = 0; - - workerEnv = util._extend(workerEnv, env); - workerEnv.NODE_UNIQUE_ID = '' + id; - - for (var i = 0; i < execArgv.length; i++) { - var match = execArgv[i].match( - /^(--inspect|--debug|--debug-(brk|port))(=\d+)?$/ - ); - - if (match) { - if (debugPort === 0) { - debugPort = process.debugPort + debugPortOffset; - ++debugPortOffset; - } - - execArgv[i] = match[1] + '=' + debugPort; - } - } - - return fork(cluster.settings.exec, cluster.settings.args, { - env: workerEnv, - silent: cluster.settings.silent, - execArgv: execArgv, - stdio: cluster.settings.stdio, - gid: cluster.settings.gid, - uid: cluster.settings.uid - }); - } - - var ids = 0; - - function removeWorker(worker) { - assert(worker); - - delete cluster.workers[worker.id]; - - if (Object.keys(cluster.workers).length === 0) { - assert(Object.keys(handles).length === 0, 'Resource leak detected.'); - intercom.emit('disconnect'); - } - } - - function removeHandlesForWorker(worker) { - assert(worker); - - for (var key in handles) { - var handle = handles[key]; - if (handle.remove(worker)) delete handles[key]; - } - } - - cluster.fork = function(env) { - cluster.setupMaster(); - const id = ++ids; - const workerProcess = createWorkerProcess(id, env); - const worker = new Worker({ - id: id, - process: workerProcess - }); - - worker.on('message', function(message, handle) { - cluster.emit('message', this, message, handle); - }); - - worker.process.once('exit', function(exitCode, signalCode) { - /* - * Remove the worker from the workers list only - * if it has disconnected, otherwise we might - * still want to access it. - */ - if (!worker.isConnected()) { - removeHandlesForWorker(worker); - removeWorker(worker); - } - - worker.exitedAfterDisconnect = !!worker.exitedAfterDisconnect; - worker.state = 'dead'; - worker.emit('exit', exitCode, signalCode); - cluster.emit('exit', worker, exitCode, signalCode); - }); - - worker.process.once('disconnect', function() { - /* - * Now is a good time to remove the handles - * associated with this worker because it is - * not connected to the master anymore. - */ - removeHandlesForWorker(worker); - - /* - * Remove the worker from the workers list only - * if its process has exited. Otherwise, we might - * still want to access it. - */ - if (worker.isDead()) removeWorker(worker); - - worker.exitedAfterDisconnect = !!worker.exitedAfterDisconnect; - worker.state = 'disconnected'; - worker.emit('disconnect'); - cluster.emit('disconnect', worker); - }); - - worker.process.on('internalMessage', internal(worker, onmessage)); - process.nextTick(emitForkNT, worker); - cluster.workers[worker.id] = worker; - return worker; - }; - - function emitForkNT(worker) { - cluster.emit('fork', worker); - } - - cluster.disconnect = function(cb) { - var workers = Object.keys(cluster.workers); - if (workers.length === 0) { - process.nextTick(() => intercom.emit('disconnect')); - } else { - for (var key in workers) { - key = workers[key]; - if (cluster.workers[key].isConnected()) - cluster.workers[key].disconnect(); - } - } - if (cb) intercom.once('disconnect', cb); - }; - - Worker.prototype.disconnect = function() { - this.exitedAfterDisconnect = true; - send(this, { act: 'disconnect' }); - removeHandlesForWorker(this); - removeWorker(this); - return this; - }; - - Worker.prototype.destroy = function(signo) { - signo = signo || 'SIGTERM'; - var proc = this.process; - if (this.isConnected()) { - this.once('disconnect', () => proc.kill(signo)); - this.disconnect(); - return; - } - proc.kill(signo); - }; - - function onmessage(message, handle) { - var worker = this; - if (message.act === 'online') - online(worker); - else if (message.act === 'queryServer') - queryServer(worker, message); - else if (message.act === 'listening') - listening(worker, message); - else if (message.act === 'exitedAfterDisconnect') - exitedAfterDisconnect(worker, message); - else if (message.act === 'close') - close(worker, message); - } - - function online(worker) { - worker.state = 'online'; - worker.emit('online'); - cluster.emit('online', worker); - } - - function exitedAfterDisconnect(worker, message) { - worker.exitedAfterDisconnect = true; - send(worker, { ack: message.seq }); - } - - function queryServer(worker, message) { - // Stop processing if worker already disconnecting - if (worker.exitedAfterDisconnect) - return; - var args = [message.address, - message.port, - message.addressType, - message.fd, - message.index]; - var key = args.join(':'); - var handle = handles[key]; - if (handle === undefined) { - var constructor = RoundRobinHandle; - // UDP is exempt from round-robin connection balancing for what should - // be obvious reasons: it's connectionless. There is nothing to send to - // the workers except raw datagrams and that's pointless. - if (schedulingPolicy !== SCHED_RR || - message.addressType === 'udp4' || - message.addressType === 'udp6') { - constructor = SharedHandle; - } - handles[key] = handle = new constructor(key, - message.address, - message.port, - message.addressType, - message.fd, - message.flags); - } - if (!handle.data) handle.data = message.data; - - // Set custom server data - handle.add(worker, function(errno, reply, handle) { - reply = util._extend({ - errno: errno, - key: key, - ack: message.seq, - data: handles[key].data - }, reply); - if (errno) delete handles[key]; // Gives other workers a chance to retry. - send(worker, reply, handle); - }); - } - - function listening(worker, message) { - var info = { - addressType: message.addressType, - address: message.address, - port: message.port, - fd: message.fd - }; - worker.state = 'listening'; - worker.emit('listening', info); - cluster.emit('listening', worker, info); - } - - // Server in worker is closing, remove from list. The handle may have been - // removed by a prior call to removeHandlesForWorker() so guard against that. - function close(worker, message) { - var key = message.key; - var handle = handles[key]; - if (handle && handle.remove(worker)) delete handles[key]; - } - - function send(worker, message, handle, cb) { - return sendHelper(worker.process, message, handle, cb); - } -} - - -function workerInit() { - var handles = {}; - var indexes = {}; - - // Called from src/node.js - cluster._setupWorker = function() { - var worker = new Worker({ - id: +process.env.NODE_UNIQUE_ID | 0, - process: process, - state: 'online' - }); - cluster.worker = worker; - process.once('disconnect', function() { - worker.emit('disconnect'); - if (!worker.exitedAfterDisconnect) { - // Unexpected disconnect, master exited, or some such nastiness, so - // worker exits immediately. - process.exit(0); - } - }); - process.on('internalMessage', internal(worker, onmessage)); - send({ act: 'online' }); - function onmessage(message, handle) { - if (message.act === 'newconn') - onconnection(message, handle); - else if (message.act === 'disconnect') - _disconnect.call(worker, true); - } - }; - - // obj is a net#Server or a dgram#Socket object. - cluster._getServer = function(obj, options, cb) { - const indexesKey = [ options.address, - options.port, - options.addressType, - options.fd ].join(':'); - if (indexes[indexesKey] === undefined) - indexes[indexesKey] = 0; - else - indexes[indexesKey]++; - - const message = util._extend({ - act: 'queryServer', - index: indexes[indexesKey], - data: null - }, options); - - // Set custom data on handle (i.e. tls tickets key) - if (obj._getServerData) message.data = obj._getServerData(); - send(message, function(reply, handle) { - if (obj._setServerData) obj._setServerData(reply.data); - - if (handle) - shared(reply, handle, indexesKey, cb); // Shared listen socket. - else - rr(reply, indexesKey, cb); // Round-robin. - }); - obj.once('listening', function() { - cluster.worker.state = 'listening'; - const address = obj.address(); - message.act = 'listening'; - message.port = address && address.port || options.port; - send(message); - }); - }; - - // Shared listen socket. - function shared(message, handle, indexesKey, cb) { - var key = message.key; - // Monkey-patch the close() method so we can keep track of when it's - // closed. Avoids resource leaks when the handle is short-lived. - var close = handle.close; - handle.close = function() { - send({ act: 'close', key: key }); - delete handles[key]; - delete indexes[indexesKey]; - return close.apply(this, arguments); - }; - assert(handles[key] === undefined); - handles[key] = handle; - cb(message.errno, handle); - } - - // Round-robin. Master distributes handles across workers. - function rr(message, indexesKey, cb) { - if (message.errno) - return cb(message.errno, null); - - var key = message.key; - function listen(backlog) { - // TODO(bnoordhuis) Send a message to the master that tells it to - // update the backlog size. The actual backlog should probably be - // the largest requested size by any worker. - return 0; - } - - function close() { - // lib/net.js treats server._handle.close() as effectively synchronous. - // That means there is a time window between the call to close() and - // the ack by the master process in which we can still receive handles. - // onconnection() below handles that by sending those handles back to - // the master. - if (key === undefined) return; - send({ act: 'close', key: key }); - delete handles[key]; - delete indexes[indexesKey]; - key = undefined; - } - - function getsockname(out) { - if (key) util._extend(out, message.sockname); - return 0; - } - - // XXX(bnoordhuis) Probably no point in implementing ref() and unref() - // because the control channel is going to keep the worker alive anyway. - function ref() { - } - - function unref() { - } - - // Faux handle. Mimics a TCPWrap with just enough fidelity to get away - // with it. Fools net.Server into thinking that it's backed by a real - // handle. - var handle = { - close: close, - listen: listen, - ref: ref, - unref: unref, - }; - if (message.sockname) { - handle.getsockname = getsockname; // TCP handles only. - } - assert(handles[key] === undefined); - handles[key] = handle; - cb(0, handle); - } - - // Round-robin connection. - function onconnection(message, handle) { - var key = message.key; - var server = handles[key]; - var accepted = server !== undefined; - send({ ack: message.seq, accepted: accepted }); - if (accepted) server.onconnection(0, handle); - } - - Worker.prototype.disconnect = function() { - _disconnect.call(this); - return this; - }; - - Worker.prototype.destroy = function() { - this.exitedAfterDisconnect = true; - if (!this.isConnected()) { - process.exit(0); - } else { - send({ act: 'exitedAfterDisconnect' }, () => process.disconnect()); - process.once('disconnect', () => process.exit(0)); - } - }; - - function send(message, cb) { - return sendHelper(process, message, null, cb); - } - - function _disconnect(masterInitiated) { - this.exitedAfterDisconnect = true; - let waitingCount = 1; - - function checkWaitingCount() { - waitingCount--; - if (waitingCount === 0) { - // If disconnect is worker initiated, wait for ack to be sure - // exitedAfterDisconnect is properly set in the master, otherwise, if - // it's master initiated there's no need to send the - // exitedAfterDisconnect message - if (masterInitiated) { - process.disconnect(); - } else { - send({ act: 'exitedAfterDisconnect' }, () => process.disconnect()); - } - } - } - - for (const key in handles) { - const handle = handles[key]; - delete handles[key]; - waitingCount++; - - if (handle.owner) - handle.owner.close(checkWaitingCount); - else - handle.close(checkWaitingCount); - } - - checkWaitingCount(); - } -} - - -var seq = 0; -var callbacks = {}; -function sendHelper(proc, message, handle, cb) { - if (!proc.connected) - return false; - - // Mark message as internal. See INTERNAL_PREFIX in lib/child_process.js - message = util._extend({ cmd: 'NODE_CLUSTER' }, message); - if (cb) callbacks[seq] = cb; - message.seq = seq; - seq += 1; - return proc.send(message, handle); -} - - -// Returns an internalMessage listener that hands off normal messages -// to the callback but intercepts and redirects ACK messages. -function internal(worker, cb) { - return function(message, handle) { - if (message.cmd !== 'NODE_CLUSTER') return; - var fn = cb; - if (message.ack !== undefined && callbacks[message.ack] !== undefined) { - fn = callbacks[message.ack]; - delete callbacks[message.ack]; - } - fn.apply(worker, arguments); - }; -} +module.exports = ('NODE_UNIQUE_ID' in process.env) ? + require('internal/cluster/child') : + require('internal/cluster/master'); diff --git a/lib/internal/cluster.js b/lib/internal/cluster.js deleted file mode 100644 index 8380ea7482c670..00000000000000 --- a/lib/internal/cluster.js +++ /dev/null @@ -1,4 +0,0 @@ -'use strict'; - -// Used in tests. -exports.handles = {}; diff --git a/lib/internal/cluster/child.js b/lib/internal/cluster/child.js new file mode 100644 index 00000000000000..3275eec720c738 --- /dev/null +++ b/lib/internal/cluster/child.js @@ -0,0 +1,224 @@ +'use strict'; +const assert = require('assert'); +const util = require('util'); +const EventEmitter = require('events'); +const Worker = require('internal/cluster/worker'); +const { internal, sendHelper } = require('internal/cluster/utils'); +const cluster = new EventEmitter(); +const handles = {}; +const indexes = {}; +const noop = () => {}; + +module.exports = cluster; + +cluster.isWorker = true; +cluster.isMaster = false; +cluster.worker = null; +cluster.Worker = Worker; + +cluster._setupWorker = function() { + const worker = new Worker({ + id: +process.env.NODE_UNIQUE_ID | 0, + process: process, + state: 'online' + }); + + cluster.worker = worker; + + process.once('disconnect', () => { + worker.emit('disconnect'); + + if (!worker.exitedAfterDisconnect) { + // Unexpected disconnect, master exited, or some such nastiness, so + // worker exits immediately. + process.exit(0); + } + }); + + process.on('internalMessage', internal(worker, onmessage)); + send({ act: 'online' }); + + function onmessage(message, handle) { + if (message.act === 'newconn') + onconnection(message, handle); + else if (message.act === 'disconnect') + _disconnect.call(worker, true); + } +}; + +// obj is a net#Server or a dgram#Socket object. +cluster._getServer = function(obj, options, cb) { + const indexesKey = [options.address, + options.port, + options.addressType, + options.fd ].join(':'); + + if (indexes[indexesKey] === undefined) + indexes[indexesKey] = 0; + else + indexes[indexesKey]++; + + const message = util._extend({ + act: 'queryServer', + index: indexes[indexesKey], + data: null + }, options); + + // Set custom data on handle (i.e. tls tickets key) + if (obj._getServerData) + message.data = obj._getServerData(); + + send(message, (reply, handle) => { + if (typeof obj._setServerData === 'function') + obj._setServerData(reply.data); + + if (handle) + shared(reply, handle, indexesKey, cb); // Shared listen socket. + else + rr(reply, indexesKey, cb); // Round-robin. + }); + + obj.once('listening', () => { + cluster.worker.state = 'listening'; + const address = obj.address(); + message.act = 'listening'; + message.port = address && address.port || options.port; + send(message); + }); +}; + +// Shared listen socket. +function shared(message, handle, indexesKey, cb) { + const key = message.key; + // Monkey-patch the close() method so we can keep track of when it's + // closed. Avoids resource leaks when the handle is short-lived. + const close = handle.close; + + handle.close = function() { + send({ act: 'close', key }); + delete handles[key]; + delete indexes[indexesKey]; + return close.apply(this, arguments); + }; + assert(handles[key] === undefined); + handles[key] = handle; + cb(message.errno, handle); +} + +// Round-robin. Master distributes handles across workers. +function rr(message, indexesKey, cb) { + if (message.errno) + return cb(message.errno, null); + + var key = message.key; + + function listen(backlog) { + // TODO(bnoordhuis) Send a message to the master that tells it to + // update the backlog size. The actual backlog should probably be + // the largest requested size by any worker. + return 0; + } + + function close() { + // lib/net.js treats server._handle.close() as effectively synchronous. + // That means there is a time window between the call to close() and + // the ack by the master process in which we can still receive handles. + // onconnection() below handles that by sending those handles back to + // the master. + if (key === undefined) + return; + + send({ act: 'close', key }); + delete handles[key]; + delete indexes[indexesKey]; + key = undefined; + } + + function getsockname(out) { + if (key) + util._extend(out, message.sockname); + + return 0; + } + + // Faux handle. Mimics a TCPWrap with just enough fidelity to get away + // with it. Fools net.Server into thinking that it's backed by a real + // handle. Use a noop function for ref() and unref() because the control + // channel is going to keep the worker alive anyway. + const handle = { close, listen, ref: noop, unref: noop }; + + if (message.sockname) { + handle.getsockname = getsockname; // TCP handles only. + } + + assert(handles[key] === undefined); + handles[key] = handle; + cb(0, handle); +} + +// Round-robin connection. +function onconnection(message, handle) { + const key = message.key; + const server = handles[key]; + const accepted = server !== undefined; + + send({ ack: message.seq, accepted }); + + if (accepted) + server.onconnection(0, handle); +} + +function send(message, cb) { + return sendHelper(process, message, null, cb); +} + +function _disconnect(masterInitiated) { + this.exitedAfterDisconnect = true; + let waitingCount = 1; + + function checkWaitingCount() { + waitingCount--; + + if (waitingCount === 0) { + // If disconnect is worker initiated, wait for ack to be sure + // exitedAfterDisconnect is properly set in the master, otherwise, if + // it's master initiated there's no need to send the + // exitedAfterDisconnect message + if (masterInitiated) { + process.disconnect(); + } else { + send({ act: 'exitedAfterDisconnect' }, () => process.disconnect()); + } + } + } + + for (const key in handles) { + const handle = handles[key]; + delete handles[key]; + waitingCount++; + + if (handle.owner) + handle.owner.close(checkWaitingCount); + else + handle.close(checkWaitingCount); + } + + checkWaitingCount(); +} + +// Extend generic Worker with methods specific to worker processes. +Worker.prototype.disconnect = function() { + _disconnect.call(this); + return this; +}; + +Worker.prototype.destroy = function() { + this.exitedAfterDisconnect = true; + + if (!this.isConnected()) { + process.exit(0); + } else { + send({ act: 'exitedAfterDisconnect' }, () => process.disconnect()); + process.once('disconnect', () => process.exit(0)); + } +}; diff --git a/lib/internal/cluster/master.js b/lib/internal/cluster/master.js new file mode 100644 index 00000000000000..9d5062f5427ffa --- /dev/null +++ b/lib/internal/cluster/master.js @@ -0,0 +1,367 @@ +'use strict'; +const assert = require('assert'); +const fork = require('child_process').fork; +const util = require('util'); +const EventEmitter = require('events'); +const RoundRobinHandle = require('internal/cluster/round_robin_handle'); +const SharedHandle = require('internal/cluster/shared_handle'); +const Worker = require('internal/cluster/worker'); +const { internal, sendHelper, handles } = require('internal/cluster/utils'); +const keys = Object.keys; +const cluster = new EventEmitter(); +const intercom = new EventEmitter(); +const SCHED_NONE = 1; +const SCHED_RR = 2; + +module.exports = cluster; + +cluster.isWorker = false; +cluster.isMaster = true; +cluster.Worker = Worker; +cluster.workers = {}; +cluster.settings = {}; +cluster.SCHED_NONE = SCHED_NONE; // Leave it to the operating system. +cluster.SCHED_RR = SCHED_RR; // Master distributes connections. + +var ids = 0; +var debugPortOffset = 1; +var initialized = false; + +// XXX(bnoordhuis) Fold cluster.schedulingPolicy into cluster.settings? +var schedulingPolicy = { + 'none': SCHED_NONE, + 'rr': SCHED_RR +}[process.env.NODE_CLUSTER_SCHED_POLICY]; + +if (schedulingPolicy === undefined) { + // FIXME Round-robin doesn't perform well on Windows right now due to the + // way IOCP is wired up. + schedulingPolicy = (process.platform === 'win32') ? SCHED_NONE : SCHED_RR; +} + +cluster.schedulingPolicy = schedulingPolicy; + +cluster.setupMaster = function(options) { + var settings = { + args: process.argv.slice(2), + exec: process.argv[1], + execArgv: process.execArgv, + silent: false + }; + settings = util._extend(settings, cluster.settings); + settings = util._extend(settings, options || {}); + + // Tell V8 to write profile data for each process to a separate file. + // Without --logfile=v8-%p.log, everything ends up in a single, unusable + // file. (Unusable because what V8 logs are memory addresses and each + // process has its own memory mappings.) + if (settings.execArgv.some((s) => s.startsWith('--prof')) && + !settings.execArgv.some((s) => s.startsWith('--logfile='))) { + settings.execArgv = settings.execArgv.concat(['--logfile=v8-%p.log']); + } + + cluster.settings = settings; + + if (initialized === true) + return process.nextTick(setupSettingsNT, settings); + + initialized = true; + schedulingPolicy = cluster.schedulingPolicy; // Freeze policy. + assert(schedulingPolicy === SCHED_NONE || schedulingPolicy === SCHED_RR, + `Bad cluster.schedulingPolicy: ${schedulingPolicy}`); + + const hasDebugArg = process.execArgv.some((argv) => { + return /^(--debug|--debug-brk)(=\d+)?$/.test(argv); + }); + + process.nextTick(setupSettingsNT, settings); + + // Send debug signal only if not started in debug mode, this helps a lot + // on windows, because RegisterDebugHandler is not called when node starts + // with --debug.* arg. + if (hasDebugArg) + return; + + process.on('internalMessage', (message) => { + if (message.cmd !== 'NODE_DEBUG_ENABLED') + return; + + var key; + for (key in cluster.workers) { + const worker = cluster.workers[key]; + + if (worker.state === 'online' || worker.state === 'listening') { + process._debugProcess(worker.process.pid); + } else { + worker.once('online', function() { + process._debugProcess(this.process.pid); + }); + } + } + }); +}; + +function setupSettingsNT(settings) { + cluster.emit('setup', settings); +} + +function createWorkerProcess(id, env) { + var workerEnv = util._extend({}, process.env); + var execArgv = cluster.settings.execArgv.slice(); + var debugPort = 0; + + workerEnv = util._extend(workerEnv, env); + workerEnv.NODE_UNIQUE_ID = '' + id; + + for (var i = 0; i < execArgv.length; i++) { + const match = execArgv[i].match( + /^(--inspect|--debug|--debug-(brk|port))(=\d+)?$/ + ); + + if (match) { + if (debugPort === 0) { + debugPort = process.debugPort + debugPortOffset; + ++debugPortOffset; + } + + execArgv[i] = match[1] + '=' + debugPort; + } + } + + return fork(cluster.settings.exec, cluster.settings.args, { + env: workerEnv, + silent: cluster.settings.silent, + execArgv: execArgv, + stdio: cluster.settings.stdio, + gid: cluster.settings.gid, + uid: cluster.settings.uid + }); +} + +function removeWorker(worker) { + assert(worker); + delete cluster.workers[worker.id]; + + if (keys(cluster.workers).length === 0) { + assert(keys(handles).length === 0, 'Resource leak detected.'); + intercom.emit('disconnect'); + } +} + +function removeHandlesForWorker(worker) { + assert(worker); + + for (var key in handles) { + const handle = handles[key]; + + if (handle.remove(worker)) + delete handles[key]; + } +} + +cluster.fork = function(env) { + cluster.setupMaster(); + const id = ++ids; + const workerProcess = createWorkerProcess(id, env); + const worker = new Worker({ + id: id, + process: workerProcess + }); + + worker.on('message', function(message, handle) { + cluster.emit('message', this, message, handle); + }); + + worker.process.once('exit', (exitCode, signalCode) => { + /* + * Remove the worker from the workers list only + * if it has disconnected, otherwise we might + * still want to access it. + */ + if (!worker.isConnected()) { + removeHandlesForWorker(worker); + removeWorker(worker); + } + + worker.exitedAfterDisconnect = !!worker.exitedAfterDisconnect; + worker.state = 'dead'; + worker.emit('exit', exitCode, signalCode); + cluster.emit('exit', worker, exitCode, signalCode); + }); + + worker.process.once('disconnect', () => { + /* + * Now is a good time to remove the handles + * associated with this worker because it is + * not connected to the master anymore. + */ + removeHandlesForWorker(worker); + + /* + * Remove the worker from the workers list only + * if its process has exited. Otherwise, we might + * still want to access it. + */ + if (worker.isDead()) + removeWorker(worker); + + worker.exitedAfterDisconnect = !!worker.exitedAfterDisconnect; + worker.state = 'disconnected'; + worker.emit('disconnect'); + cluster.emit('disconnect', worker); + }); + + worker.process.on('internalMessage', internal(worker, onmessage)); + process.nextTick(emitForkNT, worker); + cluster.workers[worker.id] = worker; + return worker; +}; + +function emitForkNT(worker) { + cluster.emit('fork', worker); +} + +cluster.disconnect = function(cb) { + const workers = keys(cluster.workers); + + if (workers.length === 0) { + process.nextTick(() => intercom.emit('disconnect')); + } else { + for (var key in workers) { + key = workers[key]; + + if (cluster.workers[key].isConnected()) + cluster.workers[key].disconnect(); + } + } + + if (typeof cb === 'function') + intercom.once('disconnect', cb); +}; + +function onmessage(message, handle) { + const worker = this; + + if (message.act === 'online') + online(worker); + else if (message.act === 'queryServer') + queryServer(worker, message); + else if (message.act === 'listening') + listening(worker, message); + else if (message.act === 'exitedAfterDisconnect') + exitedAfterDisconnect(worker, message); + else if (message.act === 'close') + close(worker, message); +} + +function online(worker) { + worker.state = 'online'; + worker.emit('online'); + cluster.emit('online', worker); +} + +function exitedAfterDisconnect(worker, message) { + worker.exitedAfterDisconnect = true; + send(worker, { ack: message.seq }); +} + +function queryServer(worker, message) { + // Stop processing if worker already disconnecting + if (worker.exitedAfterDisconnect) + return; + + const args = [message.address, + message.port, + message.addressType, + message.fd, + message.index]; + const key = args.join(':'); + var handle = handles[key]; + + if (handle === undefined) { + var constructor = RoundRobinHandle; + // UDP is exempt from round-robin connection balancing for what should + // be obvious reasons: it's connectionless. There is nothing to send to + // the workers except raw datagrams and that's pointless. + if (schedulingPolicy !== SCHED_RR || + message.addressType === 'udp4' || + message.addressType === 'udp6') { + constructor = SharedHandle; + } + + handles[key] = handle = new constructor(key, + message.address, + message.port, + message.addressType, + message.fd, + message.flags); + } + + if (!handle.data) + handle.data = message.data; + + // Set custom server data + handle.add(worker, (errno, reply, handle) => { + reply = util._extend({ + errno: errno, + key: key, + ack: message.seq, + data: handles[key].data + }, reply); + + if (errno) + delete handles[key]; // Gives other workers a chance to retry. + + send(worker, reply, handle); + }); +} + +function listening(worker, message) { + const info = { + addressType: message.addressType, + address: message.address, + port: message.port, + fd: message.fd + }; + + worker.state = 'listening'; + worker.emit('listening', info); + cluster.emit('listening', worker, info); +} + +// Server in worker is closing, remove from list. The handle may have been +// removed by a prior call to removeHandlesForWorker() so guard against that. +function close(worker, message) { + const key = message.key; + const handle = handles[key]; + + if (handle && handle.remove(worker)) + delete handles[key]; +} + +function send(worker, message, handle, cb) { + return sendHelper(worker.process, message, handle, cb); +} + +// Extend generic Worker with methods specific to the master process. +Worker.prototype.disconnect = function() { + this.exitedAfterDisconnect = true; + send(this, { act: 'disconnect' }); + removeHandlesForWorker(this); + removeWorker(this); + return this; +}; + +Worker.prototype.destroy = function(signo) { + const proc = this.process; + + signo = signo || 'SIGTERM'; + + if (this.isConnected()) { + this.once('disconnect', () => proc.kill(signo)); + this.disconnect(); + return; + } + + proc.kill(signo); +}; diff --git a/lib/internal/cluster/round_robin_handle.js b/lib/internal/cluster/round_robin_handle.js new file mode 100644 index 00000000000000..5dbc205426b1db --- /dev/null +++ b/lib/internal/cluster/round_robin_handle.js @@ -0,0 +1,115 @@ +'use strict'; +const assert = require('assert'); +const net = require('net'); +const { sendHelper } = require('internal/cluster/utils'); +const getOwnPropertyNames = Object.getOwnPropertyNames; +const uv = process.binding('uv'); + +module.exports = RoundRobinHandle; + +function RoundRobinHandle(key, address, port, addressType, fd) { + this.key = key; + this.all = {}; + this.free = []; + this.handles = []; + this.handle = null; + this.server = net.createServer(assert.fail); + + if (fd >= 0) + this.server.listen({ fd }); + else if (port >= 0) + this.server.listen(port, address); + else + this.server.listen(address); // UNIX socket path. + + this.server.once('listening', () => { + this.handle = this.server._handle; + this.handle.onconnection = (err, handle) => this.distribute(err, handle); + this.server._handle = null; + this.server = null; + }); +} + +RoundRobinHandle.prototype.add = function(worker, send) { + assert(worker.id in this.all === false); + this.all[worker.id] = worker; + + const done = () => { + if (this.handle.getsockname) { + const out = {}; + this.handle.getsockname(out); + // TODO(bnoordhuis) Check err. + send(null, { sockname: out }, null); + } else { + send(null, null, null); // UNIX socket. + } + + this.handoff(worker); // In case there are connections pending. + }; + + if (this.server === null) + return done(); + + // Still busy binding. + this.server.once('listening', done); + this.server.once('error', (err) => { + // Hack: translate 'EADDRINUSE' error string back to numeric error code. + // It works but ideally we'd have some backchannel between the net and + // cluster modules for stuff like this. + const errno = uv['UV_' + err.errno]; + send(errno, null); + }); +}; + +RoundRobinHandle.prototype.remove = function(worker) { + if (worker.id in this.all === false) + return false; + + delete this.all[worker.id]; + const index = this.free.indexOf(worker); + + if (index !== -1) + this.free.splice(index, 1); + + if (getOwnPropertyNames(this.all).length !== 0) + return false; + + for (var handle; handle = this.handles.shift(); handle.close()) + ; + + this.handle.close(); + this.handle = null; + return true; +}; + +RoundRobinHandle.prototype.distribute = function(err, handle) { + this.handles.push(handle); + const worker = this.free.shift(); + + if (worker) + this.handoff(worker); +}; + +RoundRobinHandle.prototype.handoff = function(worker) { + if (worker.id in this.all === false) { + return; // Worker is closing (or has closed) the server. + } + + const handle = this.handles.shift(); + + if (handle === undefined) { + this.free.push(worker); // Add to ready queue again. + return; + } + + const message = { act: 'newconn', key: this.key }; + + sendHelper(worker.process, message, handle, (reply) => { + if (reply.accepted) + handle.close(); + else + this.distribute(0, handle); // Worker is shutting down. Send to another. + + this.handoff(worker); + }); +}; diff --git a/lib/internal/cluster/shared_handle.js b/lib/internal/cluster/shared_handle.js new file mode 100644 index 00000000000000..c0663772426213 --- /dev/null +++ b/lib/internal/cluster/shared_handle.js @@ -0,0 +1,48 @@ +'use strict'; +const assert = require('assert'); +const dgram = require('dgram'); +const net = require('net'); + +module.exports = SharedHandle; + +function SharedHandle(key, address, port, addressType, fd, flags) { + this.key = key; + this.workers = []; + this.handle = null; + this.errno = 0; + + // FIXME(bnoordhuis) Polymorphic return type for lack of a better solution. + var rval; + + if (addressType === 'udp4' || addressType === 'udp6') + rval = dgram._createSocketHandle(address, port, addressType, fd, flags); + else + rval = net._createServerHandle(address, port, addressType, fd); + + if (typeof rval === 'number') + this.errno = rval; + else + this.handle = rval; +} + +SharedHandle.prototype.add = function(worker, send) { + assert(this.workers.indexOf(worker) === -1); + this.workers.push(worker); + send(this.errno, null, this.handle); +}; + +SharedHandle.prototype.remove = function(worker) { + const index = this.workers.indexOf(worker); + + if (index === -1) + return false; // The worker wasn't sharing this handle. + + this.workers.splice(index, 1); + + if (this.workers.length !== 0) + return false; + + this.handle.close(); + this.handle = null; + return true; +}; diff --git a/lib/internal/cluster/utils.js b/lib/internal/cluster/utils.js new file mode 100644 index 00000000000000..ba72ff90945d3c --- /dev/null +++ b/lib/internal/cluster/utils.js @@ -0,0 +1,44 @@ +'use strict'; +const util = require('util'); + +module.exports = { + sendHelper, + internal, + handles: {} // Used in tests. +}; + +const callbacks = {}; +var seq = 0; + +function sendHelper(proc, message, handle, cb) { + if (!proc.connected) + return false; + + // Mark message as internal. See INTERNAL_PREFIX in lib/child_process.js + message = util._extend({ cmd: 'NODE_CLUSTER' }, message); + + if (typeof cb === 'function') + callbacks[seq] = cb; + + message.seq = seq; + seq += 1; + return proc.send(message, handle); +} + +// Returns an internalMessage listener that hands off normal messages +// to the callback but intercepts and redirects ACK messages. +function internal(worker, cb) { + return function onInternalMessage(message, handle) { + if (message.cmd !== 'NODE_CLUSTER') + return; + + var fn = cb; + + if (message.ack !== undefined && callbacks[message.ack] !== undefined) { + fn = callbacks[message.ack]; + delete callbacks[message.ack]; + } + + fn.apply(worker, arguments); + }; +} diff --git a/lib/internal/cluster/worker.js b/lib/internal/cluster/worker.js new file mode 100644 index 00000000000000..fd46ed571076d5 --- /dev/null +++ b/lib/internal/cluster/worker.js @@ -0,0 +1,63 @@ +'use strict'; +const EventEmitter = require('events'); +const internalUtil = require('internal/util'); +const util = require('util'); +const defineProperty = Object.defineProperty; +const suicideDeprecationMessage = + 'worker.suicide is deprecated. Please use worker.exitedAfterDisconnect.'; + +module.exports = Worker; + +// Common Worker implementation shared between the cluster master and workers. +function Worker(options) { + if (!(this instanceof Worker)) + return new Worker(options); + + EventEmitter.call(this); + + if (options === null || typeof options !== 'object') + options = {}; + + this.exitedAfterDisconnect = undefined; + + defineProperty(this, 'suicide', { + get: internalUtil.deprecate( + () => this.exitedAfterDisconnect, + suicideDeprecationMessage), + set: internalUtil.deprecate( + (val) => { this.exitedAfterDisconnect = val; }, + suicideDeprecationMessage), + enumerable: true + }); + + this.state = options.state || 'none'; + this.id = options.id | 0; + + if (options.process) { + this.process = options.process; + this.process.on('error', (code, signal) => + this.emit('error', code, signal) + ); + this.process.on('message', (message, handle) => + this.emit('message', message, handle) + ); + } +} + +util.inherits(Worker, EventEmitter); + +Worker.prototype.kill = function() { + this.destroy.apply(this, arguments); +}; + +Worker.prototype.send = function() { + return this.process.send.apply(this.process, arguments); +}; + +Worker.prototype.isDead = function() { + return this.process.exitCode != null || this.process.signalCode != null; +}; + +Worker.prototype.isConnected = function() { + return this.process.connected; +}; diff --git a/node.gyp b/node.gyp index 3da08d5187f8e9..af10830de5dd8c 100644 --- a/node.gyp +++ b/node.gyp @@ -76,7 +76,12 @@ 'lib/zlib.js', 'lib/internal/buffer.js', 'lib/internal/child_process.js', - 'lib/internal/cluster.js', + 'lib/internal/cluster/child.js', + 'lib/internal/cluster/master.js', + 'lib/internal/cluster/round_robin_handle.js', + 'lib/internal/cluster/shared_handle.js', + 'lib/internal/cluster/utils.js', + 'lib/internal/cluster/worker.js', 'lib/internal/freelist.js', 'lib/internal/fs.js', 'lib/internal/linkedlist.js', diff --git a/test/parallel/test-cluster-disconnect-handles.js b/test/parallel/test-cluster-disconnect-handles.js index 680e316cf0ba92..4b481f0a7b1751 100644 --- a/test/parallel/test-cluster-disconnect-handles.js +++ b/test/parallel/test-cluster-disconnect-handles.js @@ -24,7 +24,7 @@ cluster.schedulingPolicy = cluster.SCHED_RR; // pending handle queue. if (cluster.isMaster) { let isKilling = false; - const handles = require('internal/cluster').handles; + const handles = require('internal/cluster/utils').handles; const address = common.hasIPv6 ? '[::1]' : common.localhostIPv4; cluster.setupMaster({ execArgv: [`--debug=${address}:${common.PORT}`] }); const worker = cluster.fork(); From 33af09fe6a6aebaddd0955c6fcd83124c3bcb934 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Wed, 11 Jan 2017 23:20:54 -0800 Subject: [PATCH 203/291] test,net: add tests for server.connections There were no tests confirming situations where server.connections should return `null`. Add a test for that situation. Expand existing server.connection test slightly to check value. Refactor (mostly spacing) code for server.connections setter. PR-URL: https://github.com/nodejs/node/pull/10762 Reviewed-By: James M Snell --- lib/net.js | 5 +-- .../test-net-server-connections-child-null.js | 44 +++++++++++++++++++ test/parallel/test-net-server-connections.js | 14 ++++-- 3 files changed, 56 insertions(+), 7 deletions(-) create mode 100644 test/parallel/test-net-server-connections-child-null.js diff --git a/lib/net.js b/lib/net.js index ce60d2f3521317..e4f97ab80debd5 100644 --- a/lib/net.js +++ b/lib/net.js @@ -1132,9 +1132,8 @@ function Server(options, connectionListener) { return this._connections; }, 'Server.connections property is deprecated. ' + 'Use Server.getConnections method instead.'), - set: internalUtil.deprecate((val) => { - return (this._connections = val); - }, 'Server.connections property is deprecated.'), + set: internalUtil.deprecate((val) => (this._connections = val), + 'Server.connections property is deprecated.'), configurable: true, enumerable: false }); diff --git a/test/parallel/test-net-server-connections-child-null.js b/test/parallel/test-net-server-connections-child-null.js new file mode 100644 index 00000000000000..a8a1346fec3370 --- /dev/null +++ b/test/parallel/test-net-server-connections-child-null.js @@ -0,0 +1,44 @@ +'use strict'; +const common = require('../common'); +const assert = require('assert'); +const fork = require('child_process').fork; +const net = require('net'); + +if (process.argv[2] === 'child') { + + process.on('message', (msg, socket) => { + socket.end('goodbye'); + }); + + process.send('hello'); + +} else { + + const child = fork(process.argv[1], ['child']); + + const runTest = common.mustCall(() => { + + const server = net.createServer(); + + // server.connections should start as 0 + assert.strictEqual(server.connections, 0); + server.on('connection', (socket) => { + child.send({what: 'socket'}, socket); + }); + server.on('close', () => { + child.kill(); + }); + + server.listen(0, common.mustCall(() => { + const connect = net.connect(server.address().port); + + connect.on('close', common.mustCall(() => { + // now server.connections should be null + assert.strictEqual(server.connections, null); + server.close(); + })); + })); + }); + + child.on('message', runTest); +} diff --git a/test/parallel/test-net-server-connections.js b/test/parallel/test-net-server-connections.js index 7ee1df1a544b95..01e535803a8f39 100644 --- a/test/parallel/test-net-server-connections.js +++ b/test/parallel/test-net-server-connections.js @@ -1,12 +1,18 @@ 'use strict'; -require('../common'); +const common = require('../common'); const assert = require('assert'); const net = require('net'); -// test that server.connections property is no longer enumerable now that it -// has been marked as deprecated - const server = new net.Server(); +const expectedWarning = 'Server.connections property is deprecated. ' + + 'Use Server.getConnections method instead.'; + +common.expectWarning('DeprecationWarning', expectedWarning); + +// test that server.connections property is no longer enumerable now that it +// has been marked as deprecated assert.strictEqual(Object.keys(server).indexOf('connections'), -1); + +assert.strictEqual(server.connections, 0); From e30e307a7003ff37bae9b217c869a39c1a38410c Mon Sep 17 00:00:00 2001 From: Eugene Ostroukhov Date: Fri, 18 Nov 2016 13:52:22 -0800 Subject: [PATCH 204/291] inspector: move options parsing As inspector functionality expands, more options will need to be added. Currently this requires changing adding function arguments, etc. This change packs the veriables into a single class that can be extended without changing APIs. PR-URL: https://github.com/nodejs/node/pull/9691 Reviewed-By: Ben Noordhuis --- node.gyp | 2 + src/debug-agent.cc | 16 ++-- src/debug-agent.h | 6 +- src/inspector_agent.cc | 25 +++--- src/inspector_agent.h | 5 +- src/node.cc | 165 ++++++++------------------------------ src/node_debug_options.cc | 144 +++++++++++++++++++++++++++++++++ src/node_debug_options.h | 51 ++++++++++++ 8 files changed, 260 insertions(+), 154 deletions(-) create mode 100644 src/node_debug_options.cc create mode 100644 src/node_debug_options.h diff --git a/node.gyp b/node.gyp index af10830de5dd8c..3fe0a9830fc2ac 100644 --- a/node.gyp +++ b/node.gyp @@ -159,6 +159,7 @@ 'src/node_config.cc', 'src/node_constants.cc', 'src/node_contextify.cc', + 'src/node_debug_options.cc', 'src/node_file.cc', 'src/node_http_parser.cc', 'src/node_javascript.cc', @@ -201,6 +202,7 @@ 'src/node.h', 'src/node_buffer.h', 'src/node_constants.h', + 'src/node_debug_options.h', 'src/node_file.h', 'src/node_http_parser.h', 'src/node_internals.h', diff --git a/src/debug-agent.cc b/src/debug-agent.cc index 2766702525d088..2d8ed8afc980ec 100644 --- a/src/debug-agent.cc +++ b/src/debug-agent.cc @@ -50,7 +50,6 @@ using v8::Value; Agent::Agent(Environment* env) : state_(kNone), - port_(5858), wait_(false), parent_env_(env), child_env_(nullptr), @@ -69,7 +68,7 @@ Agent::~Agent() { } -bool Agent::Start(const char* host, int port, bool wait) { +bool Agent::Start(const DebugOptions& options) { int err; if (state_ == kRunning) @@ -85,9 +84,8 @@ bool Agent::Start(const char* host, int port, bool wait) { goto async_init_failed; uv_unref(reinterpret_cast(&child_signal_)); - host_ = host; - port_ = port; - wait_ = wait; + options_ = options; + wait_ = options_.wait_for_connect(); err = uv_thread_create(&thread_, reinterpret_cast(ThreadCb), @@ -210,9 +208,11 @@ void Agent::InitAdaptor(Environment* env) { api->Set(String::NewFromUtf8(isolate, "host", NewStringType::kNormal).ToLocalChecked(), - String::NewFromUtf8(isolate, host_.data(), NewStringType::kNormal, - host_.size()).ToLocalChecked()); - api->Set(String::NewFromUtf8(isolate, "port"), Integer::New(isolate, port_)); + String::NewFromUtf8(isolate, options_.host_name().data(), + NewStringType::kNormal, + options_.host_name().size()).ToLocalChecked()); + api->Set(String::NewFromUtf8(isolate, "port"), + Integer::New(isolate, options_.port())); env->process_object()->Set(String::NewFromUtf8(isolate, "_debugAPI"), api); api_.Reset(env->isolate(), api); diff --git a/src/debug-agent.h b/src/debug-agent.h index 783403cf0920d1..0faa25f12470a9 100644 --- a/src/debug-agent.h +++ b/src/debug-agent.h @@ -25,6 +25,7 @@ #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS #include "node_mutex.h" +#include "node_debug_options.h" #include "util.h" #include "util-inl.h" #include "uv.h" @@ -76,7 +77,7 @@ class Agent { typedef void (*DispatchHandler)(node::Environment* env); // Start the debugger agent thread - bool Start(const char* host, int port, bool wait); + bool Start(const DebugOptions& options); // Listen for debug events void Enable(); // Stop the debugger agent @@ -114,9 +115,8 @@ class Agent { }; State state_; + DebugOptions options_; - std::string host_; - int port_; bool wait_; uv_sem_t start_sem_; diff --git a/src/inspector_agent.cc b/src/inspector_agent.cc index 8e72b3643c872c..dba4e0f9826004 100644 --- a/src/inspector_agent.cc +++ b/src/inspector_agent.cc @@ -131,7 +131,8 @@ class AgentImpl { explicit AgentImpl(node::Environment* env); // Start the inspector agent thread - bool Start(v8::Platform* platform, const char* path, int port, bool wait); + bool Start(v8::Platform* platform, const char* path, + const DebugOptions& options); // Stop the inspector agent void Stop(); @@ -168,6 +169,7 @@ class AgentImpl { void NotifyMessageReceived(); State ToState(State state); + DebugOptions options_; uv_sem_t start_sem_; ConditionVariable incoming_message_cond_; Mutex state_lock_; @@ -175,8 +177,6 @@ class AgentImpl { uv_loop_t child_loop_; InspectorAgentDelegate* delegate_; - - int port_; bool wait_; bool shutting_down_; State state_; @@ -192,6 +192,8 @@ class AgentImpl { InspectorSocketServer* server_; std::string script_name_; + std::string script_path_; + const std::string id_; friend class ChannelImpl; friend class DispatchOnInspectorBackendTask; @@ -316,7 +318,6 @@ class V8NodeInspector : public v8_inspector::V8InspectorClient { }; AgentImpl::AgentImpl(Environment* env) : delegate_(nullptr), - port_(0), wait_(false), shutting_down_(false), state_(State::kNew), @@ -396,7 +397,10 @@ void InspectorWrapConsoleCall(const v8::FunctionCallbackInfo& args) { } bool AgentImpl::Start(v8::Platform* platform, const char* path, - int port, bool wait) { + const DebugOptions& options) { + options_ = options; + wait_ = options.wait_for_connect(); + auto env = parent_env_; inspector_ = new V8NodeInspector(this, env, platform); platform_ = platform; @@ -408,9 +412,6 @@ bool AgentImpl::Start(v8::Platform* platform, const char* path, int err = uv_loop_init(&child_loop_); CHECK_EQ(err, 0); - port_ = port; - wait_ = wait; - err = uv_thread_create(&thread_, AgentImpl::ThreadCbIO, this); CHECK_EQ(err, 0); uv_sem_wait(&start_sem_); @@ -420,7 +421,7 @@ bool AgentImpl::Start(v8::Platform* platform, const char* path, return false; } state_ = State::kAccepting; - if (wait) { + if (options_.wait_for_connect()) { DispatchMessages(); } return true; @@ -548,7 +549,7 @@ void AgentImpl::WorkerRunIO() { } InspectorAgentDelegate delegate(this, script_path, script_name_, wait_); delegate_ = &delegate; - InspectorSocketServer server(&delegate, port_); + InspectorSocketServer server(&delegate, options_.port()); if (!server.Start(&child_loop_)) { fprintf(stderr, "Unable to open devtools socket: %s\n", uv_strerror(err)); state_ = State::kError; // Safe, main thread is waiting on semaphore @@ -666,8 +667,8 @@ Agent::~Agent() { } bool Agent::Start(v8::Platform* platform, const char* path, - int port, bool wait) { - return impl->Start(platform, path, port, wait); + const DebugOptions& options) { + return impl->Start(platform, path, options); } void Agent::Stop() { diff --git a/src/inspector_agent.h b/src/inspector_agent.h index b31c77496b3d70..9cc2fa676d4d13 100644 --- a/src/inspector_agent.h +++ b/src/inspector_agent.h @@ -7,6 +7,8 @@ #error("This header can only be used when inspector is enabled") #endif +#include "node_debug_options.h" + // Forward declaration to break recursive dependency chain with src/env.h. namespace node { class Environment; @@ -31,7 +33,8 @@ class Agent { ~Agent(); // Start the inspector agent thread - bool Start(v8::Platform* platform, const char* path, int port, bool wait); + bool Start(v8::Platform* platform, const char* path, + const DebugOptions& options); // Stop the inspector agent void Stop(); diff --git a/src/node.cc b/src/node.cc index 75f3078db5b4f9..0f1d19283762f8 100644 --- a/src/node.cc +++ b/src/node.cc @@ -7,6 +7,7 @@ #include "node_version.h" #include "node_internals.h" #include "node_revert.h" +#include "node_debug_options.h" #if defined HAVE_PERFCTR #include "node_counters.h" @@ -141,17 +142,6 @@ static bool track_heap_objects = false; static const char* eval_string = nullptr; static unsigned int preload_module_count = 0; static const char** preload_modules = nullptr; -#if HAVE_INSPECTOR -static bool use_inspector = false; -#else -static const bool use_inspector = false; -#endif -static bool use_debug_agent = false; -static bool debug_wait_connect = false; -static std::string* debug_host; // coverity[leaked_storage] -static const int default_debugger_port = 5858; -static const int default_inspector_port = 9229; -static int debug_port = -1; static const int v8_default_thread_pool_size = 4; static int v8_thread_pool_size = v8_default_thread_pool_size; static bool prof_process = false; @@ -198,6 +188,8 @@ static uv_async_t dispatch_debug_messages_async; static Mutex node_isolate_mutex; static v8::Isolate* node_isolate; +static node::DebugOptions debug_options; + static struct { #if NODE_USE_V8_PLATFORM void Initialize(int thread_pool_size) { @@ -214,14 +206,12 @@ static struct { platform_ = nullptr; } - bool StartInspector(Environment *env, const char* script_path, - int port, bool wait) { #if HAVE_INSPECTOR - return env->inspector_agent()->Start(platform_, script_path, port, wait); -#else - return true; -#endif // HAVE_INSPECTOR + bool StartInspector(Environment *env, const char* script_path, + const node::DebugOptions& options) { + return env->inspector_agent()->Start(platform_, script_path, options); } +#endif // HAVE_INSPECTOR v8::Platform* platform_; #else // !NODE_USE_V8_PLATFORM @@ -2522,7 +2512,7 @@ void FatalException(Isolate* isolate, if (exit_code) { #if HAVE_INSPECTOR - if (use_inspector) { + if (debug_options.inspector_enabled()) { env->inspector_agent()->FatalException(error, message); } #endif @@ -2923,17 +2913,14 @@ static Local GetFeatures(Environment* env) { static void DebugPortGetter(Local property, const PropertyCallbackInfo& info) { - int port = debug_port; - if (port < 0) - port = use_inspector ? default_inspector_port : default_debugger_port; - info.GetReturnValue().Set(port); + info.GetReturnValue().Set(debug_options.port()); } static void DebugPortSetter(Local property, Local value, const PropertyCallbackInfo& info) { - debug_port = value->Int32Value(); + debug_options.set_port(value->Int32Value()); } @@ -3277,7 +3264,7 @@ void SetupProcessObject(Environment* env, } // --debug-brk - if (debug_wait_connect) { + if (debug_options.wait_for_connect()) { READONLY_PROPERTY(process, "_debugWaitConnect", True(env->isolate())); } @@ -3469,90 +3456,6 @@ void LoadEnvironment(Environment* env) { f->Call(Null(env->isolate()), 1, &arg); } - -static void PrintHelp(); - -static bool ParseDebugOpt(const char* arg) { - const char* port = nullptr; - - if (!strcmp(arg, "--debug")) { - use_debug_agent = true; - } else if (!strncmp(arg, "--debug=", sizeof("--debug=") - 1)) { - use_debug_agent = true; - port = arg + sizeof("--debug=") - 1; - } else if (!strcmp(arg, "--debug-brk")) { - use_debug_agent = true; - debug_wait_connect = true; - } else if (!strncmp(arg, "--debug-brk=", sizeof("--debug-brk=") - 1)) { - use_debug_agent = true; - debug_wait_connect = true; - port = arg + sizeof("--debug-brk=") - 1; - } else if (!strncmp(arg, "--debug-port=", sizeof("--debug-port=") - 1)) { - // XXX(bnoordhuis) Misnomer, configures port and listen address. - port = arg + sizeof("--debug-port=") - 1; -#if HAVE_INSPECTOR - // Specifying both --inspect and --debug means debugging is on, using Chromium - // inspector. - } else if (!strcmp(arg, "--inspect")) { - use_debug_agent = true; - use_inspector = true; - } else if (!strncmp(arg, "--inspect=", sizeof("--inspect=") - 1)) { - use_debug_agent = true; - use_inspector = true; - port = arg + sizeof("--inspect=") - 1; -#else - } else if (!strncmp(arg, "--inspect", sizeof("--inspect") - 1)) { - fprintf(stderr, - "Inspector support is not available with this Node.js build\n"); - return false; -#endif - } else { - return false; - } - - if (port == nullptr) { - return true; - } - - // FIXME(bnoordhuis) Move IPv6 address parsing logic to lib/net.js. - // It seems reasonable to support [address]:port notation - // in net.Server#listen() and net.Socket#connect(). - const size_t port_len = strlen(port); - if (port[0] == '[' && port[port_len - 1] == ']') { - debug_host = new std::string(port + 1, port_len - 2); - return true; - } - - const char* const colon = strrchr(port, ':'); - if (colon == nullptr) { - // Either a port number or a host name. Assume that - // if it's not all decimal digits, it's a host name. - for (size_t n = 0; port[n] != '\0'; n += 1) { - if (port[n] < '0' || port[n] > '9') { - debug_host = new std::string(port); - return true; - } - } - } else { - const bool skip = (colon > port && port[0] == '[' && colon[-1] == ']'); - debug_host = new std::string(port + skip, colon - skip); - } - - char* endptr; - errno = 0; - const char* const digits = colon != nullptr ? colon + 1 : port; - const long result = strtol(digits, &endptr, 10); // NOLINT(runtime/int) - if (errno != 0 || *endptr != '\0' || result < 1024 || result > 65535) { - fprintf(stderr, "Debug port must be in range 1024 to 65535.\n"); - PrintHelp(); - exit(12); - } - - debug_port = static_cast(result); - - return true; -} - static void PrintHelp() { // XXX: If you add an option here, please also add it to doc/node.1 and // doc/api/cli.md @@ -3667,8 +3570,8 @@ static void ParseArgs(int* argc, const char* const arg = argv[index]; unsigned int args_consumed = 1; - if (ParseDebugOpt(arg)) { - // Done, consumed by ParseDebugOpt(). + if (debug_options.ParseOption(arg)) { + // Done, consumed by DebugOptions::ParseOption(). } else if (strcmp(arg, "--version") == 0 || strcmp(arg, "-v") == 0) { printf("%s\n", NODE_VERSION); exit(0); @@ -3810,22 +3713,21 @@ static void DispatchMessagesDebugAgentCallback(Environment* env) { } -static void StartDebug(Environment* env, const char* path, bool wait) { +static void StartDebug(Environment* env, const char* path, + DebugOptions debug_options) { CHECK(!debugger_running); - if (use_inspector) { - debugger_running = v8_platform.StartInspector(env, path, - debug_port >= 0 ? debug_port : default_inspector_port, wait); - } else { +#if HAVE_INSPECTOR + if (debug_options.inspector_enabled()) + debugger_running = v8_platform.StartInspector(env, path, debug_options); +#endif // HAVE_INSPECTOR + if (debug_options.debugger_enabled()) { env->debugger_agent()->set_dispatch_handler( DispatchMessagesDebugAgentCallback); - const char* host = debug_host ? debug_host->c_str() : "127.0.0.1"; - int port = debug_port >= 0 ? debug_port : default_debugger_port; - debugger_running = - env->debugger_agent()->Start(host, port, wait); + debugger_running = env->debugger_agent()->Start(debug_options); if (debugger_running == false) { - fprintf(stderr, "Starting debugger on %s:%d failed\n", host, port); + fprintf(stderr, "Starting debugger on %s:%d failed\n", + debug_options.host_name().c_str(), debug_options.port()); fflush(stderr); - return; } } } @@ -3835,7 +3737,7 @@ static void StartDebug(Environment* env, const char* path, bool wait) { static void EnableDebug(Environment* env) { CHECK(debugger_running); - if (use_inspector) { + if (!debug_options.debugger_enabled()) { return; } @@ -3876,8 +3778,8 @@ static void DispatchDebugMessagesAsyncCallback(uv_async_t* handle) { HandleScope scope(isolate); Environment* env = Environment::GetCurrent(isolate); Context::Scope context_scope(env->context()); - - StartDebug(env, nullptr, false); + debug_options.EnableDebugAgent(DebugAgentType::kDebugger); + StartDebug(env, nullptr, debug_options); EnableDebug(env); } @@ -4131,7 +4033,7 @@ static void DebugEnd(const FunctionCallbackInfo& args) { if (debugger_running) { Environment* env = Environment::GetCurrent(args); #if HAVE_INSPECTOR - if (use_inspector) { + if (debug_options.inspector_enabled()) { env->inspector_agent()->Stop(); } else { #endif @@ -4305,7 +4207,7 @@ void Init(int* argc, const char no_typed_array_heap[] = "--typed_array_max_size_in_heap=0"; V8::SetFlagsFromString(no_typed_array_heap, sizeof(no_typed_array_heap) - 1); - if (!use_debug_agent) { + if (!debug_options.debugger_enabled() && !debug_options.inspector_enabled()) { RegisterDebugSignalHandler(); } @@ -4422,11 +4324,14 @@ inline int Start(Isolate* isolate, IsolateData* isolate_data, Environment env(isolate_data, context); env.Start(argc, argv, exec_argc, exec_argv, v8_is_profiling); + bool debug_enabled = + debug_options.debugger_enabled() || debug_options.inspector_enabled(); + // Start debug agent when argv has --debug - if (use_debug_agent) { + if (debug_enabled) { const char* path = argc > 1 ? argv[1] : nullptr; - StartDebug(&env, path, debug_wait_connect); - if (use_inspector && !debugger_running) + StartDebug(&env, path, debug_options); + if (debug_options.debugger_enabled() && !debugger_running) return 12; // Signal internal error. } @@ -4438,7 +4343,7 @@ inline int Start(Isolate* isolate, IsolateData* isolate_data, env.set_trace_sync_io(trace_sync_io); // Enable debugger - if (use_debug_agent) + if (debug_enabled) EnableDebug(&env); { diff --git a/src/node_debug_options.cc b/src/node_debug_options.cc new file mode 100644 index 00000000000000..5681e3d46edaca --- /dev/null +++ b/src/node_debug_options.cc @@ -0,0 +1,144 @@ +#include "node_debug_options.h" + +#include +#include +#include +#include "util.h" + +namespace node { + +namespace { +const int default_debugger_port = 5858; +const int default_inspector_port = 9229; + +inline std::string remove_brackets(const std::string& host) { + if (!host.empty() && host.front() == '[' && host.back() == ']') + return host.substr(1, host.size() - 2); + else + return host; +} + +int parse_and_validate_port(const std::string& port) { + char* endptr; + errno = 0; + const long result = strtol(port.c_str(), &endptr, 10); // NOLINT(runtime/int) + if (errno != 0 || *endptr != '\0'|| result < 1024 || result > 65535) { + fprintf(stderr, "Debug port must be in range 1024 to 65535.\n"); + exit(12); + } + return static_cast(result); +} + +std::pair split_host_port(const std::string& arg) { + // IPv6, no port + std::string host = remove_brackets(arg); + if (host.length() < arg.length()) + return {host, -1}; + + size_t colon = arg.rfind(':'); + if (colon == std::string::npos) { + // Either a port number or a host name. Assume that + // if it's not all decimal digits, it's a host name. + for (char c : arg) { + if (c < '0' || c > '9') { + return {arg, -1}; + } + } + return {"", parse_and_validate_port(arg)}; + } + return std::make_pair(remove_brackets(arg.substr(0, colon)), + parse_and_validate_port(arg.substr(colon + 1))); +} + +} // namespace + +DebugOptions::DebugOptions() : debugger_enabled_(false), +#if HAVE_INSPECTOR + inspector_enabled_(false), +#endif // HAVE_INSPECTOR + wait_connect_(false), http_enabled_(false), + host_name_("127.0.0.1"), port_(-1) { } + +void DebugOptions::EnableDebugAgent(DebugAgentType tool) { + switch (tool) { +#if HAVE_INSPECTOR + case DebugAgentType::kInspector: + inspector_enabled_ = true; + debugger_enabled_ = true; + break; +#endif // HAVE_INSPECTOR + case DebugAgentType::kDebugger: + debugger_enabled_ = true; + break; + case DebugAgentType::kNone: + break; + } +} + +bool DebugOptions::ParseOption(const std::string& option) { + bool enable_inspector = false; + bool has_argument = false; + std::string option_name; + std::string argument; + + auto pos = option.find("="); + if (pos == std::string::npos) { + option_name = option; + } else { + has_argument = true; + option_name = option.substr(0, pos); + argument = option.substr(pos + 1); + } + + if (option_name == "--debug") { + debugger_enabled_ = true; + } else if (option_name == "--debug-brk") { + debugger_enabled_ = true; + wait_connect_ = true; + } else if (option_name == "--inspect") { + debugger_enabled_ = true; + enable_inspector = true; + } else if (option_name != "--debug-port" || !has_argument) { + return false; + } + + if (enable_inspector) { +#if HAVE_INSPECTOR + inspector_enabled_ = true; +#else + fprintf(stderr, + "Inspector support is not available with this Node.js build\n"); + return false; +#endif + } + + if (!has_argument) { + return true; + } + + // FIXME(bnoordhuis) Move IPv6 address parsing logic to lib/net.js. + // It seems reasonable to support [address]:port notation + // in net.Server#listen() and net.Socket#connect(). + std::pair host_port = split_host_port(argument); + if (!host_port.first.empty()) { + host_name_ = host_port.first; + } + if (host_port.second >= 0) { + port_ = host_port.second; + } + return true; +} + +int DebugOptions::port() const { + int port = port_; + if (port < 0) { +#if HAVE_INSPECTOR + port = inspector_enabled_ ? default_inspector_port : default_debugger_port; +#else + port = default_debugger_port; +#endif // HAVE_INSPECTOR + } + return port; +} + +} // namespace node diff --git a/src/node_debug_options.h b/src/node_debug_options.h new file mode 100644 index 00000000000000..d03bdb15497bbf --- /dev/null +++ b/src/node_debug_options.h @@ -0,0 +1,51 @@ +#ifndef SRC_NODE_DEBUG_OPTIONS_H_ +#define SRC_NODE_DEBUG_OPTIONS_H_ + +#include + +// Forward declaration to break recursive dependency chain with src/env.h. +namespace node { + +enum class DebugAgentType { + kNone, + kDebugger, +#if HAVE_INSPECTOR + kInspector +#endif // HAVE_INSPECTOR +}; + +class DebugOptions { + public: + DebugOptions(); + bool ParseOption(const std::string& option); + bool debugger_enabled() const { + return debugger_enabled_ && !inspector_enabled(); + } + bool inspector_enabled() const { +#if HAVE_INSPECTOR + return inspector_enabled_; +#else + return false; +#endif // HAVE_INSPECTOR + } + void EnableDebugAgent(DebugAgentType type); + bool ToolsServerEnabled(); + bool wait_for_connect() const { return wait_connect_; } + std::string host_name() const { return host_name_; } + int port() const; + void set_port(int port) { port_ = port; } + + private: + bool debugger_enabled_; +#if HAVE_INSPECTOR + bool inspector_enabled_; +#endif // HAVE_INSPECTOR + bool wait_connect_; + bool http_enabled_; + std::string host_name_; + int port_; +}; + +} // namespace node + +#endif // SRC_NODE_DEBUG_OPTIONS_H_ From 2d08bbadd6eb5aab9b66d05b68f9f8ce57680e76 Mon Sep 17 00:00:00 2001 From: Eugene Ostroukhov Date: Mon, 21 Nov 2016 09:38:19 -0800 Subject: [PATCH 205/291] inspector: stop relying on magic strings Inspector uses magical strings to communicate some events between main thread and transport thread. This change replaces those strings with enums that are more mainatainable (and remove unnecessary encodings/decodings) PR-URL: https://github.com/nodejs/node/pull/10159 Reviewed-By: Ben Noordhuis --- src/inspector_agent.cc | 106 ++++++++++++++++++++++++----------------- 1 file changed, 61 insertions(+), 45 deletions(-) diff --git a/src/inspector_agent.cc b/src/inspector_agent.cc index dba4e0f9826004..2173af146855fd 100644 --- a/src/inspector_agent.cc +++ b/src/inspector_agent.cc @@ -16,6 +16,7 @@ #include #include +#include #include #include @@ -30,9 +31,6 @@ namespace { using v8_inspector::StringBuffer; using v8_inspector::StringView; -const char TAG_CONNECT[] = "#connect"; -const char TAG_DISCONNECT[] = "#disconnect"; - static const uint8_t PROTOCOL_JSON[] = { #include "v8_inspector_protocol_json.h" // NOLINT(build/include_order) }; @@ -105,6 +103,14 @@ std::unique_ptr Utf8ToStringView(const std::string& message) { class V8NodeInspector; +enum class InspectorAction { + kStartSession, kEndSession, kSendMessage +}; + +enum class TransportAction { + kSendMessage, kStop +}; + class InspectorAgentDelegate: public node::inspector::SocketServerDelegate { public: InspectorAgentDelegate(AgentImpl* agent, const std::string& script_path, @@ -143,14 +149,16 @@ class AgentImpl { void FatalException(v8::Local error, v8::Local message); - void PostIncomingMessage(int session_id, const std::string& message); + void PostIncomingMessage(InspectorAction action, int session_id, + const std::string& message); void ResumeStartup() { uv_sem_post(&start_sem_); } private: + template using MessageQueue = - std::vector>>; + std::vector>>; enum class State { kNew, kAccepting, kConnected, kDone, kError }; static void ThreadCbIO(void* agent); @@ -161,10 +169,13 @@ class AgentImpl { void WorkerRunIO(); void SetConnected(bool connected); void DispatchMessages(); - void Write(int session_id, const StringView& message); - bool AppendMessage(MessageQueue* vector, int session_id, - std::unique_ptr buffer); - void SwapBehindLock(MessageQueue* vector1, MessageQueue* vector2); + void Write(TransportAction action, int session_id, const StringView& message); + template + bool AppendMessage(MessageQueue* vector, ActionType action, + int session_id, std::unique_ptr buffer); + template + void SwapBehindLock(MessageQueue* vector1, + MessageQueue* vector2); void WaitForFrontendMessage(); void NotifyMessageReceived(); State ToState(State state); @@ -185,8 +196,8 @@ class AgentImpl { uv_async_t io_thread_req_; V8NodeInspector* inspector_; v8::Platform* platform_; - MessageQueue incoming_message_queue_; - MessageQueue outgoing_message_queue_; + MessageQueue incoming_message_queue_; + MessageQueue outgoing_message_queue_; bool dispatching_messages_; int session_id_; InspectorSocketServer* server_; @@ -236,7 +247,7 @@ class ChannelImpl final : public v8_inspector::V8Inspector::Channel { void flushProtocolNotifications() override { } void sendMessageToFrontend(const StringView& message) { - agent_->Write(agent_->session_id_, message); + agent_->Write(TransportAction::kSendMessage, agent_->session_id_, message); } AgentImpl* const agent_; @@ -444,9 +455,7 @@ bool AgentImpl::IsStarted() { void AgentImpl::WaitForDisconnect() { if (state_ == State::kConnected) { shutting_down_ = true; - // Gives a signal to stop accepting new connections - // TODO(eugeneo): Introduce an API with explicit request names. - Write(0, StringView()); + Write(TransportAction::kStop, 0, StringView()); fprintf(stderr, "Waiting for the debugger to disconnect...\n"); fflush(stderr); inspector_->runMessageLoopOnPause(0); @@ -521,15 +530,17 @@ void AgentImpl::ThreadCbIO(void* agent) { // static void AgentImpl::WriteCbIO(uv_async_t* async) { AgentImpl* agent = static_cast(async->data); - MessageQueue outgoing_messages; + MessageQueue outgoing_messages; agent->SwapBehindLock(&agent->outgoing_message_queue_, &outgoing_messages); - for (const MessageQueue::value_type& outgoing : outgoing_messages) { - StringView view = outgoing.second->string(); - if (view.length() == 0) { + for (const auto& outgoing : outgoing_messages) { + switch (std::get<0>(outgoing)) { + case TransportAction::kStop: agent->server_->Stop(nullptr); - } else { - agent->server_->Send(outgoing.first, - StringViewToUtf8(outgoing.second->string())); + break; + case TransportAction::kSendMessage: + std::string message = StringViewToUtf8(std::get<2>(outgoing)->string()); + agent->server_->Send(std::get<1>(outgoing), message); + break; } } } @@ -573,22 +584,26 @@ void AgentImpl::WorkerRunIO() { server_ = nullptr; } -bool AgentImpl::AppendMessage(MessageQueue* queue, int session_id, +template +bool AgentImpl::AppendMessage(MessageQueue* queue, + ActionType action, int session_id, std::unique_ptr buffer) { Mutex::ScopedLock scoped_lock(state_lock_); bool trigger_pumping = queue->empty(); - queue->push_back(std::make_pair(session_id, std::move(buffer))); + queue->push_back(std::make_tuple(action, session_id, std::move(buffer))); return trigger_pumping; } -void AgentImpl::SwapBehindLock(MessageQueue* vector1, MessageQueue* vector2) { +template +void AgentImpl::SwapBehindLock(MessageQueue* vector1, + MessageQueue* vector2) { Mutex::ScopedLock scoped_lock(state_lock_); vector1->swap(*vector2); } -void AgentImpl::PostIncomingMessage(int session_id, +void AgentImpl::PostIncomingMessage(InspectorAction action, int session_id, const std::string& message) { - if (AppendMessage(&incoming_message_queue_, session_id, + if (AppendMessage(&incoming_message_queue_, action, session_id, Utf8ToStringView(message))) { v8::Isolate* isolate = parent_env_->isolate(); platform_->CallOnForegroundThread(isolate, @@ -617,25 +632,21 @@ void AgentImpl::DispatchMessages() { if (dispatching_messages_) return; dispatching_messages_ = true; - MessageQueue tasks; + MessageQueue tasks; do { tasks.clear(); SwapBehindLock(&incoming_message_queue_, &tasks); - for (const MessageQueue::value_type& pair : tasks) { - StringView message = pair.second->string(); - std::string tag; - if (message.length() == sizeof(TAG_CONNECT) - 1 || - message.length() == sizeof(TAG_DISCONNECT) - 1) { - tag = StringViewToUtf8(message); - } - - if (tag == TAG_CONNECT) { + for (const auto& task : tasks) { + StringView message = std::get<2>(task)->string(); + switch (std::get<0>(task)) { + case InspectorAction::kStartSession: CHECK_EQ(State::kAccepting, state_); - session_id_ = pair.first; + session_id_ = std::get<1>(task); state_ = State::kConnected; fprintf(stderr, "Debugger attached.\n"); inspector_->connectFrontend(); - } else if (tag == TAG_DISCONNECT) { + break; + case InspectorAction::kEndSession: CHECK_EQ(State::kConnected, state_); if (shutting_down_) { state_ = State::kDone; @@ -644,16 +655,19 @@ void AgentImpl::DispatchMessages() { } inspector_->quitMessageLoopOnPause(); inspector_->disconnectFrontend(); - } else { + break; + case InspectorAction::kSendMessage: inspector_->dispatchMessageFromFrontend(message); + break; } } } while (!tasks.empty()); dispatching_messages_ = false; } -void AgentImpl::Write(int session_id, const StringView& inspector_message) { - AppendMessage(&outgoing_message_queue_, session_id, +void AgentImpl::Write(TransportAction action, int session_id, + const StringView& inspector_message) { + AppendMessage(&outgoing_message_queue_, action, session_id, StringBuffer::create(inspector_message)); int err = uv_async_send(&io_thread_req_); CHECK_EQ(0, err); @@ -710,7 +724,8 @@ bool InspectorAgentDelegate::StartSession(int session_id, if (connected_) return false; connected_ = true; - agent_->PostIncomingMessage(session_id, TAG_CONNECT); + session_id_++; + agent_->PostIncomingMessage(InspectorAction::kStartSession, session_id, ""); return true; } @@ -727,12 +742,13 @@ void InspectorAgentDelegate::MessageReceived(int session_id, agent_->ResumeStartup(); } } - agent_->PostIncomingMessage(session_id, message); + agent_->PostIncomingMessage(InspectorAction::kSendMessage, session_id, + message); } void InspectorAgentDelegate::EndSession(int session_id) { connected_ = false; - agent_->PostIncomingMessage(session_id, TAG_DISCONNECT); + agent_->PostIncomingMessage(InspectorAction::kEndSession, session_id, ""); } std::vector InspectorAgentDelegate::GetTargetIds() { From 63f43021b07039852910e6d48b7e330858aed735 Mon Sep 17 00:00:00 2001 From: Ben Noordhuis Date: Thu, 22 Dec 2016 10:12:08 +0100 Subject: [PATCH 206/291] src: remove unused PROTOCOL_JSON array Overlooked when moving code around in commit 42da740 ("inspector: split HTTP/WS server from the inspector".) PR-URL: https://github.com/nodejs/node/pull/10407 Reviewed-By: Colin Ihrig Reviewed-By: James M Snell Reviewed-By: Santiago Gimeno --- src/inspector_agent.cc | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/inspector_agent.cc b/src/inspector_agent.cc index 2173af146855fd..403afe0e120b97 100644 --- a/src/inspector_agent.cc +++ b/src/inspector_agent.cc @@ -31,10 +31,6 @@ namespace { using v8_inspector::StringBuffer; using v8_inspector::StringView; -static const uint8_t PROTOCOL_JSON[] = { -#include "v8_inspector_protocol_json.h" // NOLINT(build/include_order) -}; - std::string GetProcessTitle() { // uv_get_process_title will trim the title if it is too long. char title[2048]; From 9a111e701ef6eca3bbe18b20f333872456d31151 Mon Sep 17 00:00:00 2001 From: Eugene Ostroukhov Date: Wed, 18 Jan 2017 10:18:32 -0800 Subject: [PATCH 207/291] inspector: no crash when WS server can't start This change also changes error message to make it consistent with the one printed by the debugger. Fixes: https://github.com/nodejs/node/issues/10858 PR-URL: https://github.com/nodejs/node/pull/10878 Reviewed-By: Ben Noordhuis Reviewed-By: James M Snell Reviewed-By: Colin Ihrig --- src/inspector_agent.cc | 5 +++-- src/inspector_socket_server.cc | 24 +++++++++++++-------- src/inspector_socket_server.h | 2 ++ src/node.cc | 2 +- test/cctest/test_inspector_socket_server.cc | 22 ++++++++++--------- 5 files changed, 33 insertions(+), 22 deletions(-) diff --git a/src/inspector_agent.cc b/src/inspector_agent.cc index 403afe0e120b97..ae2e666384b5af 100644 --- a/src/inspector_agent.cc +++ b/src/inspector_agent.cc @@ -556,9 +556,10 @@ void AgentImpl::WorkerRunIO() { } InspectorAgentDelegate delegate(this, script_path, script_name_, wait_); delegate_ = &delegate; - InspectorSocketServer server(&delegate, options_.port()); + InspectorSocketServer server(&delegate, + options_.host_name(), + options_.port()); if (!server.Start(&child_loop_)) { - fprintf(stderr, "Unable to open devtools socket: %s\n", uv_strerror(err)); state_ = State::kError; // Safe, main thread is waiting on semaphore uv_close(reinterpret_cast(&io_thread_req_), nullptr); uv_loop_close(&child_loop_); diff --git a/src/inspector_socket_server.cc b/src/inspector_socket_server.cc index 5308e9bcf0b924..ee44a69a683690 100644 --- a/src/inspector_socket_server.cc +++ b/src/inspector_socket_server.cc @@ -24,9 +24,9 @@ void Escape(std::string* string) { } } -std::string GetWsUrl(int port, const std::string& id) { +std::string GetWsUrl(const std::string& host, int port, const std::string& id) { char buf[1024]; - snprintf(buf, sizeof(buf), "127.0.0.1:%d/%s", port, id.c_str()); + snprintf(buf, sizeof(buf), "%s:%d/%s", host.c_str(), port, id.c_str()); return buf; } @@ -74,7 +74,8 @@ void OnBufferAlloc(uv_handle_t* handle, size_t len, uv_buf_t* buf) { buf->len = len; } -void PrintDebuggerReadyMessage(int port, +void PrintDebuggerReadyMessage(const std::string& host, + int port, const std::vector& ids, FILE* out) { if (out == NULL) { @@ -92,7 +93,8 @@ void PrintDebuggerReadyMessage(int port, for (const std::string& id : ids) { fprintf(out, " chrome-devtools://devtools/bundled/inspector.html?" - "experiments=true&v8only=true&ws=%s\n", GetWsUrl(port, id).c_str()); + "experiments=true&v8only=true&ws=%s\n", + GetWsUrl(host, port, id).c_str()); } fflush(out); } @@ -229,9 +231,11 @@ class SocketSession { }; InspectorSocketServer::InspectorSocketServer(SocketServerDelegate* delegate, + const std::string& host, int port, FILE* out) : loop_(nullptr), delegate_(delegate), + host_(host), port_(port), server_(uv_tcp_t()), closer_(nullptr), @@ -284,7 +288,7 @@ void InspectorSocketServer::SessionTerminated(int session_id) { delegate_->EndSession(session_id); if (connected_sessions_.empty() && uv_is_active(reinterpret_cast(&server_))) { - PrintDebuggerReadyMessage(port_, delegate_->GetTargetIds(), out_); + PrintDebuggerReadyMessage(host_, port_, delegate_->GetTargetIds(), out_); } } @@ -337,7 +341,7 @@ void InspectorSocketServer::SendListResponse(InspectorSocket* socket) { } } if (!connected) { - std::string address = GetWsUrl(port_, id); + std::string address = GetWsUrl(host_, port_, id); std::ostringstream frontend_url; frontend_url << "chrome-devtools://devtools/bundled"; frontend_url << "/inspector.html?experiments=true&v8only=true&ws="; @@ -353,7 +357,7 @@ bool InspectorSocketServer::Start(uv_loop_t* loop) { loop_ = loop; sockaddr_in addr; uv_tcp_init(loop_, &server_); - uv_ip4_addr("0.0.0.0", port_, &addr); + uv_ip4_addr(host_.c_str(), port_, &addr); int err = uv_tcp_bind(&server_, reinterpret_cast(&addr), 0); if (err == 0) @@ -363,11 +367,13 @@ bool InspectorSocketServer::Start(uv_loop_t* loop) { SocketConnectedCallback); } if (err == 0 && connected_sessions_.empty()) { - PrintDebuggerReadyMessage(port_, delegate_->GetTargetIds(), out_); + PrintDebuggerReadyMessage(host_, port_, delegate_->GetTargetIds(), out_); } if (err != 0 && connected_sessions_.empty()) { if (out_ != NULL) { - fprintf(out_, "Unable to open devtools socket: %s\n", uv_strerror(err)); + fprintf(out_, "Starting inspector on %s:%d failed: %s\n", + host_.c_str(), port_, uv_strerror(err)); + fflush(out_); } uv_close(reinterpret_cast(&server_), nullptr); return false; diff --git a/src/inspector_socket_server.h b/src/inspector_socket_server.h index 48ebc5353f123d..b82d9ee6013a40 100644 --- a/src/inspector_socket_server.h +++ b/src/inspector_socket_server.h @@ -33,6 +33,7 @@ class InspectorSocketServer { public: using ServerCallback = void (*)(InspectorSocketServer*); InspectorSocketServer(SocketServerDelegate* delegate, + const std::string& host, int port, FILE* out = stderr); bool Start(uv_loop_t* loop); @@ -65,6 +66,7 @@ class InspectorSocketServer { uv_loop_t* loop_; SocketServerDelegate* const delegate_; + const std::string host_; int port_; std::string path_; uv_tcp_t server_; diff --git a/src/node.cc b/src/node.cc index 0f1d19283762f8..406977cf09c0f1 100644 --- a/src/node.cc +++ b/src/node.cc @@ -4331,7 +4331,7 @@ inline int Start(Isolate* isolate, IsolateData* isolate_data, if (debug_enabled) { const char* path = argc > 1 ? argv[1] : nullptr; StartDebug(&env, path, debug_options); - if (debug_options.debugger_enabled() && !debugger_running) + if (!debugger_running) return 12; // Signal internal error. } diff --git a/test/cctest/test_inspector_socket_server.cc b/test/cctest/test_inspector_socket_server.cc index e1e9f6f66865d3..6fe8a7548fd4a5 100644 --- a/test/cctest/test_inspector_socket_server.cc +++ b/test/cctest/test_inspector_socket_server.cc @@ -8,6 +8,8 @@ static uv_loop_t loop; +static const char HOST[] = "127.0.0.1"; + static const char CLIENT_CLOSE_FRAME[] = "\x88\x80\x2D\x0E\x1E\xFA"; static const char SERVER_CLOSE_FRAME[] = "\x88\x00"; @@ -249,7 +251,7 @@ class SocketWrapper { } static void Connected_(uv_connect_t* connect, int status) { - EXPECT_EQ(0, status); + EXPECT_EQ(0, status) << "Unable to connect: " << uv_strerror(status); SocketWrapper* wrapper = node::ContainerOf(&SocketWrapper::connect_, connect); wrapper->connected_ = true; @@ -301,7 +303,7 @@ class ServerHolder { template ServerHolder(Delegate* delegate, int port, FILE* out = NULL) : closed(false), paused(false), sessions_terminated(false), - server_(delegate, port, out) { + server_(delegate, HOST, port, out) { delegate->Connect(&server_); } @@ -362,7 +364,7 @@ class ServerDelegateNoTargets : public SocketServerDelegate { static void TestHttpRequest(int port, const std::string& path, const std::string& expected_body) { SocketWrapper socket(&loop); - socket.Connect("0.0.0.0", port); + socket.Connect(HOST, port); socket.TestHttpRequest(path, expected_body); socket.Close(); } @@ -385,7 +387,7 @@ TEST_F(InspectorSocketServerTest, InspectorSessions) { SocketWrapper well_behaved_socket(&loop); // Regular connection - well_behaved_socket.Connect("0.0.0.0", server.port()); + well_behaved_socket.Connect(HOST, server.port()); well_behaved_socket.Write(WsHandshakeRequest(MAIN_TARGET_ID)); well_behaved_socket.Expect(WS_HANDSHAKE_RESPONSE); @@ -408,7 +410,7 @@ TEST_F(InspectorSocketServerTest, InspectorSessions) { // Declined connection SocketWrapper declined_target_socket(&loop); - declined_target_socket.Connect("127.0.0.1", server.port()); + declined_target_socket.Connect(HOST, server.port()); declined_target_socket.Write(WsHandshakeRequest(UNCONNECTABLE_TARGET_ID)); declined_target_socket.Expect("HTTP/1.0 400 Bad Request"); declined_target_socket.ExpectEOF(); @@ -417,7 +419,7 @@ TEST_F(InspectorSocketServerTest, InspectorSessions) { // Bogus target - start session callback should not even be invoked SocketWrapper bogus_target_socket(&loop); - bogus_target_socket.Connect("127.0.0.1", server.port()); + bogus_target_socket.Connect(HOST, server.port()); bogus_target_socket.Write(WsHandshakeRequest("bogus_target")); bogus_target_socket.Expect("HTTP/1.0 400 Bad Request"); bogus_target_socket.ExpectEOF(); @@ -426,7 +428,7 @@ TEST_F(InspectorSocketServerTest, InspectorSessions) { // Drop connection (no proper close frames) SocketWrapper dropped_connection_socket(&loop); - dropped_connection_socket.Connect("127.0.0.1", server.port()); + dropped_connection_socket.Connect(HOST, server.port()); dropped_connection_socket.Write(WsHandshakeRequest(MAIN_TARGET_ID)); dropped_connection_socket.Expect(WS_HANDSHAKE_RESPONSE); @@ -440,7 +442,7 @@ TEST_F(InspectorSocketServerTest, InspectorSessions) { // Reconnect regular connection SocketWrapper stays_till_termination_socket(&loop); - stays_till_termination_socket.Connect("127.0.0.1", server.port()); + stays_till_termination_socket.Connect(HOST, server.port()); stays_till_termination_socket.Write(WsHandshakeRequest(MAIN_TARGET_ID)); stays_till_termination_socket.Expect(WS_HANDSHAKE_RESPONSE); @@ -484,7 +486,7 @@ TEST_F(InspectorSocketServerTest, ServerWithoutTargets) { // Declined connection SocketWrapper socket(&loop); - socket.Connect("0.0.0.0", server.port()); + socket.Connect(HOST, server.port()); socket.Write(WsHandshakeRequest(UNCONNECTABLE_TARGET_ID)); socket.Expect("HTTP/1.0 400 Bad Request"); socket.ExpectEOF(); @@ -512,7 +514,7 @@ TEST_F(InspectorSocketServerTest, StoppingServerDoesNotKillConnections) { ServerHolder server(&delegate, 0); ASSERT_TRUE(server->Start(&loop)); SocketWrapper socket1(&loop); - socket1.Connect("0.0.0.0", server.port()); + socket1.Connect(HOST, server.port()); socket1.TestHttpRequest("/json/list", "[ ]"); server->Stop(ServerHolder::CloseCallback); SPIN_WHILE(!server.closed); From 66c57a24c2cc7e358d230c4bc97e3eec3216d6a3 Mon Sep 17 00:00:00 2001 From: abouthiroppy Date: Sun, 15 Jan 2017 03:30:14 +0900 Subject: [PATCH 208/291] test: add test case to test-http-response-statuscode.js Change regular expression of error message. Add test case(`res.writeHead()`). PR-URL: https://github.com/nodejs/node/pull/10808 Reviewed-By: Luigi Pinca Reviewed-By: James M Snell Reviewed-By: Colin Ihrig --- .../parallel/test-http-response-statuscode.js | 35 ++++++++++++------- 1 file changed, 22 insertions(+), 13 deletions(-) diff --git a/test/parallel/test-http-response-statuscode.js b/test/parallel/test-http-response-statuscode.js index 4bd75647aebea7..ed3676b03e1f0c 100644 --- a/test/parallel/test-http-response-statuscode.js +++ b/test/parallel/test-http-response-statuscode.js @@ -3,70 +3,79 @@ const common = require('../common'); const assert = require('assert'); const http = require('http'); -const MAX_REQUESTS = 12; +const MAX_REQUESTS = 13; let reqNum = 0; +const createErrorMessage = (code) => { + return new RegExp(`^RangeError: Invalid status code: ${code}$`); +}; + const server = http.Server(common.mustCall(function(req, res) { switch (reqNum) { case 0: assert.throws(common.mustCall(() => { res.writeHead(-1); - }), /invalid status code/i); + }), createErrorMessage(-1)); break; case 1: assert.throws(common.mustCall(() => { res.writeHead(Infinity); - }), /invalid status code/i); + }), createErrorMessage(0)); break; case 2: assert.throws(common.mustCall(() => { res.writeHead(NaN); - }), /invalid status code/i); + }), createErrorMessage(0)); break; case 3: assert.throws(common.mustCall(() => { res.writeHead({}); - }), /invalid status code/i); + }), createErrorMessage(0)); break; case 4: assert.throws(common.mustCall(() => { res.writeHead(99); - }), /invalid status code/i); + }), createErrorMessage(99)); break; case 5: assert.throws(common.mustCall(() => { res.writeHead(1000); - }), /invalid status code/i); + }), createErrorMessage(1000)); break; case 6: assert.throws(common.mustCall(() => { res.writeHead('1000'); - }), /invalid status code/i); + }), createErrorMessage(1000)); break; case 7: assert.throws(common.mustCall(() => { res.writeHead(null); - }), /invalid status code/i); + }), createErrorMessage(0)); break; case 8: assert.throws(common.mustCall(() => { res.writeHead(true); - }), /invalid status code/i); + }), createErrorMessage(1)); break; case 9: assert.throws(common.mustCall(() => { res.writeHead([]); - }), /invalid status code/i); + }), createErrorMessage(0)); break; case 10: assert.throws(common.mustCall(() => { res.writeHead('this is not valid'); - }), /invalid status code/i); + }), createErrorMessage(0)); break; case 11: assert.throws(common.mustCall(() => { res.writeHead('404 this is not valid either'); - }), /invalid status code/i); + }), createErrorMessage(0)); + break; + case 12: + assert.throws(common.mustCall(() => { + res.writeHead(); + }), createErrorMessage(0)); this.close(); break; default: From 7f043779eb94dc4378b62f9f20bed7f38d3ff57e Mon Sep 17 00:00:00 2001 From: Adrian Estrada Date: Sun, 15 Jan 2017 22:23:19 -0500 Subject: [PATCH 209/291] test: improve code in test-http-host-headers * use common.fail to handle errors * remove console.log * use arrow functions PR-URL: https://github.com/nodejs/node/pull/10830 Reviewed-By: Luigi Pinca Reviewed-By: Colin Ihrig Reviewed-By: James M Snell --- test/parallel/test-http-host-headers.js | 37 ++++++++----------------- 1 file changed, 12 insertions(+), 25 deletions(-) diff --git a/test/parallel/test-http-host-headers.js b/test/parallel/test-http-host-headers.js index c127b3375b224c..79a2833f7df148 100644 --- a/test/parallel/test-http-host-headers.js +++ b/test/parallel/test-http-host-headers.js @@ -1,11 +1,10 @@ 'use strict'; -require('../common'); +const common = require('../common'); const http = require('http'); const assert = require('assert'); const httpServer = http.createServer(reqHandler); function reqHandler(req, res) { - console.log('Got request: ' + req.headers.host + ' ' + req.url); if (req.url === '/setHostFalse5') { assert.strictEqual(req.headers.host, undefined); } else { @@ -14,14 +13,9 @@ function reqHandler(req, res) { req.headers.host); } res.writeHead(200, {}); - //process.nextTick(function() { res.end('ok'); }); res.end('ok'); } -function thrower(er) { - throw er; -} - testHttp(); function testHttp() { @@ -30,59 +24,52 @@ function testHttp() { function cb(res) { counter--; - console.log('back from http request. counter = ' + counter); if (counter === 0) { httpServer.close(); } res.resume(); } - httpServer.listen(0, function(er) { - console.error(`test http server listening on ${this.address().port}`); + httpServer.listen(0, (er) => { assert.ifError(er); http.get({ method: 'GET', path: '/' + (counter++), host: 'localhost', - //agent: false, - port: this.address().port, + port: httpServer.address().port, rejectUnauthorized: false - }, cb).on('error', thrower); + }, cb).on('error', common.fail); http.request({ method: 'GET', path: '/' + (counter++), host: 'localhost', - //agent: false, - port: this.address().port, + port: httpServer.address().port, rejectUnauthorized: false - }, cb).on('error', thrower).end(); + }, cb).on('error', common.fail).end(); http.request({ method: 'POST', path: '/' + (counter++), host: 'localhost', - //agent: false, - port: this.address().port, + port: httpServer.address().port, rejectUnauthorized: false - }, cb).on('error', thrower).end(); + }, cb).on('error', common.fail).end(); http.request({ method: 'PUT', path: '/' + (counter++), host: 'localhost', - //agent: false, - port: this.address().port, + port: httpServer.address().port, rejectUnauthorized: false - }, cb).on('error', thrower).end(); + }, cb).on('error', common.fail).end(); http.request({ method: 'DELETE', path: '/' + (counter++), host: 'localhost', - //agent: false, - port: this.address().port, + port: httpServer.address().port, rejectUnauthorized: false - }, cb).on('error', thrower).end(); + }, cb).on('error', common.fail).end(); }); } From 46bbabe6c218d08f771c8b85ae04ca8374349856 Mon Sep 17 00:00:00 2001 From: stefan judis Date: Tue, 10 Jan 2017 17:38:48 +0100 Subject: [PATCH 210/291] test: improve test-stream2-large-read-stall * use const instead of var * use assert.strictEqual instead of assert.equal * use common.mustCall instead of process.on( 'exit', fn ) PR-URL: https://github.com/nodejs/node/pull/10725 Reviewed-By: James M Snell Reviewed-By: Italo A. Casas --- test/parallel/test-stream2-large-read-stall.js | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/test/parallel/test-stream2-large-read-stall.js b/test/parallel/test-stream2-large-read-stall.js index 36d4e0c6c9d7c9..2422747f820bc1 100644 --- a/test/parallel/test-stream2-large-read-stall.js +++ b/test/parallel/test-stream2-large-read-stall.js @@ -33,7 +33,9 @@ r.on('readable', function() { rs.length); }); -r.on('end', common.mustCall(function() {})); +r.on('end', common.mustCall(function() { + assert.strictEqual(pushes, PUSHCOUNT + 1); +})); let pushes = 0; function push() { @@ -49,7 +51,3 @@ function push() { if (r.push(Buffer.allocUnsafe(PUSHSIZE))) setTimeout(push, 1); } - -process.on('exit', function() { - assert.strictEqual(pushes, PUSHCOUNT + 1); -}); From b496374363050aa9fe8ee480e976ca6cff2507df Mon Sep 17 00:00:00 2001 From: Adrian Estrada Date: Sat, 14 Jan 2017 19:05:04 -0500 Subject: [PATCH 211/291] test: improve code in test-domain-multi * use common.mustCall to validate functions executions * use common.fail to control error * remove unnecessary variables * remove unnecessary assertions * remove console.log and console.error * use arrow functions PR-URL: https://github.com/nodejs/node/pull/10798 Reviewed-By: James M Snell Reviewed-By: Luigi Pinca --- test/parallel/test-domain-multi.js | 45 ++++++++---------------------- 1 file changed, 11 insertions(+), 34 deletions(-) diff --git a/test/parallel/test-domain-multi.js b/test/parallel/test-domain-multi.js index b8005726219519..a38b6a2bc42bdf 100644 --- a/test/parallel/test-domain-multi.js +++ b/test/parallel/test-domain-multi.js @@ -1,26 +1,16 @@ 'use strict'; // Tests of multiple domains happening at once. -require('../common'); -const assert = require('assert'); +const common = require('../common'); const domain = require('domain'); - -let caughtA = false; -let caughtB = false; -let caughtC = false; - +const http = require('http'); const a = domain.create(); a.enter(); // this will be our "root" domain -a.on('error', function(er) { - caughtA = true; - console.log('This should not happen'); - throw er; -}); +a.on('error', common.fail); -const http = require('http'); -const server = http.createServer(function(req, res) { +const server = http.createServer((req, res) => { // child domain of a. const b = domain.create(); a.add(b); @@ -31,47 +21,34 @@ const server = http.createServer(function(req, res) { b.add(req); b.add(res); - b.on('error', function(er) { - caughtB = true; - console.error('Error encountered', er); + b.on('error', common.mustCall((er) => { if (res) { res.writeHead(500); res.end('An error occurred'); } // res.writeHead(500), res.destroy, etc. server.close(); - }); + })); // XXX this bind should not be necessary. // the write cb behavior in http/net should use an // event so that it picks up the domain handling. - res.write('HELLO\n', b.bind(function() { + res.write('HELLO\n', b.bind(() => { throw new Error('this kills domain B, not A'); })); -}).listen(0, function() { +}).listen(0, () => { const c = domain.create(); - const req = http.get({ host: 'localhost', port: this.address().port }); + const req = http.get({ host: 'localhost', port: server.address().port }); // add the request to the C domain c.add(req); - req.on('response', function(res) { - console.error('got response'); + req.on('response', (res) => { // add the response object to the C domain c.add(res); res.pipe(process.stdout); }); - c.on('error', function(er) { - caughtC = true; - console.error('Error on c', er.message); - }); -}); - -process.on('exit', function() { - assert.strictEqual(caughtA, false); - assert.strictEqual(caughtB, true); - assert.strictEqual(caughtC, true); - console.log('ok - Errors went where they were supposed to go'); + c.on('error', common.mustCall((er) => { })); }); From 1666600f165e649e0072eed21508c4bf993639f8 Mon Sep 17 00:00:00 2001 From: Adrian Estrada Date: Mon, 16 Jan 2017 21:06:33 -0500 Subject: [PATCH 212/291] test: improve code in test-console-instance * use common.mustCall to validate functions executions * use common.fail to check test fail * improve error validations * remove unnecessary assertions * use arrow functions PR-URL: https://github.com/nodejs/node/pull/10813 Reviewed-By: James M Snell Reviewed-By: Luigi Pinca Reviewed-By: Colin Ihrig --- test/parallel/test-console-instance.js | 48 ++++++++++---------------- 1 file changed, 18 insertions(+), 30 deletions(-) diff --git a/test/parallel/test-console-instance.js b/test/parallel/test-console-instance.js index 4488e893732751..328adfde0ed803 100644 --- a/test/parallel/test-console-instance.js +++ b/test/parallel/test-console-instance.js @@ -1,71 +1,59 @@ 'use strict'; -require('../common'); +const common = require('../common'); const assert = require('assert'); const Stream = require('stream'); const Console = require('console').Console; -let called = false; const out = new Stream(); const err = new Stream(); // ensure the Console instance doesn't write to the // process' "stdout" or "stderr" streams -process.stdout.write = process.stderr.write = function() { - throw new Error('write() should not be called!'); -}; +process.stdout.write = process.stderr.write = common.fail; // make sure that the "Console" function exists assert.strictEqual('function', typeof Console); // make sure that the Console constructor throws // when not given a writable stream instance -assert.throws(function() { +assert.throws(() => { new Console(); -}, /Console expects a writable stream/); +}, /^TypeError: Console expects a writable stream instance$/); // Console constructor should throw if stderr exists but is not writable -assert.throws(function() { - out.write = function() {}; +assert.throws(() => { + out.write = () => {}; err.write = undefined; new Console(out, err); -}, /Console expects writable stream instances/); +}, /^TypeError: Console expects writable stream instances$/); -out.write = err.write = function(d) {}; +out.write = err.write = (d) => {}; const c = new Console(out, err); -out.write = err.write = function(d) { +out.write = err.write = common.mustCall((d) => { assert.strictEqual(d, 'test\n'); - called = true; -}; +}, 2); -assert(!called); c.log('test'); -assert(called); - -called = false; c.error('test'); -assert(called); -out.write = function(d) { +out.write = common.mustCall((d) => { assert.strictEqual('{ foo: 1 }\n', d); - called = true; -}; +}); -called = false; c.dir({ foo: 1 }); -assert(called); // ensure that the console functions are bound to the console instance -called = 0; -out.write = function(d) { +let called = 0; +out.write = common.mustCall((d) => { called++; - assert.strictEqual(d, called + ' ' + (called - 1) + ' [ 1, 2, 3 ]\n'); -}; + assert.strictEqual(d, `${called} ${called - 1} [ 1, 2, 3 ]\n`); +}, 3); + [1, 2, 3].forEach(c.log); -assert.strictEqual(3, called); // Console() detects if it is called without `new` keyword -assert.doesNotThrow(function() { +assert.doesNotThrow(() => { Console(out, err); }); From ffdf605f1441695408b5e46409bd5e24ae97f94b Mon Sep 17 00:00:00 2001 From: abouthiroppy Date: Fri, 13 Jan 2017 11:05:35 +0900 Subject: [PATCH 213/291] test: improving coverage for dgram PR-URL: https://github.com/nodejs/node/pull/10783 Reviewed-By: James M Snell Reviewed-By: Colin Ihrig --- .../parallel/test-dgram-multicast-loopback.js | 12 +++++++++++ test/parallel/test-dgram-multicast-setTTL.js | 20 +++++++++---------- test/parallel/test-dgram-setTTL.js | 15 +++++++++----- 3 files changed, 32 insertions(+), 15 deletions(-) create mode 100644 test/parallel/test-dgram-multicast-loopback.js diff --git a/test/parallel/test-dgram-multicast-loopback.js b/test/parallel/test-dgram-multicast-loopback.js new file mode 100644 index 00000000000000..01def7e28160cd --- /dev/null +++ b/test/parallel/test-dgram-multicast-loopback.js @@ -0,0 +1,12 @@ +'use strict'; +const common = require('../common'); +const assert = require('assert'); +const dgram = require('dgram'); +const socket = dgram.createSocket('udp4'); + +socket.bind(0); +socket.on('listening', common.mustCall(() => { + const result = socket.setMulticastLoopback(16); + assert.strictEqual(result, 16); + socket.close(); +})); diff --git a/test/parallel/test-dgram-multicast-setTTL.js b/test/parallel/test-dgram-multicast-setTTL.js index 83d482f426bcd4..11b5a0a7635857 100644 --- a/test/parallel/test-dgram-multicast-setTTL.js +++ b/test/parallel/test-dgram-multicast-setTTL.js @@ -1,23 +1,23 @@ 'use strict'; -require('../common'); +const common = require('../common'); const assert = require('assert'); const dgram = require('dgram'); const socket = dgram.createSocket('udp4'); -let thrown = false; socket.bind(0); -socket.on('listening', function() { - socket.setMulticastTTL(16); +socket.on('listening', common.mustCall(() => { + const result = socket.setMulticastTTL(16); + assert.strictEqual(result, 16); //Try to set an invalid TTL (valid ttl is > 0 and < 256) - try { + assert.throws(() => { socket.setMulticastTTL(1000); - } catch (e) { - thrown = true; - } + }, /^Error: setMulticastTTL EINVAL$/); - assert(thrown, 'Setting an invalid multicast TTL should throw some error'); + assert.throws(() => { + socket.setMulticastTTL('foo'); + }, /^TypeError: Argument must be a number$/); //close the socket socket.close(); -}); +})); diff --git a/test/parallel/test-dgram-setTTL.js b/test/parallel/test-dgram-setTTL.js index 3985297217d8b7..7da3975ad4c3fd 100644 --- a/test/parallel/test-dgram-setTTL.js +++ b/test/parallel/test-dgram-setTTL.js @@ -1,17 +1,22 @@ 'use strict'; -require('../common'); +const common = require('../common'); const assert = require('assert'); const dgram = require('dgram'); const socket = dgram.createSocket('udp4'); socket.bind(0); -socket.on('listening', function() { +socket.on('listening', common.mustCall(() => { const result = socket.setTTL(16); assert.strictEqual(result, 16); - assert.throws(function() { + assert.throws(() => { socket.setTTL('foo'); - }, /Argument must be a number/); + }, /^TypeError: Argument must be a number$/); + + // TTL must be a number from > 0 to < 256 + assert.throws(() => { + socket.setTTL(1000); + }, /^Error: setTTL EINVAL$/); socket.close(); -}); +})); From 939517abfdd28a5f72a79409cc82974bb729b2aa Mon Sep 17 00:00:00 2001 From: abouthiroppy Date: Wed, 11 Jan 2017 07:54:12 +0900 Subject: [PATCH 214/291] test: refactor test-fs-read-zero-length.js PR-URL: https://github.com/nodejs/node/pull/10729 Reviewed-By: James M Snell Reviewed-By: Colin Ihrig --- test/parallel/test-fs-read-zero-length.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/parallel/test-fs-read-zero-length.js b/test/parallel/test-fs-read-zero-length.js index 42e260360e79e2..a3e98f540a4151 100644 --- a/test/parallel/test-fs-read-zero-length.js +++ b/test/parallel/test-fs-read-zero-length.js @@ -7,7 +7,7 @@ const filepath = path.join(common.fixturesDir, 'x.txt'); const fd = fs.openSync(filepath, 'r'); const expected = ''; -fs.read(fd, 0, 0, 'utf-8', common.mustCall(function(err, str, bytesRead) { +fs.read(fd, 0, 0, 'utf-8', common.mustCall((err, str, bytesRead) => { assert.ok(!err); assert.strictEqual(str, expected); assert.strictEqual(bytesRead, 0); From c8a069e54495cc34ec760bfdc9ae6efe2e791f99 Mon Sep 17 00:00:00 2001 From: abouthiroppy Date: Tue, 17 Jan 2017 10:37:14 +0900 Subject: [PATCH 215/291] test: improving coverage of dns-lookup PR-URL: https://github.com/nodejs/node/pull/10844 Reviewed-By: James M Snell Reviewed-By: Luigi Pinca Reviewed-By: Colin Ihrig Reviewed-By: Italo A. Casas --- test/parallel/test-dns-lookup-cb-error.js | 25 ------- test/parallel/test-dns-lookup.js | 89 +++++++++++++++++++++++ 2 files changed, 89 insertions(+), 25 deletions(-) delete mode 100644 test/parallel/test-dns-lookup-cb-error.js create mode 100644 test/parallel/test-dns-lookup.js diff --git a/test/parallel/test-dns-lookup-cb-error.js b/test/parallel/test-dns-lookup-cb-error.js deleted file mode 100644 index d866a8a13bf622..00000000000000 --- a/test/parallel/test-dns-lookup-cb-error.js +++ /dev/null @@ -1,25 +0,0 @@ -'use strict'; -const common = require('../common'); -const assert = require('assert'); -const cares = process.binding('cares_wrap'); - -const dns = require('dns'); - -// Stub `getaddrinfo` to *always* error. -cares.getaddrinfo = function() { - return process.binding('uv').UV_ENOENT; -}; - -assert.doesNotThrow(() => { - let tickValue = 0; - - dns.lookup('example.com', common.mustCall((error, result, addressType) => { - assert(error); - assert.strictEqual(tickValue, 1); - assert.strictEqual(error.code, 'ENOENT'); - })); - - // Make sure that the error callback is called - // on next tick. - tickValue = 1; -}); diff --git a/test/parallel/test-dns-lookup.js b/test/parallel/test-dns-lookup.js new file mode 100644 index 00000000000000..a720c46e02a630 --- /dev/null +++ b/test/parallel/test-dns-lookup.js @@ -0,0 +1,89 @@ +'use strict'; +const common = require('../common'); +const assert = require('assert'); +const cares = process.binding('cares_wrap'); +const dns = require('dns'); + +// Stub `getaddrinfo` to *always* error. +cares.getaddrinfo = () => process.binding('uv').UV_ENOENT; + +assert.throws(() => { + dns.lookup(1, {}); +}, /^TypeError: Invalid arguments: hostname must be a string or falsey$/); + +assert.throws(() => { + dns.lookup(false, 'cb'); +}, /^TypeError: Invalid arguments: callback must be passed$/); + +assert.throws(() => { + dns.lookup(false, 'options', 'cb'); +}, /^TypeError: Invalid arguments: callback must be passed$/); + +assert.throws(() => { + dns.lookup(false, { + hints: 100, + family: 0, + all: false + }, () => {}); +}, /^TypeError: Invalid argument: hints must use valid flags$/); + +assert.throws(() => { + dns.lookup(false, { + hints: 0, + family: 20, + all: false + }, () => {}); +}, /^TypeError: Invalid argument: family must be 4 or 6$/); + +assert.doesNotThrow(() => { + dns.lookup(false, { + hints: 0, + family: 0, + all: true + }, common.mustCall((error, result, addressType) => { + assert.ifError(error); + assert.deepStrictEqual(result, []); + assert.strictEqual(addressType, undefined); + })); +}); + +assert.doesNotThrow(() => { + dns.lookup('127.0.0.1', { + hints: 0, + family: 4, + all: true + }, common.mustCall((error, result, addressType) => { + assert.ifError(error); + assert.deepStrictEqual(result, [{ + address: '127.0.0.1', + family: 4 + }]); + assert.strictEqual(addressType, undefined); + })); +}); + +assert.doesNotThrow(() => { + dns.lookup('127.0.0.1', { + hints: 0, + family: 4, + all: false + }, common.mustCall((error, result, addressType) => { + assert.ifError(error); + assert.deepStrictEqual(result, '127.0.0.1'); + assert.strictEqual(addressType, 4); + })); +}); + +assert.doesNotThrow(() => { + let tickValue = 0; + + dns.lookup('example.com', common.mustCall((error, result, addressType) => { + assert(error); + assert.strictEqual(tickValue, 1); + assert.strictEqual(error.code, 'ENOENT'); + })); + + // Make sure that the error callback is called + // on next tick. + tickValue = 1; +}); From 3cd9833effed7e5cfbb32ccf19d42e714e01b488 Mon Sep 17 00:00:00 2001 From: abouthiroppy Date: Fri, 13 Jan 2017 09:34:24 +0900 Subject: [PATCH 216/291] test: add tests for rs+, sr+ to test-fs-open-flags.js PR-URL: https://github.com/nodejs/node/pull/10780 Reviewed-By: James M Snell Reviewed-By: Colin Ihrig Reviewed-By: Sam Roberts Reviewed-By: Michael Dawson --- test/parallel/test-fs-open-flags.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/test/parallel/test-fs-open-flags.js b/test/parallel/test-fs-open-flags.js index 878726580b6f6a..ee3380691104a4 100644 --- a/test/parallel/test-fs-open-flags.js +++ b/test/parallel/test-fs-open-flags.js @@ -10,6 +10,7 @@ const O_CREAT = fs.constants.O_CREAT || 0; const O_EXCL = fs.constants.O_EXCL || 0; const O_RDONLY = fs.constants.O_RDONLY || 0; const O_RDWR = fs.constants.O_RDWR || 0; +const O_SYNC = fs.constants.O_SYNC || 0; const O_TRUNC = fs.constants.O_TRUNC || 0; const O_WRONLY = fs.constants.O_WRONLY || 0; @@ -17,6 +18,8 @@ const { stringToFlags } = require('internal/fs'); assert.strictEqual(stringToFlags('r'), O_RDONLY); assert.strictEqual(stringToFlags('r+'), O_RDWR); +assert.strictEqual(stringToFlags('rs+'), O_RDWR | O_SYNC); +assert.strictEqual(stringToFlags('sr+'), O_RDWR | O_SYNC); assert.strictEqual(stringToFlags('w'), O_TRUNC | O_CREAT | O_WRONLY); assert.strictEqual(stringToFlags('w+'), O_TRUNC | O_CREAT | O_RDWR); assert.strictEqual(stringToFlags('a'), O_APPEND | O_CREAT | O_WRONLY); From 659428fe1dbf5fcf5965d1b265de57d57a10ca8d Mon Sep 17 00:00:00 2001 From: Daniel Bevenius Date: Wed, 18 Jan 2017 12:34:33 +0100 Subject: [PATCH 217/291] build: sort sources alphabetically MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The header files in the sources list are sorted alphabetically but not the c++ source code files. This commit sorts the c++ source code file names. PR-URL: https://github.com/nodejs/node/pull/10892 Reviewed-By: Luigi Pinca Reviewed-By: Ben Noordhuis Reviewed-By: Colin Ihrig Reviewed-By: Johan Bergström Reviewed-By: James M Snell --- node.gyp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/node.gyp b/node.gyp index 3fe0a9830fc2ac..1cb2497296a7ea 100644 --- a/node.gyp +++ b/node.gyp @@ -145,13 +145,13 @@ ], 'sources': [ - 'src/debug-agent.cc', 'src/async-wrap.cc', - 'src/env.cc', - 'src/fs_event_wrap.cc', 'src/cares_wrap.cc', 'src/connection_wrap.cc', 'src/connect_wrap.cc', + 'src/debug-agent.cc', + 'src/env.cc', + 'src/fs_event_wrap.cc', 'src/handle_wrap.cc', 'src/js_stream.cc', 'src/node.cc', @@ -174,6 +174,7 @@ 'src/node_zlib.cc', 'src/node_i18n.cc', 'src/pipe_wrap.cc', + 'src/process_wrap.cc', 'src/signal_wrap.cc', 'src/spawn_sync.cc', 'src/string_bytes.cc', @@ -183,7 +184,6 @@ 'src/tcp_wrap.cc', 'src/timer_wrap.cc', 'src/tty_wrap.cc', - 'src/process_wrap.cc', 'src/udp_wrap.cc', 'src/util.cc', 'src/uv.cc', From 537d954ed2f4811a8ca82e0cf04a49e55e4f1aa4 Mon Sep 17 00:00:00 2001 From: abouthiroppy Date: Wed, 18 Jan 2017 10:25:31 +0900 Subject: [PATCH 218/291] test: increase coverage of string-decoder Make use of Arrow Function. Add normalizeencoding's test. normalizeEncoding: https://github.com/nodejs/node/blob/master/lib/string_decoder.js#L9 PR-URL: https://github.com/nodejs/node/pull/10863 Reviewed-By: James M Snell Reviewed-By: Luigi Pinca Reviewed-By: Colin Ihrig Reviewed-By: Anna Henningsen --- test/parallel/test-string-decoder-end.js | 10 +++------- test/parallel/test-string-decoder.js | 12 ++++++++++-- 2 files changed, 13 insertions(+), 9 deletions(-) diff --git a/test/parallel/test-string-decoder-end.js b/test/parallel/test-string-decoder-end.js index a04972e545bf1d..6e9eea3193e163 100644 --- a/test/parallel/test-string-decoder-end.js +++ b/test/parallel/test-string-decoder-end.js @@ -8,15 +8,11 @@ const assert = require('assert'); const SD = require('string_decoder').StringDecoder; const encodings = ['base64', 'hex', 'utf8', 'utf16le', 'ucs2']; -const bufs = [ '☃💩', 'asdf' ].map(function(b) { - return Buffer.from(b); -}); +const bufs = [ '☃💩', 'asdf' ].map((b) => Buffer.from(b)); // also test just arbitrary bytes from 0-15. for (let i = 1; i <= 16; i++) { - const bytes = new Array(i).join('.').split('.').map(function(_, j) { - return j + 0x78; - }); + const bytes = new Array(i).join('.').split('.').map((_, j) => j + 0x78); bufs.push(Buffer.from(bytes)); } @@ -25,7 +21,7 @@ encodings.forEach(testEncoding); console.log('ok'); function testEncoding(encoding) { - bufs.forEach(function(buf) { + bufs.forEach((buf) => { testBuf(encoding, buf); }); } diff --git a/test/parallel/test-string-decoder.js b/test/parallel/test-string-decoder.js index 77ffbfcc73b1e1..a8fdb999a0923f 100644 --- a/test/parallel/test-string-decoder.js +++ b/test/parallel/test-string-decoder.js @@ -104,6 +104,14 @@ assert.strictEqual(decoder.write(Buffer.from('3DD8', 'hex')), ''); assert.strictEqual(decoder.write(Buffer.from('4D', 'hex')), ''); assert.strictEqual(decoder.end(), '\ud83d'); +assert.throws(() => { + new StringDecoder(1); +}, /^Error: Unknown encoding: 1$/); + +assert.throws(() => { + new StringDecoder('test'); +}, /^Error: Unknown encoding: test$/); + // test verifies that StringDecoder will correctly decode the given input // buffer with the given encoding to the expected output. It will attempt all // possible ways to write() the input buffer, see writeSequences(). The @@ -116,10 +124,10 @@ function test(encoding, input, expected, singleSequence) { } else { sequences = [singleSequence]; } - sequences.forEach(function(sequence) { + sequences.forEach((sequence) => { const decoder = new StringDecoder(encoding); let output = ''; - sequence.forEach(function(write) { + sequence.forEach((write) => { output += decoder.write(input.slice(write[0], write[1])); }); output += decoder.end(); From dc826caed24f1d7faf0d93651ac0b3473c585212 Mon Sep 17 00:00:00 2001 From: Franziska Hinkelmann Date: Tue, 20 Dec 2016 13:50:45 +0100 Subject: [PATCH 219/291] test: update V8 flag in test MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --expose-debug-as is deprecated in V8, switch test-preload.js to a flag that still exists. PR-URL: https://github.com/nodejs/node/pull/10917 Reviewed-By: Colin Ihrig Reviewed-By: Michaël Zasso --- test/parallel/test-preload.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/parallel/test-preload.js b/test/parallel/test-preload.js index 444c3a0a6d5e2b..8dc64cc6c60168 100644 --- a/test/parallel/test-preload.js +++ b/test/parallel/test-preload.js @@ -139,7 +139,7 @@ childProcess.exec( // https://github.com/nodejs/node/issues/1691 process.chdir(common.fixturesDir); childProcess.exec( - nodeBinary + ' ' + '--expose_debug_as=v8debug ' + '--require ' + + nodeBinary + ' ' + '--expose_natives_as=v8natives ' + '--require ' + fixture('cluster-preload.js') + ' ' + 'cluster-preload-test.js', function(err, stdout, stderr) { assert.ifError(err); From 90a99177a3a21f0e12de57915a09ef17188178bc Mon Sep 17 00:00:00 2001 From: abouthiroppy Date: Thu, 19 Jan 2017 15:36:32 +0900 Subject: [PATCH 220/291] test: add dgram.Socket.prototype.bind's test MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Test that an error is thrown when bind() is called on an already bound socket. PR-URL: https://github.com/nodejs/node/pull/10894 Reviewed-By: Luigi Pinca Reviewed-By: Colin Ihrig Reviewed-By: Claudio Rodriguez Reviewed-By: James M Snell Reviewed-By: Italo A. Casas Reviewed-By: Michaël Zasso --- test/parallel/test-dgram-bind.js | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/test/parallel/test-dgram-bind.js b/test/parallel/test-dgram-bind.js index 882f2e87bdd7ee..f4624358a4fab4 100644 --- a/test/parallel/test-dgram-bind.js +++ b/test/parallel/test-dgram-bind.js @@ -1,13 +1,17 @@ 'use strict'; -require('../common'); +const common = require('../common'); const assert = require('assert'); const dgram = require('dgram'); const socket = dgram.createSocket('udp4'); -socket.on('listening', function() { +socket.on('listening', common.mustCall(() => { + assert.throws(() => { + socket.bind(); + }, /^Error: Socket is already bound$/); + socket.close(); -}); +})); const result = socket.bind(); // should not throw From c0c1a4c029ebf4c8c067574c7bab1af22767ac7d Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Thu, 19 Jan 2017 17:18:13 -0800 Subject: [PATCH 221/291] url: refactor lib/internal/url.js MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * set an identifier for the separator rather than using multiple instances of the same literal * consistent arrow function body formatting PR-URL: https://github.com/nodejs/node/pull/10912 Reviewed-By: Michaël Zasso Reviewed-By: Joyee Cheung Reviewed-By: Colin Ihrig Reviewed-By: Italo A. Casas Reviewed-By: Timothy Gu --- lib/internal/url.js | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/lib/internal/url.js b/lib/internal/url.js index 9be683f28a4e06..679e14d72a9c39 100644 --- a/lib/internal/url.js +++ b/lib/internal/url.js @@ -860,6 +860,7 @@ URLSearchParams.prototype[Symbol.iterator] = URLSearchParams.prototype.entries; URLSearchParams.prototype[util.inspect.custom] = function inspect(recurseTimes, ctx) { + const separator = ', '; const innerOpts = Object.assign({}, ctx); if (recurseTimes !== null) { innerOpts.depth = recurseTimes - 1; @@ -872,13 +873,14 @@ URLSearchParams.prototype[util.inspect.custom] = output.push(`${innerInspect(list[i])} => ${innerInspect(list[i + 1])}`); const colorRe = /\u001b\[\d\d?m/g; - const length = output.reduce((prev, cur) => { - return prev + cur.replace(colorRe, '').length + ', '.length; - }, -', '.length); + const length = output.reduce( + (prev, cur) => prev + cur.replace(colorRe, '').length + separator.length, + -separator.length + ); if (length > ctx.breakLength) { return `${this.constructor.name} {\n ${output.join(',\n ')} }`; } else if (output.length) { - return `${this.constructor.name} { ${output.join(', ')} }`; + return `${this.constructor.name} { ${output.join(separator)} }`; } else { return `${this.constructor.name} {}`; } From b7bf43aa2b79bc5531e9e86a153026478f514b46 Mon Sep 17 00:00:00 2001 From: cjihrig Date: Thu, 19 Jan 2017 11:18:51 -0500 Subject: [PATCH 222/291] test: use common.fail() instead of assert(false) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR-URL: https://github.com/nodejs/node/pull/10899 Reviewed-By: James M Snell Reviewed-By: Michaël Zasso Reviewed-By: Italo A. Casas Reviewed-By: Luigi Pinca --- test/internet/test-dns.js | 20 +++++-------------- test/internet/test-tls-add-ca-cert.js | 2 +- .../test-async-wrap-throw-from-callback.js | 4 ++-- .../test-child-process-stdout-flush-exit.js | 3 +-- .../test-domain-uncaught-exception.js | 12 +++++------ test/parallel/test-http-conn-reset.js | 4 +--- .../test-http-double-content-length.js | 5 +---- test/parallel/test-http-parser.js | 6 ++---- ...test-http-response-multi-content-length.js | 2 +- test/parallel/test-net-error-twice.js | 4 ++-- test/parallel/test-net-reconnect-error.js | 3 +-- test/parallel/test-stream-writev.js | 4 ++-- test/parallel/test-tls-client-abort.js | 4 +--- test/parallel/test-tls-close-error.js | 4 +--- test/parallel/test-tls-connect.js | 5 +---- test/parallel/test-tls-handshake-error.js | 4 +--- test/parallel/test-vm-syntax-error-message.js | 4 ++-- .../test-whatwg-url-searchparams-foreach.js | 4 ++-- test/pummel/test-fs-watch-file.js | 7 ++----- 19 files changed, 34 insertions(+), 67 deletions(-) diff --git a/test/internet/test-dns.js b/test/internet/test-dns.js index 8a857c030af39e..3e154a5afad3fa 100644 --- a/test/internet/test-dns.js +++ b/test/internet/test-dns.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); const assert = require('assert'); const dns = require('dns'); const net = require('net'); @@ -44,19 +44,9 @@ function checkWrap(req) { TEST(function test_reverse_bogus(done) { - let error; - - try { - dns.reverse('bogus ip', function() { - assert.ok(false); - }); - } catch (e) { - error = e; - } - - assert.ok(error instanceof Error); - assert.strictEqual(error.errno, 'EINVAL'); - + assert.throws(() => { + dns.reverse('bogus ip', common.fail); + }, /^Error: getHostByAddr EINVAL$/); done(); }); @@ -442,7 +432,7 @@ TEST(function test_lookup_all_mixed(done) { else if (isIPv6(ip.address)) assert.strictEqual(ip.family, 6); else - assert(false); + common.fail('unexpected IP address'); }); done(); diff --git a/test/internet/test-tls-add-ca-cert.js b/test/internet/test-tls-add-ca-cert.js index 05f3b4dc10e36c..135b9215feaa4f 100644 --- a/test/internet/test-tls-add-ca-cert.js +++ b/test/internet/test-tls-add-ca-cert.js @@ -38,7 +38,7 @@ tls.connect(opts, fail).on('error', common.mustCall((err) => { })); function fail() { - assert(false, 'should fail to connect'); + common.fail('should fail to connect'); } // New secure contexts have the well-known root CAs. diff --git a/test/parallel/test-async-wrap-throw-from-callback.js b/test/parallel/test-async-wrap-throw-from-callback.js index b1a51773e2348c..c4a6a9bdaddd1c 100644 --- a/test/parallel/test-async-wrap-throw-from-callback.js +++ b/test/parallel/test-async-wrap-throw-from-callback.js @@ -37,10 +37,10 @@ if (typeof process.argv[2] === 'string') { async_wrap.setupHooks({ init, pre, post, destroy }); async_wrap.enable(); - process.on('uncaughtException', () => assert.ok(0, 'UNREACHABLE')); + process.on('uncaughtException', common.fail); const d = domain.create(); - d.on('error', () => assert.ok(0, 'UNREACHABLE')); + d.on('error', common.fail); d.run(() => { // Using randomBytes because timers are not yet supported. crypto.randomBytes(0, () => { }); diff --git a/test/parallel/test-child-process-stdout-flush-exit.js b/test/parallel/test-child-process-stdout-flush-exit.js index 9db74b51ce5864..682d382b9a1034 100644 --- a/test/parallel/test-child-process-stdout-flush-exit.js +++ b/test/parallel/test-child-process-stdout-flush-exit.js @@ -21,8 +21,7 @@ if (process.argv[2] === 'child') { child.stderr.setEncoding('utf8'); child.stderr.on('data', function(data) { - console.log('parent stderr: ' + data); - assert.ok(false); + common.fail(`Unexpected parent stderr: ${data}`); }); // check if we receive both 'hello' at start and 'goodbye' at end diff --git a/test/parallel/test-domain-uncaught-exception.js b/test/parallel/test-domain-uncaught-exception.js index 58df4ac59a7818..b13bf79b1a034b 100644 --- a/test/parallel/test-domain-uncaught-exception.js +++ b/test/parallel/test-domain-uncaught-exception.js @@ -9,7 +9,6 @@ */ const common = require('../common'); -const assert = require('assert'); const domain = require('domain'); const child_process = require('child_process'); @@ -184,17 +183,16 @@ if (process.argv[2] === 'child') { test.expectedMessages.forEach(function(expectedMessage) { if (test.messagesReceived === undefined || test.messagesReceived.indexOf(expectedMessage) === -1) - assert(false, 'test ' + test.fn.name + - ' should have sent message: ' + expectedMessage + - ' but didn\'t'); + common.fail('test ' + test.fn.name + ' should have sent message: ' + + expectedMessage + ' but didn\'t'); }); if (test.messagesReceived) { test.messagesReceived.forEach(function(receivedMessage) { if (test.expectedMessages.indexOf(receivedMessage) === -1) { - assert(false, 'test ' + test.fn.name + - ' should not have sent message: ' + receivedMessage + - ' but did'); + common.fail('test ' + test.fn.name + + ' should not have sent message: ' + receivedMessage + + ' but did'); } }); } diff --git a/test/parallel/test-http-conn-reset.js b/test/parallel/test-http-conn-reset.js index ae04c41aff5181..161e0e5c2bc830 100644 --- a/test/parallel/test-http-conn-reset.js +++ b/test/parallel/test-http-conn-reset.js @@ -19,9 +19,7 @@ server.listen(0, options.host, common.mustCall(onListen)); // do a GET request, expect it to fail function onListen() { options.port = this.address().port; - const req = http.request(options, function(res) { - assert.ok(false, 'this should never run'); - }); + const req = http.request(options, common.fail); req.on('error', common.mustCall(function(err) { assert.strictEqual(err.code, 'ECONNRESET'); })); diff --git a/test/parallel/test-http-double-content-length.js b/test/parallel/test-http-double-content-length.js index fdc79fb74ec5c2..0427d8edb8ae38 100644 --- a/test/parallel/test-http-double-content-length.js +++ b/test/parallel/test-http-double-content-length.js @@ -7,10 +7,7 @@ const assert = require('assert'); // The callback should never be invoked because the server // should respond with a 400 Client Error when a double // Content-Length header is received. -const server = http.createServer((req, res) => { - assert(false, 'callback should not have been invoked'); - res.end(); -}); +const server = http.createServer(common.fail); server.on('clientError', common.mustCall((err, socket) => { assert(/^Parse Error/.test(err.message)); assert.strictEqual(err.code, 'HPE_UNEXPECTED_CONTENT_LENGTH'); diff --git a/test/parallel/test-http-parser.js b/test/parallel/test-http-parser.js index de7302e60d91ba..ba987876e63142 100644 --- a/test/parallel/test-http-parser.js +++ b/test/parallel/test-http-parser.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); const assert = require('assert'); const binding = process.binding('http_parser'); @@ -35,9 +35,7 @@ function newParser(type) { parser[kOnHeadersComplete] = function(info) { }; - parser[kOnBody] = function(b, start, len) { - assert.ok(false, 'Function should not be called.'); - }; + parser[kOnBody] = common.fail; parser[kOnMessageComplete] = function() { }; diff --git a/test/parallel/test-http-response-multi-content-length.js b/test/parallel/test-http-response-multi-content-length.js index f3dce208756f74..5d53f7dcd5c621 100644 --- a/test/parallel/test-http-response-multi-content-length.js +++ b/test/parallel/test-http-response-multi-content-length.js @@ -35,7 +35,7 @@ server.listen(0, common.mustCall(() => { http.get( {port: server.address().port, headers: {'x-num': n}}, (res) => { - assert(false, 'client allowed multiple content-length headers.'); + common.fail('client allowed multiple content-length headers.'); } ).on('error', common.mustCall((err) => { assert(/^Parse Error/.test(err.message)); diff --git a/test/parallel/test-net-error-twice.js b/test/parallel/test-net-error-twice.js index 3c25d1c98ed346..79c85631594d4a 100644 --- a/test/parallel/test-net-error-twice.js +++ b/test/parallel/test-net-error-twice.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); const assert = require('assert'); const net = require('net'); @@ -20,7 +20,7 @@ const srv = net.createServer(function onConnection(conn) { conn.on('error', function(err) { errs.push(err); if (errs.length > 1 && errs[0] === errs[1]) - assert(false, 'We should not be emitting the same error twice'); + common.fail('Should not emit the same error twice'); }); conn.on('close', function() { srv.unref(); diff --git a/test/parallel/test-net-reconnect-error.js b/test/parallel/test-net-reconnect-error.js index 4e1e3d14984e80..e5e2124434cc89 100644 --- a/test/parallel/test-net-reconnect-error.js +++ b/test/parallel/test-net-reconnect-error.js @@ -10,8 +10,7 @@ let disconnect_count = 0; const c = net.createConnection(common.PORT); c.on('connect', function() { - console.error('CLIENT connected'); - assert.ok(false); + common.fail('client should not have connected'); }); c.on('error', function(e) { diff --git a/test/parallel/test-stream-writev.js b/test/parallel/test-stream-writev.js index 2caaf0a7d236c1..c62488c9e7650a 100644 --- a/test/parallel/test-stream-writev.js +++ b/test/parallel/test-stream-writev.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); const assert = require('assert'); const stream = require('stream'); @@ -39,7 +39,7 @@ function test(decode, uncork, multi, next) { const w = new stream.Writable({ decodeStrings: decode }); w._write = function(chunk, e, cb) { - assert(false, 'Should not call _write'); + common.fail('Should not call _write'); }; const expectChunks = decode ? [ diff --git a/test/parallel/test-tls-client-abort.js b/test/parallel/test-tls-client-abort.js index 21ee41e927873b..fcf1d92e3257d5 100644 --- a/test/parallel/test-tls-client-abort.js +++ b/test/parallel/test-tls-client-abort.js @@ -14,9 +14,7 @@ const path = require('path'); const cert = fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')); const key = fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')); -const conn = tls.connect({cert: cert, key: key, port: common.PORT}, function() { - assert.ok(false); // callback should never be executed -}); +const conn = tls.connect({cert, key, port: common.PORT}, common.fail); conn.on('error', function() { }); assert.doesNotThrow(function() { diff --git a/test/parallel/test-tls-close-error.js b/test/parallel/test-tls-close-error.js index 6172be813e97ce..91017cdce0667f 100644 --- a/test/parallel/test-tls-close-error.js +++ b/test/parallel/test-tls-close-error.js @@ -16,9 +16,7 @@ const server = tls.createServer({ cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }, function(c) { }).listen(0, common.mustCall(function() { - const c = tls.connect(this.address().port, function() { - assert(false, 'should not be called'); - }); + const c = tls.connect(this.address().port, common.fail); c.on('error', common.mustCall(function(err) {})); diff --git a/test/parallel/test-tls-connect.js b/test/parallel/test-tls-connect.js index 082e2e48a9dcc0..abaa1ae3346da5 100644 --- a/test/parallel/test-tls-connect.js +++ b/test/parallel/test-tls-connect.js @@ -1,6 +1,5 @@ 'use strict'; const common = require('../common'); -const assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); @@ -33,9 +32,7 @@ const path = require('path'); key: key, port: common.PORT, ciphers: 'rick-128-roll' - }, function() { - assert.ok(false); // callback should never be executed - }); + }, common.fail); conn.on('error', common.mustCall(function() {})); } diff --git a/test/parallel/test-tls-handshake-error.js b/test/parallel/test-tls-handshake-error.js index 4909fa45e160fb..2feb126669cc88 100644 --- a/test/parallel/test-tls-handshake-error.js +++ b/test/parallel/test-tls-handshake-error.js @@ -20,9 +20,7 @@ const server = tls.createServer({ const c = tls.connect({ port: this.address().port, ciphers: 'RC4' - }, function() { - assert(false, 'should not be called'); - }); + }, common.fail); c.on('error', common.mustCall(function(err) { assert.notStrictEqual(err.code, 'ECONNRESET'); diff --git a/test/parallel/test-vm-syntax-error-message.js b/test/parallel/test-vm-syntax-error-message.js index c0a00d06aa54f8..90f2b8c013406e 100644 --- a/test/parallel/test-vm-syntax-error-message.js +++ b/test/parallel/test-vm-syntax-error-message.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); const assert = require('assert'); const child_process = require('child_process'); @@ -12,7 +12,7 @@ const p = child_process.spawn(process.execPath, [ ]); p.stderr.on('data', function(data) { - assert(false, 'Unexpected stderr data: ' + data); + common.fail(`Unexpected stderr data: ${data}`); }); let output = ''; diff --git a/test/parallel/test-whatwg-url-searchparams-foreach.js b/test/parallel/test-whatwg-url-searchparams-foreach.js index 199d01b8fdfbcc..7e6b6222a8f101 100644 --- a/test/parallel/test-whatwg-url-searchparams-foreach.js +++ b/test/parallel/test-whatwg-url-searchparams-foreach.js @@ -1,6 +1,6 @@ 'use strict'; -require('../common'); +const common = require('../common'); const assert = require('assert'); const url = require('url'); const URL = url.URL; @@ -35,5 +35,5 @@ assert.deepStrictEqual(c[2], ['z', '3']); a = new URL('http://a.b/c'); b = a.searchParams; for (i of b) { - assert(false, 'should not be reached'); + common.fail('should not be reached'); } diff --git a/test/pummel/test-fs-watch-file.js b/test/pummel/test-fs-watch-file.js index 3fda41040486df..913f97737c8a54 100644 --- a/test/pummel/test-fs-watch-file.js +++ b/test/pummel/test-fs-watch-file.js @@ -93,16 +93,13 @@ setTimeout(function() { assert.doesNotThrow( function() { - function a() { - assert.ok(0); // should not run - } function b() { fs.unwatchFile(filenameThree, b); ++watchSeenThree; } - fs.watchFile(filenameThree, a); + fs.watchFile(filenameThree, common.fail); fs.watchFile(filenameThree, b); - fs.unwatchFile(filenameThree, a); + fs.unwatchFile(filenameThree, common.fail); } ); From cd94642356b65da348d4f91bc522a4673b7c23d4 Mon Sep 17 00:00:00 2001 From: cjihrig Date: Fri, 20 Jan 2017 10:37:56 -0500 Subject: [PATCH 223/291] src: add NODE_NO_WARNINGS to --help output MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This commit adds a description of the NODE_NO_WARNINGS environment variable to the --help output. This was overlooked in 49902124a9d697e441dbf724aa6b26bd98f75dd0. Refs: https://github.com/nodejs/node/pull/10842 PR-URL: https://github.com/nodejs/node/pull/10918 Reviewed-By: Michaël Zasso Reviewed-By: Sam Roberts Reviewed-By: Italo A. Casas Reviewed-By: Roman Reiss --- src/node.cc | 1 + 1 file changed, 1 insertion(+) diff --git a/src/node.cc b/src/node.cc index 406977cf09c0f1..33d38303d12d3b 100644 --- a/src/node.cc +++ b/src/node.cc @@ -3515,6 +3515,7 @@ static void PrintHelp() { " (will extend linked-in data)\n" #endif #endif + "NODE_NO_WARNINGS set to 1 to silence process warnings\n" #ifdef _WIN32 "NODE_PATH ';'-separated list of directories\n" #else From efa9845946ba7e8e0d2d2fa8e3a5901b47a7cca8 Mon Sep 17 00:00:00 2001 From: cjihrig Date: Thu, 19 Jan 2017 10:44:48 -0500 Subject: [PATCH 224/291] test: refactor test-cli-eval.js PR-URL: https://github.com/nodejs/node/pull/10898 Reviewed-By: James M Snell Reviewed-By: Rich Trott --- test/parallel/test-cli-eval.js | 149 +++++++++++++++++---------------- 1 file changed, 75 insertions(+), 74 deletions(-) diff --git a/test/parallel/test-cli-eval.js b/test/parallel/test-cli-eval.js index fdd0cc33f068d9..3eb821958539af 100644 --- a/test/parallel/test-cli-eval.js +++ b/test/parallel/test-cli-eval.js @@ -1,6 +1,7 @@ 'use strict'; if (module.parent) { - // signal we've been loaded as a module + // Signal we've been loaded as a module. + // The following console.log() is part of the test. console.log('Loaded as a module, exiting with status code 42.'); process.exit(42); } @@ -9,114 +10,114 @@ const common = require('../common'); const assert = require('assert'); const child = require('child_process'); const path = require('path'); -const nodejs = '"' + process.execPath + '"'; +const nodejs = `"${process.execPath}"`; +// Assert that nothing is written to stdout. +child.exec(`${nodejs} --eval 42`, common.mustCall((err, stdout, stderr) => { + assert.ifError(err); + assert.strictEqual(stdout, ''); + assert.strictEqual(stderr, ''); +})); -// replace \ by / because windows uses backslashes in paths, but they're still -// interpreted as the escape character when put between quotes. -const filename = __filename.replace(/\\/g, '/'); - -// assert that nothing is written to stdout -child.exec(nodejs + ' --eval 42', - function(err, stdout, stderr) { - assert.ifError(err); - assert.strictEqual(stdout, ''); - assert.strictEqual(stderr, ''); - }); - -// assert that "42\n" is written to stderr -child.exec(nodejs + ' --eval "console.error(42)"', - function(err, stdout, stderr) { +// Assert that "42\n" is written to stderr. +child.exec(`${nodejs} --eval "console.error(42)"`, + common.mustCall((err, stdout, stderr) => { assert.ifError(err); assert.strictEqual(stdout, ''); assert.strictEqual(stderr, '42\n'); - }); - -// assert that the expected output is written to stdout -['--print', '-p -e', '-pe', '-p'].forEach(function(s) { - const cmd = nodejs + ' ' + s + ' '; - - child.exec(cmd + '42', - function(err, stdout, stderr) { - assert.ifError(err); - assert.strictEqual(stdout, '42\n'); - assert.strictEqual(stderr, ''); - }); - - child.exec(cmd + "'[]'", common.mustCall( - function(err, stdout, stderr) { - assert.ifError(err); - assert.strictEqual(stdout, '[]\n'); - assert.strictEqual(stderr, ''); - })); + })); + +// Assert that the expected output is written to stdout. +['--print', '-p -e', '-pe', '-p'].forEach((s) => { + const cmd = `${nodejs} ${s} `; + + child.exec(`${cmd}42`, common.mustCall((err, stdout, stderr) => { + assert.ifError(err); + assert.strictEqual(stdout, '42\n'); + assert.strictEqual(stderr, ''); + })); + + child.exec(`${cmd} '[]'`, common.mustCall((err, stdout, stderr) => { + assert.ifError(err); + assert.strictEqual(stdout, '[]\n'); + assert.strictEqual(stderr, ''); + })); }); -// assert that module loading works -child.exec(nodejs + ' --eval "require(\'' + filename + '\')"', - function(err, stdout, stderr) { - assert.strictEqual(err.code, 42); - assert.strictEqual( - stdout, 'Loaded as a module, exiting with status code 42.\n'); - assert.strictEqual(stderr, ''); - }); +// Assert that module loading works. +{ + // Replace \ by / because Windows uses backslashes in paths, but they're still + // interpreted as the escape character when put between quotes. + const filename = __filename.replace(/\\/g, '/'); + + child.exec(`${nodejs} --eval "require('${filename}')"`, + common.mustCall((err, stdout, stderr) => { + assert.strictEqual(err.code, 42); + assert.strictEqual( + stdout, 'Loaded as a module, exiting with status code 42.\n'); + assert.strictEqual(stderr, ''); + })); +} // Check that builtin modules are pre-defined. -child.exec(nodejs + ' --print "os.platform()"', - function(err, stdout, stderr) { +child.exec(`${nodejs} --print "os.platform()"`, + common.mustCall((err, stdout, stderr) => { assert.ifError(err); assert.strictEqual(stderr, ''); assert.strictEqual(stdout.trim(), require('os').platform()); - }); + })); -// module path resolve bug, regression test -child.exec(nodejs + ' --eval "require(\'./test/parallel/test-cli-eval.js\')"', - function(err, stdout, stderr) { +// Module path resolve bug regression test. +child.exec(`${nodejs} --eval "require('./test/parallel/test-cli-eval.js')"`, + common.mustCall((err, stdout, stderr) => { assert.strictEqual(err.code, 42); assert.strictEqual( stdout, 'Loaded as a module, exiting with status code 42.\n'); assert.strictEqual(stderr, ''); - }); + })); -// Missing argument should not crash -child.exec(nodejs + ' -e', common.mustCall(function(err, stdout, stderr) { +// Missing argument should not crash. +child.exec(`${nodejs} -e`, common.mustCall((err, stdout, stderr) => { assert.strictEqual(err.code, 9); assert.strictEqual(stdout, ''); assert.strictEqual(stderr.trim(), `${process.execPath}: -e requires an argument`); })); -// empty program should do nothing -child.exec(nodejs + ' -e ""', function(err, stdout, stderr) { +// Empty program should do nothing. +child.exec(`${nodejs} -e ""`, common.mustCall((err, stdout, stderr) => { assert.ifError(err); assert.strictEqual(stdout, ''); assert.strictEqual(stderr, ''); -}); +})); -// "\\-42" should be interpreted as an escaped expression, not a switch -child.exec(nodejs + ' -p "\\-42"', - function(err, stdout, stderr) { - assert.ifError(err); - assert.strictEqual(stdout, '-42\n'); - assert.strictEqual(stderr, ''); - }); +// "\\-42" should be interpreted as an escaped expression, not a switch. +child.exec(`${nodejs} -p "\\-42"`, common.mustCall((err, stdout, stderr) => { + assert.ifError(err); + assert.strictEqual(stdout, '-42\n'); + assert.strictEqual(stderr, ''); +})); -child.exec(nodejs + ' --use-strict -p process.execArgv', - function(err, stdout, stderr) { +child.exec(`${nodejs} --use-strict -p process.execArgv`, + common.mustCall((err, stdout, stderr) => { assert.ifError(err); assert.strictEqual( stdout, "[ '--use-strict', '-p', 'process.execArgv' ]\n" ); assert.strictEqual(stderr, ''); - }); + })); -// Regression test for https://github.com/nodejs/node/issues/3574 -const emptyFile = path.join(common.fixturesDir, 'empty.js'); -child.exec(nodejs + ` -e 'require("child_process").fork("${emptyFile}")'`, - function(err, stdout, stderr) { - assert.ifError(err); - assert.strictEqual(stdout, ''); - assert.strictEqual(stderr, ''); - }); +// Regression test for https://github.com/nodejs/node/issues/3574. +{ + const emptyFile = path.join(common.fixturesDir, 'empty.js'); + + child.exec(`${nodejs} -e 'require("child_process").fork("${emptyFile}")'`, + common.mustCall((err, stdout, stderr) => { + assert.ifError(err); + assert.strictEqual(stdout, ''); + assert.strictEqual(stderr, ''); + })); +} // Regression test for https://github.com/nodejs/node/issues/8534. { From eb7ee5071768de4c28df1f9a10b4a5d4d1be1f10 Mon Sep 17 00:00:00 2001 From: Adrian Estrada Date: Thu, 19 Jan 2017 20:40:33 -0500 Subject: [PATCH 225/291] test: improve code in test-crypto-verify MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * use common.mustCall to validate functions executions * use common.fail to check test fail * remove console.log * use arrow functions PR-URL: https://github.com/nodejs/node/pull/10845 Reviewed-By: Colin Ihrig Reviewed-By: Sam Roberts Reviewed-By: Michaël Zasso Reviewed-By: James M Snell --- test/parallel/test-crypto-verify-failure.js | 28 +++++++++------------ 1 file changed, 12 insertions(+), 16 deletions(-) diff --git a/test/parallel/test-crypto-verify-failure.js b/test/parallel/test-crypto-verify-failure.js index c171814dd3c3a6..fdf0d6f6456dac 100644 --- a/test/parallel/test-crypto-verify-failure.js +++ b/test/parallel/test-crypto-verify-failure.js @@ -19,36 +19,32 @@ const options = { cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }; -const server = tls.Server(options, function(socket) { - setImmediate(function() { - console.log('sending'); +const server = tls.Server(options, (socket) => { + setImmediate(() => { verify(); - setImmediate(function() { + setImmediate(() => { socket.destroy(); }); }); }); function verify() { - console.log('verify'); crypto.createVerify('RSA-SHA1') .update('Test') .verify(certPem, 'asdfasdfas', 'base64'); } -server.listen(0, function() { +server.listen(0, common.mustCall(() => { tls.connect({ - port: this.address().port, + port: server.address().port, rejectUnauthorized: false - }, function() { + }, common.mustCall(() => { verify(); - }).on('data', function(data) { - console.log(data); - }).on('error', function(err) { - throw err; - }).on('close', function() { - server.close(); - }).resume(); -}); + })) + .on('error', common.fail) + .on('close', common.mustCall(() => { + server.close(); + })).resume(); +})); server.unref(); From a1897c1445aca0e7fd2574bbb6d96e3790face92 Mon Sep 17 00:00:00 2001 From: Adam Majer Date: Wed, 21 Dec 2016 11:16:39 +0100 Subject: [PATCH 226/291] crypto: ability to select cert store at runtime PR-URL: https://github.com/nodejs/node/pull/8334 Reviewed-By: Sam Roberts Reviewed-By: James M Snell Reviewed-By: Fedor Indutny --- doc/api/cli.md | 36 ++++++++++++++++++++++++++++++++++++ doc/node.1 | 25 +++++++++++++++++++++++++ src/node.cc | 22 ++++++++++++++++++++++ src/node.h | 5 ++++- src/node_crypto.cc | 14 +++++++------- 5 files changed, 94 insertions(+), 8 deletions(-) diff --git a/doc/api/cli.md b/doc/api/cli.md index 30d4c62e52b8a1..3aeac43afb3e3e 100644 --- a/doc/api/cli.md +++ b/doc/api/cli.md @@ -243,6 +243,24 @@ Load an OpenSSL configuration file on startup. Among other uses, this can be used to enable FIPS-compliant crypto if Node.js is built with `./configure --openssl-fips`. +### `--use-openssl-ca`, `--use-bundled-ca` + + +Use OpenSSL's default CA store or use bundled Mozilla CA store as supplied by +current NodeJS version. The default store is selectable at build-time. + +Using OpenSSL store allows for external modifications of the store. For most +Linux and BSD distributions, this store is maintained by the distribution +maintainers and system administrators. OpenSSL CA store location is dependent on +configuration of the OpenSSL library but this can be altered at runtime using +environmental variables. + +The bundled CA store, as supplied by NodeJS, is a snapshot of Mozilla CA store +that is fixed at release time. It is identical on all supported platforms. + +See `SSL_CERT_DIR` and `SSL_CERT_FILE`. ### `--icu-data-dir=file` + +Indicate the end of node options. Pass the rest of the arguments to the script. +If no script filename or eval/print script is supplied prior to this, then +the next argument will be used as a script filename. + ## Environment Variables ### `NODE_DEBUG=module[,…]` diff --git a/doc/node.1 b/doc/node.1 index e609a9d781e04a..ffe72e1d022aa6 100644 --- a/doc/node.1 +++ b/doc/node.1 @@ -37,6 +37,7 @@ node \- Server-side JavaScript runtime .RI [ script.js \ | .B -e .RI \&" script \&"] +.B [--] .RI [ arguments ] .br .B node debug @@ -191,6 +192,13 @@ See \fBSSL_CERT_DIR\fR and \fBSSL_CERT_FILE\fR. .BR \-\-icu\-data\-dir =\fIfile\fR Specify ICU data load path. (overrides \fBNODE_ICU_DATA\fR) +.TP +.BR \-\-\fR +Indicate the end of node options. Pass the rest of the arguments to the script. + +If no script filename or eval/print script is supplied prior to this, then +the next argument will be used as a script filename. + .SH ENVIRONMENT VARIABLES .TP diff --git a/src/node.cc b/src/node.cc index 96cfe9f2c3206c..3c6b9a731dc2b1 100644 --- a/src/node.cc +++ b/src/node.cc @@ -3688,6 +3688,9 @@ static void ParseArgs(int* argc, } else if (strcmp(arg, "--expose-internals") == 0 || strcmp(arg, "--expose_internals") == 0) { // consumed in js + } else if (strcmp(arg, "--") == 0) { + index += 1; + break; } else { // V8 option. Pass through as-is. new_v8_argv[new_v8_argc] = arg; diff --git a/test/parallel/test-cli-eval.js b/test/parallel/test-cli-eval.js index 3eb821958539af..260acdb0d6f90a 100644 --- a/test/parallel/test-cli-eval.js +++ b/test/parallel/test-cli-eval.js @@ -12,6 +12,11 @@ const child = require('child_process'); const path = require('path'); const nodejs = `"${process.execPath}"`; +if (process.argv.length > 2) { + console.log(process.argv.slice(2).join(' ')); + process.exit(0); +} + // Assert that nothing is written to stdout. child.exec(`${nodejs} --eval 42`, common.mustCall((err, stdout, stderr) => { assert.ifError(err); @@ -133,3 +138,38 @@ child.exec(`${nodejs} --use-strict -p process.execArgv`, assert.strictEqual(proc.stderr, ''); assert.strictEqual(proc.stdout, 'start\nbeforeExit\nexit\n'); } + +[ '-arg1', + '-arg1 arg2 --arg3', + '--', + 'arg1 -- arg2', +].forEach(function(args) { + + // Ensure that arguments are successfully passed to eval. + const opt = ' --eval "console.log(process.argv.slice(1).join(\' \'))"'; + const cmd = `${nodejs}${opt} -- ${args}`; + child.exec(cmd, common.mustCall(function(err, stdout, stderr) { + assert.strictEqual(stdout, args + '\n'); + assert.strictEqual(stderr, ''); + assert.strictEqual(err, null); + })); + + // Ensure that arguments are successfully passed to print. + const popt = ' --print "process.argv.slice(1).join(\' \')"'; + const pcmd = `${nodejs}${popt} -- ${args}`; + child.exec(pcmd, common.mustCall(function(err, stdout, stderr) { + assert.strictEqual(stdout, args + '\n'); + assert.strictEqual(stderr, ''); + assert.strictEqual(err, null); + })); + + // Ensure that arguments are successfully passed to a script. + // The first argument after '--' should be interpreted as a script + // filename. + const filecmd = `${nodejs} -- ${__filename} ${args}`; + child.exec(filecmd, common.mustCall(function(err, stdout, stderr) { + assert.strictEqual(stdout, args + '\n'); + assert.strictEqual(stderr, ''); + assert.strictEqual(err, null); + })); +}); From e7c953a5f92fa1229a178740576940aaf4dd9d43 Mon Sep 17 00:00:00 2001 From: "dcposch@dcpos.ch" Date: Tue, 6 Dec 2016 23:28:06 -0800 Subject: [PATCH 229/291] test: update Buffer.lastIndexOf Test type coercion for non-number offset arguments. Verify that Buffer and String behave the same way. PR-URL: https://github.com/nodejs/node/pull/10162 Fixes: https://github.com/nodejs/node/issues/9801 Reviewed-By: Roman Reiss Reviewed-By: Stephen Belanger Reviewed-By: Trevor Norris Reviewed-By: James M Snell Reviewed-By: Sakthipriyan Vairamani Reviewed-By: Rich Trott --- test/parallel/test-buffer-indexof.js | 63 ++++++++++++++++++++++++++-- 1 file changed, 60 insertions(+), 3 deletions(-) diff --git a/test/parallel/test-buffer-indexof.js b/test/parallel/test-buffer-indexof.js index 8efd318762684c..977d44ba3d8f05 100644 --- a/test/parallel/test-buffer-indexof.js +++ b/test/parallel/test-buffer-indexof.js @@ -11,6 +11,8 @@ const buf_f = Buffer.from('f'); const buf_z = Buffer.from('z'); const buf_empty = Buffer.from(''); +const s = 'abcdef'; + assert.strictEqual(b.indexOf('a'), 0); assert.strictEqual(b.indexOf('a', 1), -1); assert.strictEqual(b.indexOf('a', -1), -1); @@ -359,6 +361,37 @@ assert.throws(() => { b.indexOf([]); }, argumentExpected); +// Test weird offset arguments. +// The following offsets coerce to NaN or 0, searching the whole Buffer +assert.strictEqual(b.indexOf('b', undefined), 1); +assert.strictEqual(b.indexOf('b', {}), 1); +assert.strictEqual(b.indexOf('b', 0), 1); +assert.strictEqual(b.indexOf('b', null), 1); +assert.strictEqual(b.indexOf('b', []), 1); + +// The following offset coerces to 2, in other words +[2] === 2 +assert.strictEqual(b.indexOf('b', [2]), -1); + +// Behavior should match String.indexOf() +assert.strictEqual( + b.indexOf('b', undefined), + s.indexOf('b', undefined)); +assert.strictEqual( + b.indexOf('b', {}), + s.indexOf('b', {})); +assert.strictEqual( + b.indexOf('b', 0), + s.indexOf('b', 0)); +assert.strictEqual( + b.indexOf('b', null), + s.indexOf('b', null)); +assert.strictEqual( + b.indexOf('b', []), + s.indexOf('b', [])); +assert.strictEqual( + b.indexOf('b', [2]), + s.indexOf('b', [2])); + // All code for handling encodings is shared between Buffer.indexOf and // Buffer.lastIndexOf, so only testing the separate lastIndexOf semantics. @@ -413,14 +446,38 @@ assert.strictEqual(b.lastIndexOf(0x61, Infinity), 0); assert.strictEqual(b.lastIndexOf(0x0), -1); // Test weird offset arguments. -// Behaviour should match String.lastIndexOf: -assert.strictEqual(b.lastIndexOf('b', 0), -1); +// The following offsets coerce to NaN, searching the whole Buffer assert.strictEqual(b.lastIndexOf('b', undefined), 1); -assert.strictEqual(b.lastIndexOf('b', null), -1); assert.strictEqual(b.lastIndexOf('b', {}), 1); + +// The following offsets coerce to 0 +assert.strictEqual(b.lastIndexOf('b', 0), -1); +assert.strictEqual(b.lastIndexOf('b', null), -1); assert.strictEqual(b.lastIndexOf('b', []), -1); + +// The following offset coerces to 2, in other words +[2] === 2 assert.strictEqual(b.lastIndexOf('b', [2]), 1); +// Behavior should match String.lastIndexOf() +assert.strictEqual( + b.lastIndexOf('b', undefined), + s.lastIndexOf('b', undefined)); +assert.strictEqual( + b.lastIndexOf('b', {}), + s.lastIndexOf('b', {})); +assert.strictEqual( + b.lastIndexOf('b', 0), + s.lastIndexOf('b', 0)); +assert.strictEqual( + b.lastIndexOf('b', null), + s.lastIndexOf('b', null)); +assert.strictEqual( + b.lastIndexOf('b', []), + s.lastIndexOf('b', [])); +assert.strictEqual( + b.lastIndexOf('b', [2]), + s.lastIndexOf('b', [2])); + // Test needles longer than the haystack. assert.strictEqual(b.lastIndexOf('aaaaaaaaaaaaaaa', 'ucs2'), -1); assert.strictEqual(b.lastIndexOf('aaaaaaaaaaaaaaa', 'utf8'), -1); From dd608591a891aaecf3aa5ba44f87768f0c254f73 Mon Sep 17 00:00:00 2001 From: "dcposch@dcpos.ch" Date: Wed, 7 Dec 2016 00:36:16 -0800 Subject: [PATCH 230/291] doc: clarify Buffer.indexOf/lastIndexOf edge cases PR-URL: https://github.com/nodejs/node/pull/10162 Fixes: https://github.com/nodejs/node/issues/9801 Reviewed-By: Roman Reiss Reviewed-By: Stephen Belanger Reviewed-By: Trevor Norris Reviewed-By: James M Snell Reviewed-By: Sakthipriyan Vairamani Reviewed-By: Rich Trott --- doc/api/buffer.md | 53 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/doc/api/buffer.md b/doc/api/buffer.md index adc9d6b104680b..c9f15b14476083 100644 --- a/doc/api/buffer.md +++ b/doc/api/buffer.md @@ -1151,6 +1151,30 @@ console.log(utf16Buffer.indexOf('\u03a3', 0, 'ucs2')); console.log(utf16Buffer.indexOf('\u03a3', -4, 'ucs2')); ``` +If `value` is not a string, number, or `Buffer`, this method will throw a +`TypeError`. If `value` is a number, it will be coerced to a valid byte value, +an integer between 0 and 255. + +If `byteOffset` is not a number, it will be coerced to a number. Any arguments +that coerce to `NaN` or 0, like `{}`, `[]`, `null` or `undefined`, will search +the whole buffer. This behavior matches [`String#indexOf()`]. + +```js +const b = Buffer.from('abcdef'); + +// Passing a value that's a number, but not a valid byte +// Prints: 2, equivalent to searching for 99 or 'c' +console.log(b.indexOf(99.9)); +console.log(b.indexOf(256 + 99)); + +// Passing a byteOffset that coerces to NaN or 0 +// Prints: 1, searching the whole buffer +console.log(b.indexOf('b', undefined)); +console.log(b.indexOf('b', {})); +console.log(b.indexOf('b', null)); +console.log(b.indexOf('b', [])); +``` + ### buf.includes(value[, byteOffset][, encoding]) -The HTTP Agent is used for pooling sockets used in HTTP client -requests. - -The HTTP Agent also defaults client requests to using -`Connection: keep-alive`. If no pending HTTP requests are waiting on a -socket to become free the socket is closed. This means that Node.js's -pool has the benefit of keep-alive when under load but still does not -require developers to manually close the HTTP clients using -KeepAlive. - -If you opt into using HTTP KeepAlive, you can create an Agent object -with that flag set to `true`. (See the [constructor options][].) -Then, the Agent will keep unused sockets in a pool for later use. They -will be explicitly marked so as to not keep the Node.js process running. -However, it is still a good idea to explicitly [`destroy()`][] KeepAlive -agents when they are no longer in use, so that the Sockets will be shut -down. - -Sockets are removed from the agent's pool when the socket emits either -a `'close'` event or a special `'agentRemove'` event. This means that if +An `Agent` is responsible for managing connection persistence +and reuse for HTTP clients. It maintains a queue of pending requests +for a given host and port, reusing a single socket connection for each +until the queue is empty, at which time the socket is either destroyed +or put into a pool where it is kept to be used again for requests to the +same host and port. Whether it is destroyed or pooled depends on the +`keepAlive` [option](#http_new_agent_options). + +Pooled connections have TCP Keep-Alive enabled for them, but servers may +still close idle connections, in which case they will be removed from the +pool and a new connection will be made when a new HTTP request is made for +that host and port. Servers may also refuse to allow multiple requests +over the same connection, in which case the connection will have to be +remade for every request and cannot be pooled. The `Agent` will still make +the requests to that server, but each one will occur over a new connection. + +When a connection is closed by the client or the server, it is removed +from the pool. Any unused sockets in the pool will be unrefed so as not +to keep the Node.js process running when there are no outstanding requests. +(see [socket.unref()]). + +It is good practice, to [`destroy()`][] an `Agent` instance when it is no +longer in use, because unused sockets consume OS resources. + +Sockets are removed from an agent's pool when the socket emits either +a `'close'` event or an `'agentRemove'` event. This means that if you intend to keep one HTTP request open for a long time and don't want it to stay in the pool you can do something along the lines of: @@ -79,7 +85,11 @@ http.get(options, (res) => { }); ``` -Alternatively, you could just opt out of pooling entirely using +You may also use an agent for an individual request. By providing +`{agent: false}` as an option to the `http.get()` or `http.request()` +functions, a one-time use `Agent` with default options will be used +for the client connection. + `agent:false`: ```js @@ -100,11 +110,13 @@ added: v0.3.4 * `options` {Object} Set of configurable options to set on the agent. Can have the following fields: - * `keepAlive` {Boolean} Keep sockets around in a pool to be used by - other requests in the future. Default = `false` - * `keepAliveMsecs` {Integer} When using HTTP KeepAlive, how often - to send TCP KeepAlive packets over sockets being kept alive. - Default = `1000`. Only relevant if `keepAlive` is set to `true`. + * `keepAlive` {Boolean} Keep sockets around even when there are no + outstanding requests, so they can be used for future requests without + having to reestablish a TCP connection. Default = `false` + * `keepAliveMsecs` {Integer} When using the `keepAlive` option, specifies + the [initial delay](#net_socket_setkeepalive_enable_initialdelay) + for TCP Keep-Alive packets. Ignored when the + `keepAlive` option is `false` or `undefined`. Default = `1000`. * `maxSockets` {Number} Maximum number of sockets to allow per host. Default = `Infinity`. * `maxFreeSockets` {Number} Maximum number of sockets to leave open @@ -114,7 +126,7 @@ added: v0.3.4 The default [`http.globalAgent`][] that is used by [`http.request()`][] has all of these values set to their respective defaults. -To configure any of them, you must create your own [`http.Agent`][] object. +To configure any of them, you must create your own [`http.Agent`][] instance. ```js const http = require('http'); @@ -136,7 +148,7 @@ added: v0.11.4 Produces a socket/stream to be used for HTTP requests. By default, this function is the same as [`net.createConnection()`][]. However, -custom Agents may override this method in case greater flexibility is desired. +custom agents may override this method in case greater flexibility is desired. A socket/stream can be supplied in one of two ways: by returning the socket/stream from this function, or by passing the socket/stream to `callback`. @@ -151,7 +163,7 @@ added: v0.11.4 Destroy any sockets that are currently in use by the agent. It is usually not necessary to do this. However, if you are using an -agent with KeepAlive enabled, then it is best to explicitly shut down +agent with `keepAlive` enabled, then it is best to explicitly shut down the agent when you know that it will no longer be used. Otherwise, sockets may hang open for quite a long time before the server terminates them. @@ -164,7 +176,7 @@ added: v0.11.4 * {Object} An object which contains arrays of sockets currently awaiting use by -the Agent when HTTP KeepAlive is used. Do not modify. +the agent when `keepAlive` is enabled. Do not modify. ### agent.getName(options) diff --git a/test/doctool/test-doctool-html.js b/test/doctool/test-doctool-html.js index e5c825aebbb32c..442381b54d7b72 100644 --- a/test/doctool/test-doctool-html.js +++ b/test/doctool/test-doctool-html.js @@ -72,11 +72,18 @@ const testData = [ '

I exist and am being linked to.

' + '' }, + { + file: path.join(common.fixturesDir, 'sample_document.md'), + html: '
  1. fish
  2. fish

  3. Redfish

  4. ' + + '
  5. Bluefish
', + analyticsId: 'UA-67020396-1' + }, ]; testData.forEach((item) => { // Normalize expected data by stripping whitespace const expected = item.html.replace(/\s/g, ''); + const includeAnalytics = typeof item.analyticsId !== 'undefined'; fs.readFile(item.file, 'utf8', common.mustCall((err, input) => { assert.ifError(err); @@ -89,6 +96,7 @@ testData.forEach((item) => { filename: 'foo', template: 'doc/template.html', nodeVersion: process.version, + analytics: item.analyticsId, }, common.mustCall((err, output) => { assert.ifError(err); @@ -97,6 +105,16 @@ testData.forEach((item) => { // Assert that the input stripped of all whitespace contains the // expected list assert.notStrictEqual(actual.indexOf(expected), -1); + + // Testing the insertion of Google Analytics script when + // an analytics id is provided. Should not be present by default + if (includeAnalytics) { + assert.notStrictEqual(actual.indexOf('google-analytics.com'), -1, + 'Google Analytics script was not present'); + } else { + assert.strictEqual(actual.indexOf('google-analytics.com'), -1, + 'Google Analytics script was present'); + } })); })); })); diff --git a/tools/doc/generate.js b/tools/doc/generate.js index 31b23c52a08ba7..b7fcf0d4f90da5 100644 --- a/tools/doc/generate.js +++ b/tools/doc/generate.js @@ -11,16 +11,19 @@ let format = 'json'; let template = null; let inputFile = null; let nodeVersion = null; +let analytics = null; args.forEach(function(arg) { - if (!arg.match(/^--/)) { + if (!arg.startsWith('--')) { inputFile = arg; - } else if (arg.match(/^--format=/)) { + } else if (arg.startsWith('--format=')) { format = arg.replace(/^--format=/, ''); - } else if (arg.match(/^--template=/)) { + } else if (arg.startsWith('--template=')) { template = arg.replace(/^--template=/, ''); - } else if (arg.match(/^--node-version=/)) { + } else if (arg.startsWith('--node-version=')) { nodeVersion = arg.replace(/^--node-version=/, ''); + } else if (arg.startsWith('--analytics=')) { + analytics = arg.replace(/^--analytics=/, ''); } }); @@ -54,6 +57,7 @@ function next(er, input) { filename: inputFile, template: template, nodeVersion: nodeVersion, + analytics: analytics, }, function(er, html) { diff --git a/tools/doc/html.js b/tools/doc/html.js index c0790ffca5f0d4..4b1c0a0e69b2c1 100644 --- a/tools/doc/html.js +++ b/tools/doc/html.js @@ -67,6 +67,7 @@ function toHTML(opts, cb) { filename: opts.filename, template: template, nodeVersion: nodeVersion, + analytics: opts.analytics, }, cb); }); } @@ -128,6 +129,13 @@ function render(opts, cb) { gtocData.replace('class="nav-' + id, 'class="nav-' + id + ' active') ); + if (opts.analytics) { + template = template.replace( + '', + analyticsScript(opts.analytics) + ); + } + // content has to be the last thing we do with // the lexed tokens, because it's destructive. const content = marked.parser(lexed); @@ -137,6 +145,23 @@ function render(opts, cb) { }); } +function analyticsScript(analytics) { + return ` + + + `; +} + // handle general body-text replacements // for example, link man page references to the actual page function parseText(lexed) { From 8a6367cb206381e180d920966b524b6f734c650f Mon Sep 17 00:00:00 2001 From: Anna Henningsen Date: Fri, 20 Jan 2017 19:36:57 +0100 Subject: [PATCH 240/291] Revert "src: don't overwrite non-writable vm globals" This reverts commit 524f693872cf453af2655ec47356d25d52394e3d. Fixes: https://github.com/nodejs/node/issues/10806 Fixes: https://github.com/nodejs/node/issues/10492 Ref: https://github.com/nodejs/node/pull/10227 PR-URL: https://github.com/nodejs/node/pull/10920 Reviewed-By: Franziska Hinkelmann Reviewed-By: James M Snell Reviewed-By: Ben Noordhuis --- src/node_contextify.cc | 23 ++++++++++------------- test/parallel/test-vm-context.js | 11 ----------- 2 files changed, 10 insertions(+), 24 deletions(-) diff --git a/src/node_contextify.cc b/src/node_contextify.cc index fc8aa451347b94..d74b01ea0da371 100644 --- a/src/node_contextify.cc +++ b/src/node_contextify.cc @@ -383,22 +383,19 @@ class ContextifyContext { if (ctx->context_.IsEmpty()) return; - auto attributes = PropertyAttribute::None; bool is_declared = - ctx->global_proxy()->GetRealNamedPropertyAttributes(ctx->context(), - property) - .To(&attributes); - bool read_only = - static_cast(attributes) & - static_cast(PropertyAttribute::ReadOnly); - - if (is_declared && read_only) - return; + ctx->global_proxy()->HasRealNamedProperty(ctx->context(), + property).FromJust(); + bool is_contextual_store = ctx->global_proxy() != args.This(); - if (!is_declared && args.ShouldThrowOnError()) - return; + bool set_property_will_throw = + args.ShouldThrowOnError() && + !is_declared && + is_contextual_store; - ctx->sandbox()->Set(property, value); + if (!set_property_will_throw) { + ctx->sandbox()->Set(property, value); + } } diff --git a/test/parallel/test-vm-context.js b/test/parallel/test-vm-context.js index 7056ce7be35d05..75d91ce8129dcb 100644 --- a/test/parallel/test-vm-context.js +++ b/test/parallel/test-vm-context.js @@ -75,14 +75,3 @@ assert.throws(function() { // https://github.com/nodejs/node/issues/6158 ctx = new Proxy({}, {}); assert.strictEqual(typeof vm.runInNewContext('String', ctx), 'function'); - -// https://github.com/nodejs/node/issues/10223 -ctx = vm.createContext(); -vm.runInContext('Object.defineProperty(this, "x", { value: 42 })', ctx); -assert.strictEqual(ctx.x, undefined); // Not copied out by cloneProperty(). -assert.strictEqual(vm.runInContext('x', ctx), 42); -vm.runInContext('x = 0', ctx); // Does not throw but x... -assert.strictEqual(vm.runInContext('x', ctx), 42); // ...should be unaltered. -assert.throws(() => vm.runInContext('"use strict"; x = 0', ctx), - /Cannot assign to read only property 'x'/); -assert.strictEqual(vm.runInContext('x', ctx), 42); From 74ff804dbdc72d2577bf3c915d4cc2cb87808931 Mon Sep 17 00:00:00 2001 From: Anna Henningsen Date: Fri, 20 Jan 2017 19:44:56 +0100 Subject: [PATCH 241/291] test: add regression tests for vm bugs Add the regression test script presented in https://github.com/nodejs/node/issues/10806 to `test/parallel` and re-add the original regression test for https://github.com/nodejs/node/issues/10223 in `test/known_issues`. PR-URL: https://github.com/nodejs/node/pull/10920 Reviewed-By: Franziska Hinkelmann Reviewed-By: James M Snell Reviewed-By: Ben Noordhuis --- .../test-vm-global-non-writable-properties.js | 16 ++++++++++++++++ test/parallel/test-vm-global-assignment.js | 15 +++++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 test/known_issues/test-vm-global-non-writable-properties.js create mode 100644 test/parallel/test-vm-global-assignment.js diff --git a/test/known_issues/test-vm-global-non-writable-properties.js b/test/known_issues/test-vm-global-non-writable-properties.js new file mode 100644 index 00000000000000..8d7dfce55e3d81 --- /dev/null +++ b/test/known_issues/test-vm-global-non-writable-properties.js @@ -0,0 +1,16 @@ +'use strict'; +// https://github.com/nodejs/node/issues/10223 + +require('../common'); +const assert = require('assert'); +const vm = require('vm'); + +const ctx = vm.createContext(); +vm.runInContext('Object.defineProperty(this, "x", { value: 42 })', ctx); +assert.strictEqual(ctx.x, undefined); // Not copied out by cloneProperty(). +assert.strictEqual(vm.runInContext('x', ctx), 42); +vm.runInContext('x = 0', ctx); // Does not throw but x... +assert.strictEqual(vm.runInContext('x', ctx), 42); // ...should be unaltered. +assert.throws(() => vm.runInContext('"use strict"; x = 0', ctx), + /Cannot assign to read only property 'x'/); +assert.strictEqual(vm.runInContext('x', ctx), 42); diff --git a/test/parallel/test-vm-global-assignment.js b/test/parallel/test-vm-global-assignment.js new file mode 100644 index 00000000000000..3fb3470b4c2a43 --- /dev/null +++ b/test/parallel/test-vm-global-assignment.js @@ -0,0 +1,15 @@ +'use strict'; +// Regression test for https://github.com/nodejs/node/issues/10806 + +require('../common'); +const assert = require('assert'); +const vm = require('vm'); +const ctx = vm.createContext({ open() { } }); +const window = vm.runInContext('this', ctx); +const other = 123; + +assert.notStrictEqual(window.open, other); +window.open = other; +assert.strictEqual(window.open, other); +window.open = other; +assert.strictEqual(window.open, other); From fa8baa2aa13e42bf14f5413d46e173361517e1cc Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Sun, 22 Jan 2017 21:26:55 -0800 Subject: [PATCH 242/291] test: enhance test-timers In test-timers, confirm that all input values that should be coerced to 1 ms are not being coerced to a significantly larger value. This eliminates the need for the separate test-regress-GH-897. PR-URL: https://github.com/nodejs/node/pull/10960 Reviewed-By: James M Snell Reviewed-By: Luigi Pinca --- test/parallel/test-regress-GH-897.js | 20 -------------------- test/parallel/test-timers.js | 22 +++++++++++++++------- 2 files changed, 15 insertions(+), 27 deletions(-) delete mode 100644 test/parallel/test-regress-GH-897.js diff --git a/test/parallel/test-regress-GH-897.js b/test/parallel/test-regress-GH-897.js deleted file mode 100644 index 911ad6b6b2e112..00000000000000 --- a/test/parallel/test-regress-GH-897.js +++ /dev/null @@ -1,20 +0,0 @@ -'use strict'; - -// Test for bug where a timer duration greater than 0 ms but less than 1 ms -// resulted in the duration being set for 1000 ms. The expected behavior is -// that the timeout would be set for 1 ms, and thus fire before timers set -// with values greater than 1ms. -// -// Ref: https://github.com/nodejs/node-v0.x-archive/pull/897 - -const common = require('../common'); - -let timer; - -setTimeout(function() { - clearTimeout(timer); -}, 0.1); // 0.1 should be treated the same as 1, not 1000... - -timer = setTimeout(function() { - common.fail('timers fired out of order'); -}, 2); // ...so this timer should fire second. diff --git a/test/parallel/test-timers.js b/test/parallel/test-timers.js index 64a33515b1660c..df2240d2c444af 100644 --- a/test/parallel/test-timers.js +++ b/test/parallel/test-timers.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); const assert = require('assert'); const inputs = [ @@ -18,13 +18,14 @@ const inputs = [ -10, -1, -0.5, + -0.1, -0.0, 0, 0.0, + 0.1, 0.5, 1, 1.0, - 10, 2147483648, // browser behaviour: timeouts > 2^31-1 run on next tick 12345678901234 // ditto ]; @@ -43,10 +44,17 @@ inputs.forEach(function(value, index) { }, value); }); -process.on('exit', function() { - // assert that all timers have run +// All values in inputs array coerce to 1 ms. Therefore, they should all run +// before a timer set here for 2 ms. + +setTimeout(common.mustCall(function() { + // assert that all other timers have run inputs.forEach(function(value, index) { - assert.strictEqual(true, timeouts[index]); - assert.strictEqual(true, intervals[index]); + assert(timeouts[index]); + assert(intervals[index]); }); -}); +}), 2); + +// Test 10 ms timeout separately. +setTimeout(common.mustCall(function() {}), 10); +setInterval(common.mustCall(function() { clearInterval(this); }), 10); From 1fae98b8339d787011d07364530f8db7566281f6 Mon Sep 17 00:00:00 2001 From: Rebecca Turner Date: Thu, 12 Jan 2017 16:58:10 -0800 Subject: [PATCH 243/291] deps: upgrade npm to 4.1.1 PR-URL: https://github.com/nodejs/node/pull/10781 Reviewed-By: Jeremiah Senkpiel --- deps/npm/AUTHORS | 1 + deps/npm/CHANGELOG.md | 220 +++++++++- deps/npm/doc/cli/npm-cache.md | 5 +- deps/npm/doc/cli/npm-doctor.md | 102 +++++ deps/npm/doc/misc/npm-config.md | 17 + deps/npm/doc/misc/npm-index.md | 4 + deps/npm/html/doc/README.html | 2 +- deps/npm/html/doc/cli/npm-access.html | 2 +- deps/npm/html/doc/cli/npm-adduser.html | 2 +- deps/npm/html/doc/cli/npm-bin.html | 2 +- deps/npm/html/doc/cli/npm-bugs.html | 2 +- deps/npm/html/doc/cli/npm-build.html | 2 +- deps/npm/html/doc/cli/npm-bundle.html | 2 +- deps/npm/html/doc/cli/npm-cache.html | 7 +- deps/npm/html/doc/cli/npm-completion.html | 2 +- deps/npm/html/doc/cli/npm-config.html | 2 +- deps/npm/html/doc/cli/npm-dedupe.html | 2 +- deps/npm/html/doc/cli/npm-deprecate.html | 2 +- deps/npm/html/doc/cli/npm-dist-tag.html | 2 +- deps/npm/html/doc/cli/npm-docs.html | 2 +- deps/npm/html/doc/cli/npm-doctor.html | 106 +++++ deps/npm/html/doc/cli/npm-edit.html | 2 +- deps/npm/html/doc/cli/npm-explore.html | 2 +- deps/npm/html/doc/cli/npm-help-search.html | 2 +- deps/npm/html/doc/cli/npm-help.html | 2 +- deps/npm/html/doc/cli/npm-init.html | 2 +- deps/npm/html/doc/cli/npm-install-test.html | 2 +- deps/npm/html/doc/cli/npm-install.html | 2 +- deps/npm/html/doc/cli/npm-link.html | 2 +- deps/npm/html/doc/cli/npm-logout.html | 2 +- deps/npm/html/doc/cli/npm-ls.html | 4 +- deps/npm/html/doc/cli/npm-outdated.html | 2 +- deps/npm/html/doc/cli/npm-owner.html | 2 +- deps/npm/html/doc/cli/npm-pack.html | 2 +- deps/npm/html/doc/cli/npm-ping.html | 2 +- deps/npm/html/doc/cli/npm-prefix.html | 2 +- deps/npm/html/doc/cli/npm-prune.html | 2 +- deps/npm/html/doc/cli/npm-publish.html | 2 +- deps/npm/html/doc/cli/npm-rebuild.html | 2 +- deps/npm/html/doc/cli/npm-repo.html | 2 +- deps/npm/html/doc/cli/npm-restart.html | 2 +- deps/npm/html/doc/cli/npm-root.html | 2 +- deps/npm/html/doc/cli/npm-run-script.html | 2 +- deps/npm/html/doc/cli/npm-search.html | 2 +- deps/npm/html/doc/cli/npm-shrinkwrap.html | 2 +- deps/npm/html/doc/cli/npm-star.html | 2 +- deps/npm/html/doc/cli/npm-stars.html | 2 +- deps/npm/html/doc/cli/npm-start.html | 2 +- deps/npm/html/doc/cli/npm-stop.html | 2 +- deps/npm/html/doc/cli/npm-team.html | 2 +- deps/npm/html/doc/cli/npm-test.html | 2 +- deps/npm/html/doc/cli/npm-uninstall.html | 2 +- deps/npm/html/doc/cli/npm-unpublish.html | 2 +- deps/npm/html/doc/cli/npm-update.html | 2 +- deps/npm/html/doc/cli/npm-version.html | 2 +- deps/npm/html/doc/cli/npm-view.html | 2 +- deps/npm/html/doc/cli/npm-whoami.html | 2 +- deps/npm/html/doc/cli/npm.html | 6 +- deps/npm/html/doc/files/npm-folders.html | 2 +- deps/npm/html/doc/files/npm-global.html | 2 +- deps/npm/html/doc/files/npm-json.html | 2 +- deps/npm/html/doc/files/npmrc.html | 2 +- deps/npm/html/doc/files/package.json.html | 2 +- deps/npm/html/doc/index.html | 4 +- deps/npm/html/doc/misc/npm-coding-style.html | 2 +- deps/npm/html/doc/misc/npm-config.html | 17 +- deps/npm/html/doc/misc/npm-developers.html | 2 +- deps/npm/html/doc/misc/npm-disputes.html | 12 +- deps/npm/html/doc/misc/npm-index.html | 4 +- deps/npm/html/doc/misc/npm-orgs.html | 2 +- deps/npm/html/doc/misc/npm-registry.html | 2 +- deps/npm/html/doc/misc/npm-scope.html | 2 +- deps/npm/html/doc/misc/npm-scripts.html | 2 +- deps/npm/html/doc/misc/removing-npm.html | 2 +- deps/npm/html/doc/misc/semver.html | 2 +- deps/npm/lib/cache/add-named.js | 27 +- deps/npm/lib/config/cmd-list.js | 3 +- deps/npm/lib/config/defaults.js | 4 + deps/npm/lib/doctor.js | 109 +++++ deps/npm/lib/doctor/check-files-permission.js | 55 +++ deps/npm/lib/doctor/check-ping.js | 13 + deps/npm/lib/doctor/checksum-cached-files.js | 62 +++ deps/npm/lib/doctor/get-git-path.js | 13 + .../lib/doctor/get-latest-nodejs-version.js | 26 ++ deps/npm/lib/doctor/get-latest-npm-version.js | 13 + deps/npm/lib/fetch-package-metadata.js | 32 +- deps/npm/lib/install.js | 8 +- deps/npm/lib/install/deps.js | 8 +- deps/npm/lib/install/diff-trees.js | 30 +- deps/npm/lib/install/save.js | 6 +- deps/npm/lib/npm.js | 3 + deps/npm/lib/outdated.js | 7 +- deps/npm/lib/prune.js | 86 ++-- deps/npm/lib/uninstall.js | 3 + deps/npm/lib/utils/ansi-trim.js | 7 + deps/npm/lib/utils/error-handler.js | 5 + deps/npm/lib/utils/metrics-launch.js | 39 ++ deps/npm/lib/utils/metrics.js | 73 +++ .../pick-manifest-from-registry-metadata.js | 26 ++ deps/npm/man/man1/npm-README.1 | 2 +- deps/npm/man/man1/npm-access.1 | 2 +- deps/npm/man/man1/npm-adduser.1 | 2 +- deps/npm/man/man1/npm-bin.1 | 2 +- deps/npm/man/man1/npm-bugs.1 | 2 +- deps/npm/man/man1/npm-build.1 | 2 +- deps/npm/man/man1/npm-bundle.1 | 2 +- deps/npm/man/man1/npm-cache.1 | 7 +- deps/npm/man/man1/npm-completion.1 | 2 +- deps/npm/man/man1/npm-config.1 | 2 +- deps/npm/man/man1/npm-dedupe.1 | 2 +- deps/npm/man/man1/npm-deprecate.1 | 2 +- deps/npm/man/man1/npm-dist-tag.1 | 2 +- deps/npm/man/man1/npm-docs.1 | 2 +- deps/npm/man/man1/npm-doctor.1 | 113 +++++ deps/npm/man/man1/npm-edit.1 | 2 +- deps/npm/man/man1/npm-explore.1 | 2 +- deps/npm/man/man1/npm-help-search.1 | 2 +- deps/npm/man/man1/npm-help.1 | 2 +- deps/npm/man/man1/npm-init.1 | 2 +- deps/npm/man/man1/npm-install-test.1 | 2 +- deps/npm/man/man1/npm-install.1 | 2 +- deps/npm/man/man1/npm-link.1 | 2 +- deps/npm/man/man1/npm-logout.1 | 2 +- deps/npm/man/man1/npm-ls.1 | 4 +- deps/npm/man/man1/npm-outdated.1 | 2 +- deps/npm/man/man1/npm-owner.1 | 2 +- deps/npm/man/man1/npm-pack.1 | 2 +- deps/npm/man/man1/npm-ping.1 | 2 +- deps/npm/man/man1/npm-prefix.1 | 2 +- deps/npm/man/man1/npm-prune.1 | 2 +- deps/npm/man/man1/npm-publish.1 | 2 +- deps/npm/man/man1/npm-rebuild.1 | 2 +- deps/npm/man/man1/npm-repo.1 | 2 +- deps/npm/man/man1/npm-restart.1 | 2 +- deps/npm/man/man1/npm-root.1 | 2 +- deps/npm/man/man1/npm-run-script.1 | 2 +- deps/npm/man/man1/npm-search.1 | 2 +- deps/npm/man/man1/npm-shrinkwrap.1 | 2 +- deps/npm/man/man1/npm-star.1 | 2 +- deps/npm/man/man1/npm-stars.1 | 2 +- deps/npm/man/man1/npm-start.1 | 2 +- deps/npm/man/man1/npm-stop.1 | 2 +- deps/npm/man/man1/npm-team.1 | 2 +- deps/npm/man/man1/npm-test.1 | 2 +- deps/npm/man/man1/npm-uninstall.1 | 2 +- deps/npm/man/man1/npm-unpublish.1 | 2 +- deps/npm/man/man1/npm-update.1 | 2 +- deps/npm/man/man1/npm-version.1 | 2 +- deps/npm/man/man1/npm-view.1 | 2 +- deps/npm/man/man1/npm-whoami.1 | 2 +- deps/npm/man/man1/npm.1 | 4 +- deps/npm/man/man5/npm-folders.5 | 2 +- deps/npm/man/man5/npm-global.5 | 2 +- deps/npm/man/man5/npm-json.5 | 2 +- deps/npm/man/man5/npmrc.5 | 2 +- deps/npm/man/man5/package.json.5 | 2 +- deps/npm/man/man7/npm-coding-style.7 | 2 +- deps/npm/man/man7/npm-config.7 | 25 +- deps/npm/man/man7/npm-developers.7 | 2 +- deps/npm/man/man7/npm-disputes.7 | 2 +- deps/npm/man/man7/npm-index.7 | 5 +- deps/npm/man/man7/npm-orgs.7 | 2 +- deps/npm/man/man7/npm-registry.7 | 2 +- deps/npm/man/man7/npm-scope.7 | 2 +- deps/npm/man/man7/npm-scripts.7 | 2 +- deps/npm/man/man7/removing-npm.7 | 2 +- deps/npm/man/man7/semver.7 | 2 +- deps/npm/node_modules/lockfile/CHANGELOG.md | 5 + deps/npm/node_modules/lockfile/lockfile.js | 2 +- deps/npm/node_modules/lockfile/package.json | 46 +- .../lockfile/test/unlock-no-cb.js | 10 + .../node-gyp/node_modules/nopt/.npmignore | 1 + .../node-gyp/node_modules/nopt/.travis.yml | 9 + .../node_modules/nopt}/LICENSE | 0 .../node-gyp/node_modules/nopt/README.md | 211 +++++++++ .../node-gyp/node_modules/nopt/bin/nopt.js | 54 +++ .../node_modules/nopt/examples/my-program.js | 30 ++ .../node-gyp/node_modules/nopt/lib/nopt.js | 415 ++++++++++++++++++ .../node-gyp/node_modules/nopt/package.json | 96 ++++ .../node-gyp/node_modules/nopt/test/basic.js | 273 ++++++++++++ deps/npm/node_modules/nopt/.travis.yml | 7 +- deps/npm/node_modules/nopt/CHANGELOG.md | 58 +++ deps/npm/node_modules/nopt/README.md | 54 +-- deps/npm/node_modules/nopt/lib/nopt.js | 79 ++-- .../nopt/node_modules/osenv/.npmignore | 13 + .../nopt/node_modules/osenv/.travis.yml | 9 + .../node_modules/osenv}/LICENSE | 9 +- .../nopt/node_modules/osenv/README.md | 63 +++ .../osenv/node_modules/os-homedir/index.js | 24 + .../osenv/node_modules/os-homedir}/license | 0 .../node_modules/os-homedir/package.json | 109 +++++ .../osenv/node_modules/os-homedir/readme.md | 31 ++ .../osenv/node_modules/os-tmpdir/index.js | 25 ++ .../osenv/node_modules/os-tmpdir}/license | 0 .../osenv/node_modules/os-tmpdir/package.json | 109 +++++ .../osenv/node_modules/os-tmpdir/readme.md | 32 ++ .../nopt/node_modules/osenv/osenv.js | 72 +++ .../nopt/node_modules/osenv/package.json | 113 +++++ .../nopt/node_modules/osenv/test/unix.js | 71 +++ .../nopt/node_modules/osenv/test/windows.js | 74 ++++ .../nopt/node_modules/osenv/x.tap | 39 ++ deps/npm/node_modules/nopt/package.json | 69 +-- deps/npm/node_modules/nopt/test/basic.js | 44 +- .../npm-registry-client/.travis.yml | 4 +- .../npm-registry-client/README.md | 16 +- .../node_modules/npm-registry-client/index.js | 6 +- .../npm-registry-client/lib/adduser.js | 3 +- .../npm-registry-client/lib/fetch.js | 11 +- .../npm-registry-client/lib/request.js | 36 +- .../lib/send-anonymous-CLI-metrics.js | 19 + .../node_modules/npmlog/CHANGELOG.md | 36 -- .../node_modules/npmlog/README.md | 210 --------- .../node_modules/npmlog/log.js | 298 ------------- .../node_modules/are-we-there-yet/.npmignore | 5 - .../node_modules/are-we-there-yet/CHANGES.md | 19 - .../node_modules/are-we-there-yet/LICENSE | 5 - .../node_modules/are-we-there-yet/README.md | 194 -------- .../node_modules/are-we-there-yet/index.js | 4 - .../node_modules/delegates/.npmignore | 1 - .../node_modules/delegates/History.md | 22 - .../node_modules/delegates/License | 20 - .../node_modules/delegates/Makefile | 8 - .../node_modules/delegates/Readme.md | 94 ---- .../node_modules/delegates/index.js | 121 ----- .../node_modules/delegates/package.json | 96 ---- .../node_modules/delegates/test/index.js | 94 ---- .../are-we-there-yet/package.json | 102 ----- .../are-we-there-yet/test/lib/test-event.js | 29 -- .../are-we-there-yet/test/tracker.js | 57 --- .../are-we-there-yet/test/trackergroup.js | 96 ---- .../are-we-there-yet/test/trackerstream.js | 51 --- .../are-we-there-yet/tracker-base.js | 11 - .../are-we-there-yet/tracker-group.js | 107 ----- .../are-we-there-yet/tracker-stream.js | 35 -- .../node_modules/are-we-there-yet/tracker.js | 30 -- .../console-control-strings/LICENSE | 13 - .../console-control-strings/README.md | 145 ------ .../console-control-strings/index.js | 125 ------ .../console-control-strings/package.json | 108 ----- .../npmlog/node_modules/gauge/CHANGELOG.md | 131 ------ .../npmlog/node_modules/gauge/LICENSE | 13 - .../npmlog/node_modules/gauge/README.md | 395 ----------------- .../npmlog/node_modules/gauge/base-theme.js | 14 - .../npmlog/node_modules/gauge/error.js | 24 - .../npmlog/node_modules/gauge/has-color.js | 12 - .../npmlog/node_modules/gauge/index.js | 226 ---------- .../gauge/node_modules/has-color/package.json | 117 ----- .../gauge/node_modules/has-color/readme.md | 30 -- .../gauge/node_modules/object-assign/index.js | 83 ---- .../node_modules/object-assign/package.json | 126 ------ .../node_modules/object-assign/readme.md | 56 --- .../node_modules/signal-exit/CHANGELOG.md | 27 -- .../node_modules/signal-exit/LICENSE.txt | 16 - .../gauge/node_modules/signal-exit/README.md | 40 -- .../gauge/node_modules/signal-exit/index.js | 148 ------- .../node_modules/signal-exit/package.json | 118 ----- .../gauge/node_modules/signal-exit/signals.js | 53 --- .../gauge/node_modules/string-width/index.js | 37 -- .../node_modules/code-point-at/index.js | 33 -- .../node_modules/code-point-at/license | 21 - .../node_modules/number-is-nan/index.js | 4 - .../node_modules/number-is-nan/license | 21 - .../node_modules/number-is-nan/package.json | 103 ----- .../node_modules/number-is-nan/readme.md | 28 -- .../node_modules/code-point-at/package.json | 107 ----- .../node_modules/code-point-at/readme.md | 32 -- .../is-fullwidth-code-point/index.js | 46 -- .../is-fullwidth-code-point/license | 21 - .../node_modules/number-is-nan/index.js | 4 - .../node_modules/number-is-nan/license | 21 - .../node_modules/number-is-nan/package.json | 115 ----- .../node_modules/number-is-nan/readme.md | 28 -- .../is-fullwidth-code-point/package.json | 120 ----- .../is-fullwidth-code-point/readme.md | 39 -- .../node_modules/string-width/package.json | 136 ------ .../gauge/node_modules/string-width/readme.md | 42 -- .../gauge/node_modules/wide-align/.npmignore | 5 - .../gauge/node_modules/wide-align/README.md | 47 -- .../gauge/node_modules/wide-align/align.js | 65 --- .../node_modules/wide-align/package.json | 105 ----- .../node_modules/wide-align/test/align.js | 37 -- .../npmlog/node_modules/gauge/package.json | 140 ------ .../npmlog/node_modules/gauge/plumbing.js | 47 -- .../npmlog/node_modules/gauge/process.js | 3 - .../npmlog/node_modules/gauge/progress-bar.js | 35 -- .../node_modules/gauge/render-template.js | 181 -------- .../node_modules/gauge/set-immediate.js | 7 - .../npmlog/node_modules/gauge/set-interval.js | 3 - .../npmlog/node_modules/gauge/spin.js | 5 - .../node_modules/gauge/template-item.js | 73 --- .../npmlog/node_modules/gauge/theme-set.js | 115 ----- .../npmlog/node_modules/gauge/themes.js | 54 --- .../node_modules/gauge/wide-truncate.js | 25 -- .../node_modules/set-blocking/CHANGELOG.md | 26 -- .../node_modules/set-blocking/LICENSE.txt | 14 - .../node_modules/set-blocking/README.md | 31 -- .../npmlog/node_modules/set-blocking/index.js | 7 - .../node_modules/set-blocking/package.json | 118 ----- .../node_modules/npmlog/package.json | 113 ----- .../npm-registry-client/package.json | 55 ++- .../npm-registry-client/test/econnreset.js | 95 ++++ .../npm-registry-client/test/lib/server.js | 1 - .../test/send-anon-metrics.js | 78 ++++ deps/npm/node_modules/npmlog/README.md | 8 +- .../npmlog/node_modules/gauge/CHANGELOG.md | 4 + .../gauge/node_modules/has-color/index.js | 32 -- .../gauge/node_modules/has-color/package.json | 97 ---- .../gauge/node_modules/has-color/readme.md | 30 -- .../gauge/node_modules/signal-exit/index.js | 9 + .../node_modules/signal-exit/package.json | 44 +- .../gauge/node_modules/supports-color/cli.js | 28 ++ .../node_modules/supports-color}/index.js | 0 .../node_modules/supports-color/package.json | 112 +++++ .../node_modules/supports-color/readme.md | 44 ++ .../npmlog/node_modules/gauge/package.json | 26 +- deps/npm/node_modules/npmlog/package.json | 47 +- .../node_modules/os-homedir/package.json | 102 ++++- .../osenv/node_modules/os-homedir/readme.md | 10 +- .../osenv/node_modules/os-tmpdir/index.js | 2 +- .../osenv/node_modules/os-tmpdir/package.json | 98 ++++- .../osenv/node_modules/os-tmpdir/readme.md | 14 +- deps/npm/node_modules/osenv/package.json | 119 +++-- deps/npm/node_modules/osenv/test/unix.js | 10 +- deps/npm/node_modules/retry/package.json | 43 +- .../node_modules => }/uuid/.npmignore | 0 .../node_modules => }/uuid/.travis.yml | 0 .../{request/node_modules => }/uuid/AUTHORS | 0 .../node_modules => }/uuid/HISTORY.md | 0 .../node_modules => }/uuid/LICENSE.md | 0 .../{request/node_modules => }/uuid/README.md | 0 .../{request/node_modules => }/uuid/bin/uuid | 0 .../{request/node_modules => }/uuid/index.js | 0 .../node_modules => }/uuid/lib/bytesToUuid.js | 0 .../node_modules => }/uuid/lib/rng-browser.js | 0 .../node_modules => }/uuid/lib/rng.js | 0 .../node_modules => }/uuid/package.json | 28 +- .../node_modules => }/uuid/test/mocha.opts | 0 .../node_modules => }/uuid/test/test.js | 0 .../{request/node_modules => }/uuid/v1.js | 0 .../{request/node_modules => }/uuid/v4.js | 0 deps/npm/package.json | 20 +- deps/npm/test/tap/anon-cli-metrics.js | 147 +++++++ deps/npm/test/tap/doctor.js | 69 +++ deps/npm/test/tap/install-save-local.js | 69 +++ .../pick-manifest-from-registry-metadata.js | 145 ++++++ deps/npm/test/tap/prune.js | 2 +- .../splat-with-only-prerelease-to-latest.js | 12 +- 347 files changed, 4716 insertions(+), 6785 deletions(-) create mode 100644 deps/npm/doc/cli/npm-doctor.md create mode 100644 deps/npm/html/doc/cli/npm-doctor.html create mode 100644 deps/npm/lib/doctor.js create mode 100644 deps/npm/lib/doctor/check-files-permission.js create mode 100644 deps/npm/lib/doctor/check-ping.js create mode 100644 deps/npm/lib/doctor/checksum-cached-files.js create mode 100644 deps/npm/lib/doctor/get-git-path.js create mode 100644 deps/npm/lib/doctor/get-latest-nodejs-version.js create mode 100644 deps/npm/lib/doctor/get-latest-npm-version.js create mode 100644 deps/npm/lib/utils/ansi-trim.js create mode 100644 deps/npm/lib/utils/metrics-launch.js create mode 100644 deps/npm/lib/utils/metrics.js create mode 100644 deps/npm/lib/utils/pick-manifest-from-registry-metadata.js create mode 100644 deps/npm/man/man1/npm-doctor.1 create mode 100644 deps/npm/node_modules/lockfile/test/unlock-no-cb.js create mode 100644 deps/npm/node_modules/node-gyp/node_modules/nopt/.npmignore create mode 100644 deps/npm/node_modules/node-gyp/node_modules/nopt/.travis.yml rename deps/npm/node_modules/{npm-registry-client/node_modules/npmlog => node-gyp/node_modules/nopt}/LICENSE (100%) create mode 100644 deps/npm/node_modules/node-gyp/node_modules/nopt/README.md create mode 100755 deps/npm/node_modules/node-gyp/node_modules/nopt/bin/nopt.js create mode 100755 deps/npm/node_modules/node-gyp/node_modules/nopt/examples/my-program.js create mode 100644 deps/npm/node_modules/node-gyp/node_modules/nopt/lib/nopt.js create mode 100644 deps/npm/node_modules/node-gyp/node_modules/nopt/package.json create mode 100644 deps/npm/node_modules/node-gyp/node_modules/nopt/test/basic.js create mode 100644 deps/npm/node_modules/nopt/CHANGELOG.md create mode 100644 deps/npm/node_modules/nopt/node_modules/osenv/.npmignore create mode 100644 deps/npm/node_modules/nopt/node_modules/osenv/.travis.yml rename deps/npm/node_modules/{npm-registry-client/node_modules/npmlog/node_modules/gauge/node_modules/wide-align => nopt/node_modules/osenv}/LICENSE (82%) create mode 100644 deps/npm/node_modules/nopt/node_modules/osenv/README.md create mode 100644 deps/npm/node_modules/nopt/node_modules/osenv/node_modules/os-homedir/index.js rename deps/npm/node_modules/{npm-registry-client/node_modules/npmlog/node_modules/gauge/node_modules/object-assign => nopt/node_modules/osenv/node_modules/os-homedir}/license (100%) create mode 100644 deps/npm/node_modules/nopt/node_modules/osenv/node_modules/os-homedir/package.json create mode 100644 deps/npm/node_modules/nopt/node_modules/osenv/node_modules/os-homedir/readme.md create mode 100644 deps/npm/node_modules/nopt/node_modules/osenv/node_modules/os-tmpdir/index.js rename deps/npm/node_modules/{npm-registry-client/node_modules/npmlog/node_modules/gauge/node_modules/string-width => nopt/node_modules/osenv/node_modules/os-tmpdir}/license (100%) create mode 100644 deps/npm/node_modules/nopt/node_modules/osenv/node_modules/os-tmpdir/package.json create mode 100644 deps/npm/node_modules/nopt/node_modules/osenv/node_modules/os-tmpdir/readme.md create mode 100644 deps/npm/node_modules/nopt/node_modules/osenv/osenv.js create mode 100644 deps/npm/node_modules/nopt/node_modules/osenv/package.json create mode 100644 deps/npm/node_modules/nopt/node_modules/osenv/test/unix.js create mode 100644 deps/npm/node_modules/nopt/node_modules/osenv/test/windows.js create mode 100644 deps/npm/node_modules/nopt/node_modules/osenv/x.tap create mode 100644 deps/npm/node_modules/npm-registry-client/lib/send-anonymous-CLI-metrics.js delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/CHANGELOG.md delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/README.md delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/log.js delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/are-we-there-yet/.npmignore delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/are-we-there-yet/CHANGES.md delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/are-we-there-yet/LICENSE delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/are-we-there-yet/README.md delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/are-we-there-yet/index.js delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/delegates/.npmignore delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/delegates/History.md delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/delegates/License delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/delegates/Makefile delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/delegates/Readme.md delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/delegates/index.js delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/delegates/package.json delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/delegates/test/index.js delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/are-we-there-yet/package.json delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/are-we-there-yet/test/lib/test-event.js delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/are-we-there-yet/test/tracker.js delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/are-we-there-yet/test/trackergroup.js delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/are-we-there-yet/test/trackerstream.js delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/are-we-there-yet/tracker-base.js delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/are-we-there-yet/tracker-group.js delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/are-we-there-yet/tracker-stream.js delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/are-we-there-yet/tracker.js delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/console-control-strings/LICENSE delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/console-control-strings/README.md delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/console-control-strings/index.js delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/console-control-strings/package.json delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/gauge/CHANGELOG.md delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/gauge/LICENSE delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/gauge/README.md delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/gauge/base-theme.js delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/gauge/error.js delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/gauge/has-color.js delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/gauge/index.js delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/gauge/node_modules/has-color/package.json delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/gauge/node_modules/has-color/readme.md delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/gauge/node_modules/object-assign/index.js delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/gauge/node_modules/object-assign/package.json delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/gauge/node_modules/object-assign/readme.md delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/gauge/node_modules/signal-exit/CHANGELOG.md delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/gauge/node_modules/signal-exit/LICENSE.txt delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/gauge/node_modules/signal-exit/README.md delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/gauge/node_modules/signal-exit/index.js delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/gauge/node_modules/signal-exit/package.json delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/gauge/node_modules/signal-exit/signals.js delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/gauge/node_modules/string-width/index.js delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/gauge/node_modules/string-width/node_modules/code-point-at/index.js delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/gauge/node_modules/string-width/node_modules/code-point-at/license delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/gauge/node_modules/string-width/node_modules/code-point-at/node_modules/number-is-nan/index.js delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/gauge/node_modules/string-width/node_modules/code-point-at/node_modules/number-is-nan/license delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/gauge/node_modules/string-width/node_modules/code-point-at/node_modules/number-is-nan/package.json delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/gauge/node_modules/string-width/node_modules/code-point-at/node_modules/number-is-nan/readme.md delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/gauge/node_modules/string-width/node_modules/code-point-at/package.json delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/gauge/node_modules/string-width/node_modules/code-point-at/readme.md delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/gauge/node_modules/string-width/node_modules/is-fullwidth-code-point/index.js delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/gauge/node_modules/string-width/node_modules/is-fullwidth-code-point/license delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/gauge/node_modules/string-width/node_modules/is-fullwidth-code-point/node_modules/number-is-nan/index.js delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/gauge/node_modules/string-width/node_modules/is-fullwidth-code-point/node_modules/number-is-nan/license delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/gauge/node_modules/string-width/node_modules/is-fullwidth-code-point/node_modules/number-is-nan/package.json delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/gauge/node_modules/string-width/node_modules/is-fullwidth-code-point/node_modules/number-is-nan/readme.md delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/gauge/node_modules/string-width/node_modules/is-fullwidth-code-point/package.json delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/gauge/node_modules/string-width/node_modules/is-fullwidth-code-point/readme.md delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/gauge/node_modules/string-width/package.json delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/gauge/node_modules/string-width/readme.md delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/gauge/node_modules/wide-align/.npmignore delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/gauge/node_modules/wide-align/README.md delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/gauge/node_modules/wide-align/align.js delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/gauge/node_modules/wide-align/package.json delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/gauge/node_modules/wide-align/test/align.js delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/gauge/package.json delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/gauge/plumbing.js delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/gauge/process.js delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/gauge/progress-bar.js delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/gauge/render-template.js delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/gauge/set-immediate.js delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/gauge/set-interval.js delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/gauge/spin.js delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/gauge/template-item.js delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/gauge/theme-set.js delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/gauge/themes.js delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/gauge/wide-truncate.js delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/set-blocking/CHANGELOG.md delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/set-blocking/LICENSE.txt delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/set-blocking/README.md delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/set-blocking/index.js delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/node_modules/set-blocking/package.json delete mode 100644 deps/npm/node_modules/npm-registry-client/node_modules/npmlog/package.json create mode 100644 deps/npm/node_modules/npm-registry-client/test/econnreset.js create mode 100644 deps/npm/node_modules/npm-registry-client/test/send-anon-metrics.js delete mode 100644 deps/npm/node_modules/npmlog/node_modules/gauge/node_modules/has-color/index.js delete mode 100644 deps/npm/node_modules/npmlog/node_modules/gauge/node_modules/has-color/package.json delete mode 100644 deps/npm/node_modules/npmlog/node_modules/gauge/node_modules/has-color/readme.md create mode 100755 deps/npm/node_modules/npmlog/node_modules/gauge/node_modules/supports-color/cli.js rename deps/npm/node_modules/{npm-registry-client/node_modules/npmlog/node_modules/gauge/node_modules/has-color => npmlog/node_modules/gauge/node_modules/supports-color}/index.js (100%) create mode 100644 deps/npm/node_modules/npmlog/node_modules/gauge/node_modules/supports-color/package.json create mode 100644 deps/npm/node_modules/npmlog/node_modules/gauge/node_modules/supports-color/readme.md rename deps/npm/node_modules/{request/node_modules => }/uuid/.npmignore (100%) rename deps/npm/node_modules/{request/node_modules => }/uuid/.travis.yml (100%) rename deps/npm/node_modules/{request/node_modules => }/uuid/AUTHORS (100%) rename deps/npm/node_modules/{request/node_modules => }/uuid/HISTORY.md (100%) rename deps/npm/node_modules/{request/node_modules => }/uuid/LICENSE.md (100%) rename deps/npm/node_modules/{request/node_modules => }/uuid/README.md (100%) rename deps/npm/node_modules/{request/node_modules => }/uuid/bin/uuid (100%) rename deps/npm/node_modules/{request/node_modules => }/uuid/index.js (100%) rename deps/npm/node_modules/{request/node_modules => }/uuid/lib/bytesToUuid.js (100%) rename deps/npm/node_modules/{request/node_modules => }/uuid/lib/rng-browser.js (100%) rename deps/npm/node_modules/{request/node_modules => }/uuid/lib/rng.js (100%) rename deps/npm/node_modules/{request/node_modules => }/uuid/package.json (84%) rename deps/npm/node_modules/{request/node_modules => }/uuid/test/mocha.opts (100%) rename deps/npm/node_modules/{request/node_modules => }/uuid/test/test.js (100%) rename deps/npm/node_modules/{request/node_modules => }/uuid/v1.js (100%) rename deps/npm/node_modules/{request/node_modules => }/uuid/v4.js (100%) create mode 100644 deps/npm/test/tap/anon-cli-metrics.js create mode 100644 deps/npm/test/tap/doctor.js create mode 100644 deps/npm/test/tap/pick-manifest-from-registry-metadata.js diff --git a/deps/npm/AUTHORS b/deps/npm/AUTHORS index 96d8ecf66c4b2c..c91ce4a2c615b8 100644 --- a/deps/npm/AUTHORS +++ b/deps/npm/AUTHORS @@ -445,3 +445,4 @@ Alex Jordan Ville Lahdenvuo Natalie Wolfe Andrew Schmadel +Jonah Moses diff --git a/deps/npm/CHANGELOG.md b/deps/npm/CHANGELOG.md index fe673ef39c098e..5ba932dc6aff56 100644 --- a/deps/npm/CHANGELOG.md +++ b/deps/npm/CHANGELOG.md @@ -1,3 +1,216 @@ +### v4.1.1 (2016-12-16) + +This fixes a bug in the metrics reporting where, if you had enabled it then +installs would create a metrics reporting process, that would create a +metrics reporting process, that would… well, you get the idea. The only +way to actually kill these processes is to turn off your networking, then +on MacOS/Linux kill them with `kill -9`. Alternatively you can just reboot. + +Anyway, this is a quick release to fix that bug: + +* [`51c393f`](https://github.com/npm/npm/commit/51c393feff5f4908c8a9fb02baef505b1f2259be) + [#15237](https://github.com/npm/npm/pull/15237) + Don't launch a metrics sender process if we're runnning from a metrics + sender process. + ([@iarna](https://github.com/iarna)) + +### v4.1.0 (2016-12-15) + +I'm really excited about `npm@4.1.0`. I know, I know, I'm kinda overexcited +in my changelogs, but this one is GREAT. We've got a WHOLE NEW subcommand, I +mean, when was the last time you saw that? YEARS! And we have the beginnings +of usage metrics reporting. Then there's a fix for a really subtle bug that +resulted in `shasum` errors. And then we also have a few more bug fixes and +other improvements. + +#### ANONYMOUS METRIC REPORTING + +We're adding the ability for you all to help us track the quality of your +experiences using `npm`. Metrics will be sent if you run: + +``` +npm config set send-metrics true +``` + +Then `npm` will report to `registry.npmjs.org` the number of successful and +failed installations you've had. The data contains no identifying +information and npm will not attempt to correlate things like IP address +with the metrics being submitted. + +Currently we only track number of successful and failed installations. In +the future we would like to find additional metrics to help us better +quantify the quality of the `npm` experience. + +* [`190a658`](https://github.com/npm/npm/commit/190a658c4222f6aa904cbc640fc394a5c875e4db) + [#15084](https://github.com/npm/npm/pull/15084) + Add facility for recording and reporting success metrics. + ([@iarna](https://github.com/iarna)) +* [`87afc8b`](https://github.com/npm/npm/commit/87afc8b466f553fb49746c932c259173de48d0a4) + [npm/npm-registry-client#147](https://github.com/npm/npm-registry-client/pull/148) + `npm-registry-client@7.4.5`: + Add support for sending anonymous CLI metrics. + ([@iarna](https://github.com/iarna), + [@sisidovski](https://github.com/sisidovski)) + +### NPM DOCTOR + +
+Check                               Value                        Recommendation
+npm ping                            ok
+npm -v                              v4.0.5
+node -v                             v4.6.1                       Use node v6.9.2
+npm config get registry             https://registry.npmjs.org/
+which git                           /Users/rebecca/bin/git
+Perms check on cached files         ok
+Perms check on global node_modules  ok
+Perms check on local node_modules   ok
+Checksum cached files               ok
+
+ +It's a rare day that we add a new command to `npm`, so I'm excited to +present to you `npm doctor`. It checks for a number of common problems and +provides some recommended solutions. It was put together through the hard +work of [@watilde](https://github.com/watilde). + +* [`2359505`](https://github.com/npm/npm/commit/23595055669f76c9fe8f5f1cf4a705c2e794f0dc) + [`0209ee5`](https://github.com/npm/npm/commit/0209ee50448441695fbf9699019d34178b69ba73) + [#14582](https://github.com/npm/npm/pull/14582) + Add new `npm doctor` to give your project environment a health check. + ([@watilde](https://github.com/watilde)) + +#### FIX MAJOR SOURCE OF SHASUM ERRORS + +If you've been getting intermittent shasum errors then you'll be pleased to +know that we've tracked down at least one source of them, if not THE source +of them. + +* [`87afc8b`](https://github.com/npm/npm/commit/87afc8b466f553fb49746c932c259173de48d0a4) + [#14626](https://github.com/npm/npm/issues/14626) + [npm/npm-registry-client#148](https://github.com/npm/npm-registry-client/pull/148) + `npm-registry-client@7.4.5`: + Fix a bug where an `ECONNRESET` while fetching a package file would result + in a partial download that would be reported as a "shasum mismatch". It + now throws away the partial download and retries it. + ([@iarna](https://github.com/iarna)) + +#### FILE URLS AND NODE.JS 7 + +When `npm` was formatting `file` URLs we took advantage of `url.format` to +construct them. Node.js 7 changed the behavior in such a way that our use of +`url.format` stopped producing URLs that we could make use of. + +The reasons for this have to do with the `file` URL specification and how +invalid (according to the specification) URLs are handled. How this changed +is most easily explained with a table: + + + + + + + +
URLNode.js <= 6npm's understandingNode.js 7npm's understanding
VALIDfile:///abc/deffile:///abc/def/abc/deffile:///abc/def/abc/def
invalidfile:/abc/deffile:/abc/def/abc/deffile:///abc/def/abc/def
invalidfile:abc/deffile:abc/def$CWD/abc/deffile://abc/def/def on the abc host
invalidfile:../abc/deffile:../abc/def$CWD/../abc/deffile://../abc/def/abc/def on the .. host
+ +So the result was that passing a `file` URL that npm had received that used +through Node.js 7's `url.format` changed its meaning as far as `npm` was +concerned. As those kinds of URLs are, per the specification, invalid, how +they should be handled is undefined and so the change in Node.js wasn't a +bug per se. + +Our solution is to stop using `url.format` when constructing this kind of +URL. + +* [`173935b`](https://github.com/npm/npm/commit/173935b4298e09c4fdcb8f3a44b06134d5aff181) + [#15114](https://github.com/npm/npm/issues/15114) + Stop using `url.format` for relative local dep paths. + ([@zkat](https://github.com/zkat)) + +#### EXTRANEOUS LIFECYCLE SCRIPT EXECUTION WHEN REMOVING + +* [`afb1dfd`](https://github.com/npm/npm/commit/afb1dfd944e57add25a05770c0d52d983dc4e96c) + [#15090](https://github.com/npm/npm/pull/15090) + Skip top level lifecycles when uninstalling. + ([@iarna](https://github.com/iarna)) + +#### REFACTORING AND INTERNALS + +* [`c9b279a`](https://github.com/npm/npm/commit/c9b279aca0fcb8d0e483e534c7f9a7250e2a9392) + [#15205](https://github.com/npm/npm/pull/15205) + [#15196](https://github.com/npm/npm/pull/15196) + Only have one function that determines which version of a package to use + given a specifier and a list of versions. + ([@iarna](https://github.com/iarna), + [@zkat](https://github.com/zkat)) + +* [`981ce63`](https://github.com/npm/npm/commit/981ce6395e7892dde2591b44e484e191f8625431) + [#15090](https://github.com/npm/npm/pull/15090) + Rewrite prune to use modern npm plumbing. + ([@iarna](https://github.com/iarna)) + +* [`bc4b739`](https://github.com/npm/npm/commit/bc4b73911f58a11b4a2d28b49e24b4dd7365f95b) + [#15089](https://github.com/npm/npm/pull/15089) + Rename functions and variables in the module that computes what changes to + make to your installation. + ([@iarna](https://github.com/iarna)) + +* [`2449f74`](https://github.com/npm/npm/commit/2449f74a202b3efdb1b2f5a83356a78ea9ecbe35) + [#15089](https://github.com/npm/npm/pull/15089) + When computing changes to make to your installation, use a function to add + new actions to take instead of just pushing on a list. + ([@iarna](https://github.com/iarna)) + +#### IMPROVED LOGGING + +* [`335933a`](https://github.com/npm/npm/commit/335933a05396258eead139d27eea3f7668ccdfab) + [#15089](https://github.com/npm/npm/pull/15089) + Log when we remove obsolete dependencies in the tree. + ([@iarna](https://github.com/iarna)) + +#### DOCUMENTATION + +* [`33ca4e6`](https://github.com/npm/npm/commit/33ca4e6db3c1878cbc40d5e862ab49bb0e82cfb2) + [#15157](https://github.com/npm/npm/pull/15157) + Update `npm cache` docs to use more consistent language + ([@JonahMoses](https://github.com/JonahMoses)) + +#### DEPENDENCY UPDATES + +* [`c2d22fa`](https://github.com/npm/npm/commit/c2d22faf916e8260136a1cc95913ca474421c0d3) + [#15215](https://github.com/npm/npm/pull/15215) + `nopt@4.0.1`: + The breaking change is a small tweak to how empty string values are + handled. See the brand-new + [CHANGELOG.md for nopt](https://github.com/npm/nopt/blob/v4.0.1/CHANGELOG.md) for further + details about what's changed in this release! + ([@adius](https://github.com/adius), + [@samjonester](https://github.com/samjonester), + [@elidoran](https://github.com/elidoran), + [@helio](https://github.com/helio), + [@silkentrance](https://github.com/silkentrance), + [@othiym23](https://github.com/othiym23)) +* [`54d949b`](https://github.com/npm/npm/commit/54d949b05adefffeb7b5b10229c5fe0ccb929ac3) + [npm/lockfile#24](https://github.com/npm/lockfile/pull/24) + `lockfile@1.0.3`: + Handled case where callback was not passed in by the user. + ([@ORESoftware](https://github.com/ORESoftware)) +* [`54acc03`](https://github.com/npm/npm/commit/54acc0389b39850c0725d0868cb5e61317b57503) + `npmlog@4.0.2`: + Documentation update. + ([@helio-frota](https://github.com/helio-frota)) +* [`57f4bc1`](https://github.com/npm/npm/commit/57f4bc1150322294c1ea0a287ad0a8e457c151e6) + `osenv@0.1.4`: + Test changes. + ([@isaacs](https://github.com/isaacs)) +* [`bea1a2d`](https://github.com/npm/npm/commit/bea1a2d0db566560e13ecc1d5f42e55811269c88) + `retry@0.10.1`: + No changes. + ([@tim-kos](https://github.com/tim-kos)) +* [`6749e39`](https://github.com/npm/npm/commit/6749e395f868109afd97f79d36507e6567dd48fb) + [kapouer/marked-man#9](https://github.com/kapouer/marked-man/pull/9) + `marked-man@0.2.0`: + Add table support. + ([@gholk](https://github.com/gholk)) + ### v4.0.5 (2016-12-01) It's that time of year! December is upon us, which means y'all are just going to @@ -49,13 +262,13 @@ On to the actual changes! `EPERM` errors are Windows are now handled more gracefully. Windows users that tended to see these errors due to, say, an antivirus-induced race condition, should see them much more rarely, if at all. - ([@Kat Marchán](https://github.com/Kat Marchán)) + ([@zkatr](https://github.com/zkat)) * [`85b0174`](https://github.com/npm/npm/commit/85b0174ba9842e8e89f3c33d009e4b4a9e877c7d) `request@2.79.0` - ([@Kat Marchán](https://github.com/Kat Marchán)) + ([@zkat](https://github.com/zkat)) * [`9664d36`](https://github.com/npm/npm/commit/9664d36653503247737630440bc2ff657de965c3) `tap@8.0.1` - ([@Kat Marchán](https://github.com/Kat Marchán)) + ([@zkat](https://github.com/zkat)) #### MISCELLANEOUS @@ -596,6 +809,7 @@ sending `Npm-Scope` and `Npm-In-CI` headers in outgoing requests. * [`846f61c`](https://github.com/npm/npm/commit/846f61c1dd4a033f77aa736ab01c27ae6724fe1c) [npm/npm-registry-client#145](https://github.com/npm/npm-registry-client/pull/145) + [npm/npm-registry-client#147](https://github.com/npm/npm-registry-client/pull/147) `npm-registry-client@7.3.0`: * Allow npm to add headers to outgoing requests. * Add `Npm-In-CI` header that reports whether we're running in CI. diff --git a/deps/npm/doc/cli/npm-cache.md b/deps/npm/doc/cli/npm-cache.md index 03b5902bd4c00f..ea8cb1b9917759 100644 --- a/deps/npm/doc/cli/npm-cache.md +++ b/deps/npm/doc/cli/npm-cache.md @@ -11,10 +11,11 @@ npm-cache(1) -- Manipulates packages cache npm cache ls [] npm cache clean [] + aliases: npm cache clear, npm cache rm ## DESCRIPTION -Used to add, list, or clear the npm cache folder. +Used to add, list, or clean the npm cache folder. * add: Add the specified package to the local cache. This command is primarily @@ -29,7 +30,7 @@ Used to add, list, or clear the npm cache folder. * clean: Delete data out of the cache folder. If an argument is provided, then it specifies a subpath to delete. If no argument is provided, then - the entire cache is cleared. + the entire cache is deleted. ## DETAILS diff --git a/deps/npm/doc/cli/npm-doctor.md b/deps/npm/doc/cli/npm-doctor.md new file mode 100644 index 00000000000000..1a5738505cefee --- /dev/null +++ b/deps/npm/doc/cli/npm-doctor.md @@ -0,0 +1,102 @@ +npm-doctor(1) -- Check your environments +======================================================== + +## SYNOPSIS + + npm doctor + +## DESCRIPTION + +`npm doctor` runs a set of checks to ensure that your npm installation has +what it needs to manage your JavaScript packages. npm is mostly a standalone tool, but it does +have some basic requirements that must be met: + ++ Node.js and git must be executable by npm. ++ The primary npm registry, `registry.npmjs.com`, or another service that uses + the registry API, is available. ++ The directories that npm uses, `node_modules` (both locally and globally), + exist and can be written by the current user. ++ The npm cache exists, and the package tarballs within it aren't corrupt. + +Without all of these working properly, npm may not work properly. Many issues +are often attributable to things that are outside npm's code base, so `npm +doctor` confirms that the npm installation is in a good state. + +Also, in addition to this, there are also very many issue reports due to using +old versions of npm. Since npm is constantly improving, running `npm@latest` is +better than an old version. + +`npm doctor` verifies the following items in your environment, and if there are +any recommended changes, it will display them. + +### `npm ping` + +By default, npm installs from the primary npm registry, `registry.npmjs.org`. +`npm doctor` hits a special ping endpoint within the registry. This can also be +checked with `npm ping`. If this check fails, you may be using a proxy that +needs to be configured, or may need to talk to your IT staff to get access over +HTTPS to `registry.npmjs.org`. + +This check is done against whichever registry you've configured (you can see +what that is by running `npm config get registry`), and if you're using a +private registry that doesn't support the `/whoami` endpoint supported by the +primary registry, this check may fail. + +### `npm -v` + +While Node.js may come bundled with a particular version of npm, it's the +policy of the CLI team that we recommend all users run `npm@latest` if they +can. As the CLI is maintained by a small team of contributors, there are only +resources for a single line of development, so npm's own long-term support +releases typically only receive critical security and regression fixes. The +team believes that the latest tested version of npm is almost always likely to +be the most functional and defect-free version of npm. + +### `node -v` + +For most users, in most circumstances, the best version of Node will be the +latest long-term support (LTS) release. Those of you who want access to new +ECMAscript features or bleeding-edge changes to Node's standard library may be +running a newer version, and some of you may be required to run an older +version of Node because of enterprise change control policies. That's OK! But +in general, the npm team recommends that most users run Node.js LTS. + +### `npm config get registry` + +Some of you may be installing from private package registries for your project +or company. That's great! Others of you may be following tutorials or +StackOverflow questions in an effort to troubleshoot problems you may be +having. Sometimes, this may entail changing the registry you're pointing at. +This part of `npm doctor` just lets you, and maybe whoever's helping you with +support, know that you're not using the default registry. + +### `which git` + +While it's documented in the README, it may not be obvious that npm needs Git +installed to do many of the things that it does. Also, in some cases +– especially on Windows – you may have Git set up in such a way that it's not +accessible via your `PATH` so that npm can find it. This check ensures that Git +is available. + +### Permissions checks + +* Your cache must be readable and writable by the user running npm. +* Global package binaries must be writable by the user running npm. +* Your local `node_modules` path, if you're running `npm doctor` with a project + directory, must be readable and writable by the user running npm. + +### Validate the checksums of cached packages + +When an npm package is published, the publishing process generates a checksum +that npm uses at install time to verify that the package didn't get corrupted +in transit. `npm doctor` uses these checksums to validate the package tarballs +in your local cache (you can see where that cache is located with `npm config +get cache`, and see what's in that cache with `npm cache ls` – probably more +than you were expecting!). In the event that there are corrupt packages in your +cache, you should probably run `npm cache clean` and reset the cache. + +## SEE ALSO + +* npm-bugs(1) +* npm-help(1) +* npm-ping(1) diff --git a/deps/npm/doc/misc/npm-config.md b/deps/npm/doc/misc/npm-config.md index 26f7d3c61f92dc..e93e42a3fb71f9 100644 --- a/deps/npm/doc/misc/npm-config.md +++ b/deps/npm/doc/misc/npm-config.md @@ -600,6 +600,13 @@ Commit message which is used by `npm version` when creating version commit. Any "%s" in the message will be replaced with the version number. +### metrics-registry + +* Default: "https://registry.npmjs.org/" +* Type: String + +The registry you want to send cli metrics to if `send-metrics` is true. + ### node-version * Default: process.version @@ -844,6 +851,16 @@ Space-separated options that are always passed to search. The age of the cache, in seconds, before another registry request is made. +### send-metrics + +* Default: false +* Type: Boolean + +If true, success/failure metrics will be reported to the registry stored in +`metrics-registry`. These requests contain the number of successful and +failing runs of the npm CLI and the time period overwhich those counts were +gathered. No identifying information is included in these requests. + ### shell * Default: SHELL environment variable, or "bash" on Posix, or "cmd" on diff --git a/deps/npm/doc/misc/npm-index.md b/deps/npm/doc/misc/npm-index.md index 775558f4a8c60c..7569a225c7f146 100644 --- a/deps/npm/doc/misc/npm-index.md +++ b/deps/npm/doc/misc/npm-index.md @@ -65,6 +65,10 @@ Modify package distribution tags Docs for a package in a web browser maybe +### npm-doctor(1) + +Check your environments + ### npm-edit(1) Edit an installed package diff --git a/deps/npm/html/doc/README.html b/deps/npm/html/doc/README.html index 0d97ebb0153119..0b00d8b46e89de 100644 --- a/deps/npm/html/doc/README.html +++ b/deps/npm/html/doc/README.html @@ -126,5 +126,5 @@

SEE ALSO

       - + diff --git a/deps/npm/html/doc/cli/npm-access.html b/deps/npm/html/doc/cli/npm-access.html index 80a1da3423359d..d8d7811a0e1beb 100644 --- a/deps/npm/html/doc/cli/npm-access.html +++ b/deps/npm/html/doc/cli/npm-access.html @@ -84,5 +84,5 @@

SEE ALSO

       - + diff --git a/deps/npm/html/doc/cli/npm-adduser.html b/deps/npm/html/doc/cli/npm-adduser.html index 9f6ccada72eae4..605b3bd2005e83 100644 --- a/deps/npm/html/doc/cli/npm-adduser.html +++ b/deps/npm/html/doc/cli/npm-adduser.html @@ -73,5 +73,5 @@

SEE ALSO

       - + diff --git a/deps/npm/html/doc/cli/npm-bin.html b/deps/npm/html/doc/cli/npm-bin.html index 57a372baffc9bc..73370ac7f02a2b 100644 --- a/deps/npm/html/doc/cli/npm-bin.html +++ b/deps/npm/html/doc/cli/npm-bin.html @@ -35,5 +35,5 @@

SEE ALSO

       - + diff --git a/deps/npm/html/doc/cli/npm-bugs.html b/deps/npm/html/doc/cli/npm-bugs.html index 607d245c27128e..db76529b47d926 100644 --- a/deps/npm/html/doc/cli/npm-bugs.html +++ b/deps/npm/html/doc/cli/npm-bugs.html @@ -55,5 +55,5 @@

SEE ALSO

       - + diff --git a/deps/npm/html/doc/cli/npm-build.html b/deps/npm/html/doc/cli/npm-build.html index 5f89aca15cb458..1f197ee2619210 100644 --- a/deps/npm/html/doc/cli/npm-build.html +++ b/deps/npm/html/doc/cli/npm-build.html @@ -40,5 +40,5 @@

DESCRIPTION

       - + diff --git a/deps/npm/html/doc/cli/npm-bundle.html b/deps/npm/html/doc/cli/npm-bundle.html index 41a4229c999b49..d1e15012e4ab21 100644 --- a/deps/npm/html/doc/cli/npm-bundle.html +++ b/deps/npm/html/doc/cli/npm-bundle.html @@ -31,5 +31,5 @@

SEE ALSO

       - + diff --git a/deps/npm/html/doc/cli/npm-cache.html b/deps/npm/html/doc/cli/npm-cache.html index 1b6b34adb94405..272dba868b666f 100644 --- a/deps/npm/html/doc/cli/npm-cache.html +++ b/deps/npm/html/doc/cli/npm-cache.html @@ -19,8 +19,9 @@

SYNOPSIS

npm cache ls [<path>] npm cache clean [<path>] +aliases: npm cache clear, npm cache rm

DESCRIPTION

-

Used to add, list, or clear the npm cache folder.

+

Used to add, list, or clean the npm cache folder.

  • add: Add the specified package to the local cache. This command is primarily @@ -35,7 +36,7 @@

    SYNOPSIS

  • clean: Delete data out of the cache folder. If an argument is provided, then it specifies a subpath to delete. If no argument is provided, then -the entire cache is cleared.

    +the entire cache is deleted.

DETAILS

@@ -81,5 +82,5 @@

SEE ALSO

       - + diff --git a/deps/npm/html/doc/cli/npm-completion.html b/deps/npm/html/doc/cli/npm-completion.html index 2f5cad2d33b4f2..6ee1bc78a18d10 100644 --- a/deps/npm/html/doc/cli/npm-completion.html +++ b/deps/npm/html/doc/cli/npm-completion.html @@ -43,5 +43,5 @@

SEE ALSO

       - + diff --git a/deps/npm/html/doc/cli/npm-config.html b/deps/npm/html/doc/cli/npm-config.html index 9036bf84d5ac4d..677322af8b60f2 100644 --- a/deps/npm/html/doc/cli/npm-config.html +++ b/deps/npm/html/doc/cli/npm-config.html @@ -67,5 +67,5 @@

SEE ALSO

       - + diff --git a/deps/npm/html/doc/cli/npm-dedupe.html b/deps/npm/html/doc/cli/npm-dedupe.html index e822dd5e65c19c..e07dd765416aa8 100644 --- a/deps/npm/html/doc/cli/npm-dedupe.html +++ b/deps/npm/html/doc/cli/npm-dedupe.html @@ -61,5 +61,5 @@

SEE ALSO

       - + diff --git a/deps/npm/html/doc/cli/npm-deprecate.html b/deps/npm/html/doc/cli/npm-deprecate.html index 8402c36fca768f..82a0c62e4931b4 100644 --- a/deps/npm/html/doc/cli/npm-deprecate.html +++ b/deps/npm/html/doc/cli/npm-deprecate.html @@ -38,5 +38,5 @@

SEE ALSO

       - + diff --git a/deps/npm/html/doc/cli/npm-dist-tag.html b/deps/npm/html/doc/cli/npm-dist-tag.html index b1b5c038bf149d..573eaf40d3c81a 100644 --- a/deps/npm/html/doc/cli/npm-dist-tag.html +++ b/deps/npm/html/doc/cli/npm-dist-tag.html @@ -86,5 +86,5 @@

SEE ALSO

       - + diff --git a/deps/npm/html/doc/cli/npm-docs.html b/deps/npm/html/doc/cli/npm-docs.html index a713ca1f3a7c55..2a61c5ef29dbd8 100644 --- a/deps/npm/html/doc/cli/npm-docs.html +++ b/deps/npm/html/doc/cli/npm-docs.html @@ -56,5 +56,5 @@

SEE ALSO

       - + diff --git a/deps/npm/html/doc/cli/npm-doctor.html b/deps/npm/html/doc/cli/npm-doctor.html new file mode 100644 index 00000000000000..d5856b3ffb0205 --- /dev/null +++ b/deps/npm/html/doc/cli/npm-doctor.html @@ -0,0 +1,106 @@ + + + npm-doctor + + + + + + +
+ +

npm-doctor

Check your environments

+

SYNOPSIS

+
npm doctor
+

DESCRIPTION

+

npm doctor runs a set of checks to ensure that your npm installation has +what it needs to manage your JavaScript packages. npm is mostly a standalone tool, but it does +have some basic requirements that must be met:

+
    +
  • Node.js and git must be executable by npm.
  • +
  • The primary npm registry, registry.npmjs.com, or another service that uses +the registry API, is available.
  • +
  • The directories that npm uses, node_modules (both locally and globally), +exist and can be written by the current user.
  • +
  • The npm cache exists, and the package tarballs within it aren't corrupt.
  • +
+

Without all of these working properly, npm may not work properly. Many issues +are often attributable to things that are outside npm's code base, so npm +doctor confirms that the npm installation is in a good state.

+

Also, in addition to this, there are also very many issue reports due to using +old versions of npm. Since npm is constantly improving, running npm@latest is +better than an old version.

+

npm doctor verifies the following items in your environment, and if there are +any recommended changes, it will display them.

+

npm ping

+

By default, npm installs from the primary npm registry, registry.npmjs.org. +npm doctor hits a special ping endpoint within the registry. This can also be +checked with npm ping. If this check fails, you may be using a proxy that +needs to be configured, or may need to talk to your IT staff to get access over +HTTPS to registry.npmjs.org.

+

This check is done against whichever registry you've configured (you can see +what that is by running npm config get registry), and if you're using a +private registry that doesn't support the /whoami endpoint supported by the +primary registry, this check may fail.

+

npm -v

+

While Node.js may come bundled with a particular version of npm, it's the +policy of the CLI team that we recommend all users run npm@latest if they +can. As the CLI is maintained by a small team of contributors, there are only +resources for a single line of development, so npm's own long-term support +releases typically only receive critical security and regression fixes. The +team believes that the latest tested version of npm is almost always likely to +be the most functional and defect-free version of npm.

+

node -v

+

For most users, in most circumstances, the best version of Node will be the +latest long-term support (LTS) release. Those of you who want access to new +ECMAscript features or bleeding-edge changes to Node's standard library may be +running a newer version, and some of you may be required to run an older +version of Node because of enterprise change control policies. That's OK! But +in general, the npm team recommends that most users run Node.js LTS.

+

npm config get registry

+

Some of you may be installing from private package registries for your project +or company. That's great! Others of you may be following tutorials or +StackOverflow questions in an effort to troubleshoot problems you may be +having. Sometimes, this may entail changing the registry you're pointing at. +This part of npm doctor just lets you, and maybe whoever's helping you with +support, know that you're not using the default registry.

+

which git

+

While it's documented in the README, it may not be obvious that npm needs Git +installed to do many of the things that it does. Also, in some cases +– especially on Windows – you may have Git set up in such a way that it's not +accessible via your PATH so that npm can find it. This check ensures that Git +is available.

+

Permissions checks

+
    +
  • Your cache must be readable and writable by the user running npm.
  • +
  • Global package binaries must be writable by the user running npm.
  • +
  • Your local node_modules path, if you're running npm doctor with a project +directory, must be readable and writable by the user running npm.
  • +
+

Validate the checksums of cached packages

+

When an npm package is published, the publishing process generates a checksum +that npm uses at install time to verify that the package didn't get corrupted +in transit. npm doctor uses these checksums to validate the package tarballs +in your local cache (you can see where that cache is located with npm config +get cache, and see what's in that cache with npm cache ls – probably more +than you were expecting!). In the event that there are corrupt packages in your +cache, you should probably run npm cache clean and reset the cache.

+

SEE ALSO

+ + +
+ + + + + + + + + + + diff --git a/deps/npm/html/doc/cli/npm-edit.html b/deps/npm/html/doc/cli/npm-edit.html index db4eba41111280..19fb66ce3f4e68 100644 --- a/deps/npm/html/doc/cli/npm-edit.html +++ b/deps/npm/html/doc/cli/npm-edit.html @@ -49,5 +49,5 @@

SEE ALSO

       - + diff --git a/deps/npm/html/doc/cli/npm-explore.html b/deps/npm/html/doc/cli/npm-explore.html index 2fb651064c2d8d..3debd5cbd52280 100644 --- a/deps/npm/html/doc/cli/npm-explore.html +++ b/deps/npm/html/doc/cli/npm-explore.html @@ -49,5 +49,5 @@

SEE ALSO

       - + diff --git a/deps/npm/html/doc/cli/npm-help-search.html b/deps/npm/html/doc/cli/npm-help-search.html index 7a7980a97de6bc..8bec9e964f6200 100644 --- a/deps/npm/html/doc/cli/npm-help-search.html +++ b/deps/npm/html/doc/cli/npm-help-search.html @@ -45,5 +45,5 @@

SEE ALSO

       - + diff --git a/deps/npm/html/doc/cli/npm-help.html b/deps/npm/html/doc/cli/npm-help.html index 7249903ccc974f..9a1249def7c464 100644 --- a/deps/npm/html/doc/cli/npm-help.html +++ b/deps/npm/html/doc/cli/npm-help.html @@ -50,5 +50,5 @@

SEE ALSO

       - + diff --git a/deps/npm/html/doc/cli/npm-init.html b/deps/npm/html/doc/cli/npm-init.html index b4cec6b41689f9..d0d01a25aebb06 100644 --- a/deps/npm/html/doc/cli/npm-init.html +++ b/deps/npm/html/doc/cli/npm-init.html @@ -48,5 +48,5 @@

SEE ALSO

       - + diff --git a/deps/npm/html/doc/cli/npm-install-test.html b/deps/npm/html/doc/cli/npm-install-test.html index d283317a71b4cf..cf890c785a24e4 100644 --- a/deps/npm/html/doc/cli/npm-install-test.html +++ b/deps/npm/html/doc/cli/npm-install-test.html @@ -42,5 +42,5 @@

SEE ALSO

       - + diff --git a/deps/npm/html/doc/cli/npm-install.html b/deps/npm/html/doc/cli/npm-install.html index c647781dcf7ae7..b6c8f17dd8e4e3 100644 --- a/deps/npm/html/doc/cli/npm-install.html +++ b/deps/npm/html/doc/cli/npm-install.html @@ -316,5 +316,5 @@

SEE ALSO

       - + diff --git a/deps/npm/html/doc/cli/npm-link.html b/deps/npm/html/doc/cli/npm-link.html index f10b790bc2bb0f..7a14f9f684122b 100644 --- a/deps/npm/html/doc/cli/npm-link.html +++ b/deps/npm/html/doc/cli/npm-link.html @@ -74,5 +74,5 @@

SYNOPSIS

       - + diff --git a/deps/npm/html/doc/cli/npm-logout.html b/deps/npm/html/doc/cli/npm-logout.html index 6543b578511561..87b893a3c0cdca 100644 --- a/deps/npm/html/doc/cli/npm-logout.html +++ b/deps/npm/html/doc/cli/npm-logout.html @@ -51,5 +51,5 @@

scope

       - + diff --git a/deps/npm/html/doc/cli/npm-ls.html b/deps/npm/html/doc/cli/npm-ls.html index 1b5d61bd380f82..b8d712b9e4e4ae 100644 --- a/deps/npm/html/doc/cli/npm-ls.html +++ b/deps/npm/html/doc/cli/npm-ls.html @@ -21,7 +21,7 @@

SYNOPSIS

limit the results to only the paths to the packages named. Note that nested packages will also show the paths to the specified packages. For example, running npm ls promzard in npm's source tree will show:

-
npm@4.0.5 /path/to/npm
+
npm@4.1.1 /path/to/npm
 └─┬ init-package-json@0.0.4
   └── promzard@0.1.5
 

It will print out extraneous, missing, and invalid packages.

@@ -104,5 +104,5 @@

SEE ALSO

       - + diff --git a/deps/npm/html/doc/cli/npm-outdated.html b/deps/npm/html/doc/cli/npm-outdated.html index 04a0da5155da8c..245963b0adfee1 100644 --- a/deps/npm/html/doc/cli/npm-outdated.html +++ b/deps/npm/html/doc/cli/npm-outdated.html @@ -116,5 +116,5 @@

SEE ALSO

       - + diff --git a/deps/npm/html/doc/cli/npm-owner.html b/deps/npm/html/doc/cli/npm-owner.html index 9f6d4db959d509..43a57fc970a4d4 100644 --- a/deps/npm/html/doc/cli/npm-owner.html +++ b/deps/npm/html/doc/cli/npm-owner.html @@ -51,5 +51,5 @@

SEE ALSO

       - + diff --git a/deps/npm/html/doc/cli/npm-pack.html b/deps/npm/html/doc/cli/npm-pack.html index 92cea267476eb6..2a95f40f343fc5 100644 --- a/deps/npm/html/doc/cli/npm-pack.html +++ b/deps/npm/html/doc/cli/npm-pack.html @@ -41,5 +41,5 @@

SEE ALSO

       - + diff --git a/deps/npm/html/doc/cli/npm-ping.html b/deps/npm/html/doc/cli/npm-ping.html index f094762e62989e..28f7e8d281933a 100644 --- a/deps/npm/html/doc/cli/npm-ping.html +++ b/deps/npm/html/doc/cli/npm-ping.html @@ -32,5 +32,5 @@

SEE ALSO

       - + diff --git a/deps/npm/html/doc/cli/npm-prefix.html b/deps/npm/html/doc/cli/npm-prefix.html index 906de75ff820b7..d12526e41e280d 100644 --- a/deps/npm/html/doc/cli/npm-prefix.html +++ b/deps/npm/html/doc/cli/npm-prefix.html @@ -38,5 +38,5 @@

SEE ALSO

       - + diff --git a/deps/npm/html/doc/cli/npm-prune.html b/deps/npm/html/doc/cli/npm-prune.html index 9e40f28103076b..c74844bef4a69e 100644 --- a/deps/npm/html/doc/cli/npm-prune.html +++ b/deps/npm/html/doc/cli/npm-prune.html @@ -40,5 +40,5 @@

SEE ALSO

       - + diff --git a/deps/npm/html/doc/cli/npm-publish.html b/deps/npm/html/doc/cli/npm-publish.html index a6959ce0a45c1f..a9114445ae0b92 100644 --- a/deps/npm/html/doc/cli/npm-publish.html +++ b/deps/npm/html/doc/cli/npm-publish.html @@ -76,5 +76,5 @@

SEE ALSO

       - + diff --git a/deps/npm/html/doc/cli/npm-rebuild.html b/deps/npm/html/doc/cli/npm-rebuild.html index b2d06701895be2..12cb20fd200582 100644 --- a/deps/npm/html/doc/cli/npm-rebuild.html +++ b/deps/npm/html/doc/cli/npm-rebuild.html @@ -35,5 +35,5 @@

SEE ALSO

       - + diff --git a/deps/npm/html/doc/cli/npm-repo.html b/deps/npm/html/doc/cli/npm-repo.html index 83af6875167253..ad6b9be6761fdb 100644 --- a/deps/npm/html/doc/cli/npm-repo.html +++ b/deps/npm/html/doc/cli/npm-repo.html @@ -41,5 +41,5 @@

SEE ALSO

       - + diff --git a/deps/npm/html/doc/cli/npm-restart.html b/deps/npm/html/doc/cli/npm-restart.html index 6d4c455659c04e..5039bb60f69f55 100644 --- a/deps/npm/html/doc/cli/npm-restart.html +++ b/deps/npm/html/doc/cli/npm-restart.html @@ -53,5 +53,5 @@

SEE ALSO

       - + diff --git a/deps/npm/html/doc/cli/npm-root.html b/deps/npm/html/doc/cli/npm-root.html index 343790ab5799c0..d808ebad28934a 100644 --- a/deps/npm/html/doc/cli/npm-root.html +++ b/deps/npm/html/doc/cli/npm-root.html @@ -35,5 +35,5 @@

SEE ALSO

       - + diff --git a/deps/npm/html/doc/cli/npm-run-script.html b/deps/npm/html/doc/cli/npm-run-script.html index d68504647a79a3..0becbfee74ebf3 100644 --- a/deps/npm/html/doc/cli/npm-run-script.html +++ b/deps/npm/html/doc/cli/npm-run-script.html @@ -66,5 +66,5 @@

SEE ALSO

       - + diff --git a/deps/npm/html/doc/cli/npm-search.html b/deps/npm/html/doc/cli/npm-search.html index 015d4a3ddb92f6..e3902c1ba2a748 100644 --- a/deps/npm/html/doc/cli/npm-search.html +++ b/deps/npm/html/doc/cli/npm-search.html @@ -109,5 +109,5 @@

SEE ALSO

       - + diff --git a/deps/npm/html/doc/cli/npm-shrinkwrap.html b/deps/npm/html/doc/cli/npm-shrinkwrap.html index 0f80895acf155c..4eb28f3690f94d 100644 --- a/deps/npm/html/doc/cli/npm-shrinkwrap.html +++ b/deps/npm/html/doc/cli/npm-shrinkwrap.html @@ -180,5 +180,5 @@

SEE ALSO

       - + diff --git a/deps/npm/html/doc/cli/npm-star.html b/deps/npm/html/doc/cli/npm-star.html index 2564d61dfcce9d..181a4d38526303 100644 --- a/deps/npm/html/doc/cli/npm-star.html +++ b/deps/npm/html/doc/cli/npm-star.html @@ -36,5 +36,5 @@

SEE ALSO

       - + diff --git a/deps/npm/html/doc/cli/npm-stars.html b/deps/npm/html/doc/cli/npm-stars.html index a4889bd84dae3e..a514a3fbda76f1 100644 --- a/deps/npm/html/doc/cli/npm-stars.html +++ b/deps/npm/html/doc/cli/npm-stars.html @@ -36,5 +36,5 @@

SEE ALSO

       - + diff --git a/deps/npm/html/doc/cli/npm-start.html b/deps/npm/html/doc/cli/npm-start.html index 65c229ec95b16b..b51180e9b36f30 100644 --- a/deps/npm/html/doc/cli/npm-start.html +++ b/deps/npm/html/doc/cli/npm-start.html @@ -39,5 +39,5 @@

SEE ALSO

       - + diff --git a/deps/npm/html/doc/cli/npm-stop.html b/deps/npm/html/doc/cli/npm-stop.html index 277b5a845eda92..d2529c828c7957 100644 --- a/deps/npm/html/doc/cli/npm-stop.html +++ b/deps/npm/html/doc/cli/npm-stop.html @@ -34,5 +34,5 @@

SEE ALSO

       - + diff --git a/deps/npm/html/doc/cli/npm-team.html b/deps/npm/html/doc/cli/npm-team.html index 2fea57d08e5f57..2fef0f9df1011c 100644 --- a/deps/npm/html/doc/cli/npm-team.html +++ b/deps/npm/html/doc/cli/npm-team.html @@ -67,5 +67,5 @@

SEE ALSO

       - + diff --git a/deps/npm/html/doc/cli/npm-test.html b/deps/npm/html/doc/cli/npm-test.html index 041ce2130bb74e..aef313191fb88f 100644 --- a/deps/npm/html/doc/cli/npm-test.html +++ b/deps/npm/html/doc/cli/npm-test.html @@ -36,5 +36,5 @@

SEE ALSO

       - + diff --git a/deps/npm/html/doc/cli/npm-uninstall.html b/deps/npm/html/doc/cli/npm-uninstall.html index b1d9de78099b45..32480a20268918 100644 --- a/deps/npm/html/doc/cli/npm-uninstall.html +++ b/deps/npm/html/doc/cli/npm-uninstall.html @@ -60,5 +60,5 @@

SYNOPSIS

       - + diff --git a/deps/npm/html/doc/cli/npm-unpublish.html b/deps/npm/html/doc/cli/npm-unpublish.html index 147e42221ad485..69c6fe1d4a3360 100644 --- a/deps/npm/html/doc/cli/npm-unpublish.html +++ b/deps/npm/html/doc/cli/npm-unpublish.html @@ -47,5 +47,5 @@

SEE ALSO

       - + diff --git a/deps/npm/html/doc/cli/npm-update.html b/deps/npm/html/doc/cli/npm-update.html index c2b8b18d486e77..419f217d8b6a42 100644 --- a/deps/npm/html/doc/cli/npm-update.html +++ b/deps/npm/html/doc/cli/npm-update.html @@ -118,5 +118,5 @@

SEE ALSO

       - + diff --git a/deps/npm/html/doc/cli/npm-version.html b/deps/npm/html/doc/cli/npm-version.html index adbfb7ab7c9224..b3e269033bb353 100644 --- a/deps/npm/html/doc/cli/npm-version.html +++ b/deps/npm/html/doc/cli/npm-version.html @@ -107,5 +107,5 @@

SEE ALSO

       - + diff --git a/deps/npm/html/doc/cli/npm-view.html b/deps/npm/html/doc/cli/npm-view.html index f1de2303d0265c..29bbdc482a1245 100644 --- a/deps/npm/html/doc/cli/npm-view.html +++ b/deps/npm/html/doc/cli/npm-view.html @@ -86,5 +86,5 @@

SEE ALSO

       - + diff --git a/deps/npm/html/doc/cli/npm-whoami.html b/deps/npm/html/doc/cli/npm-whoami.html index 50ff32f00cd7e7..da5bfd2cad1a4b 100644 --- a/deps/npm/html/doc/cli/npm-whoami.html +++ b/deps/npm/html/doc/cli/npm-whoami.html @@ -33,5 +33,5 @@

SEE ALSO

       - + diff --git a/deps/npm/html/doc/cli/npm.html b/deps/npm/html/doc/cli/npm.html index 44685d4a29667a..a38d766a0289a6 100644 --- a/deps/npm/html/doc/cli/npm.html +++ b/deps/npm/html/doc/cli/npm.html @@ -13,7 +13,7 @@

npm

javascript package manager

SYNOPSIS

npm <command> [args]
 

VERSION

-

4.0.5

+

4.1.1

DESCRIPTION

npm is the package manager for the Node JavaScript platform. It puts modules in place so that node can find them, and manages dependency @@ -126,7 +126,7 @@

AUTHOR

Isaac Z. Schlueter :: isaacs :: @izs :: -i@izs.me

+i@izs.me

SEE ALSO

  • npm-help(1)
  • @@ -150,5 +150,5 @@

    SEE ALSO

           - + diff --git a/deps/npm/html/doc/files/npm-folders.html b/deps/npm/html/doc/files/npm-folders.html index b54e1a3f4d8011..bb323c56870589 100644 --- a/deps/npm/html/doc/files/npm-folders.html +++ b/deps/npm/html/doc/files/npm-folders.html @@ -182,5 +182,5 @@

    SEE ALSO

           - + diff --git a/deps/npm/html/doc/files/npm-global.html b/deps/npm/html/doc/files/npm-global.html index b54e1a3f4d8011..bb323c56870589 100644 --- a/deps/npm/html/doc/files/npm-global.html +++ b/deps/npm/html/doc/files/npm-global.html @@ -182,5 +182,5 @@

    SEE ALSO

           - + diff --git a/deps/npm/html/doc/files/npm-json.html b/deps/npm/html/doc/files/npm-json.html index 392d8552f84a83..47b017154560fa 100644 --- a/deps/npm/html/doc/files/npm-json.html +++ b/deps/npm/html/doc/files/npm-json.html @@ -586,5 +586,5 @@

    SEE ALSO

           - + diff --git a/deps/npm/html/doc/files/npmrc.html b/deps/npm/html/doc/files/npmrc.html index 8385a103a35e20..365ec642c4b613 100644 --- a/deps/npm/html/doc/files/npmrc.html +++ b/deps/npm/html/doc/files/npmrc.html @@ -85,5 +85,5 @@

    SEE ALSO

           - + diff --git a/deps/npm/html/doc/files/package.json.html b/deps/npm/html/doc/files/package.json.html index 392d8552f84a83..47b017154560fa 100644 --- a/deps/npm/html/doc/files/package.json.html +++ b/deps/npm/html/doc/files/package.json.html @@ -586,5 +586,5 @@

    SEE ALSO

           - + diff --git a/deps/npm/html/doc/index.html b/deps/npm/html/doc/index.html index 83baa43e6e6364..21dd422c9c263c 100644 --- a/deps/npm/html/doc/index.html +++ b/deps/npm/html/doc/index.html @@ -42,6 +42,8 @@

    npm-dist-tag(1)

    Modify package distribution tags

    npm-docs(1)

    Docs for a package in a web browser maybe

    +

    npm-doctor(1)

    +

    Check your environments

    npm-edit(1)

    Edit an installed package

    npm-explore(1)

    @@ -160,5 +162,5 @@

    semver(7)

           - + diff --git a/deps/npm/html/doc/misc/npm-coding-style.html b/deps/npm/html/doc/misc/npm-coding-style.html index 0873b5f82fb67c..99571a2db95b13 100644 --- a/deps/npm/html/doc/misc/npm-coding-style.html +++ b/deps/npm/html/doc/misc/npm-coding-style.html @@ -153,5 +153,5 @@

    SEE ALSO

           - + diff --git a/deps/npm/html/doc/misc/npm-config.html b/deps/npm/html/doc/misc/npm-config.html index c4dca1bc183180..ba35d4acb357d5 100644 --- a/deps/npm/html/doc/misc/npm-config.html +++ b/deps/npm/html/doc/misc/npm-config.html @@ -517,6 +517,12 @@

    message

Commit message which is used by npm version when creating version commit.

Any "%s" in the message will be replaced with the version number.

+

metrics-registry

+ +

The registry you want to send cli metrics to if send-metrics is true.

node-version

  • Default: process.version
  • @@ -722,6 +728,15 @@

    searchstaleness

  • Type: Number

The age of the cache, in seconds, before another registry request is made.

+

send-metrics

+
    +
  • Default: false
  • +
  • Type: Boolean
  • +
+

If true, success/failure metrics will be reported to the registry stored in +metrics-registry. These requests contain the number of successful and +failing runs of the npm CLI and the time period overwhich those counts were +gathered. No identifying information is included in these requests.

shell