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/ diff --git a/.eslintrc b/.eslintrc index 0aed06ca55f5c3..4f691caefd3a78 100644 --- a/.eslintrc +++ b/.eslintrc @@ -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 @@ -84,7 +88,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] @@ -120,12 +128,11 @@ 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 }] new-with-error: [2, Error, RangeError, TypeError, SyntaxError, ReferenceError] - no-useless-regex-char-class-escape: [2, { override: ['[', ']'] }] + timer-arguments: 2 # Global scoped method and vars globals: diff --git a/BUILDING.md b/BUILDING.md index b98bb75d79b656..75ef93f8c73a13 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`. @@ -121,7 +122,7 @@ Prerequisites: To run the tests: ```console -> .\vcbuild test +> .\vcbuild nosign test ``` To test if Node.js was built correctly: @@ -179,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 @@ -196,7 +197,7 @@ $ ./configure --without-intl ##### Windows: ```console -> .\vcbuild without-intl +> .\vcbuild nosign without-intl ``` #### Use existing installed ICU (Unix / OS X only): @@ -239,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/COLLABORATOR_GUIDE.md b/COLLABORATOR_GUIDE.md index 32533304fecc67..7ac8f49ee09ff0 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. @@ -318,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 @@ -341,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. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 6d419aa4954fde..736a9542c42baf 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 @@ -167,7 +170,7 @@ $ ./configure && make -j4 test Windows: ```text -> vcbuild test + .\vcbuild nosign test ``` (See the [BUILDING.md](./BUILDING.md) for more details.) @@ -175,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: diff --git a/README.md b/README.md index 3bc0bea7020e8b..05d45be7388689 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) - @@ -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) - 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 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/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); } } 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/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)); 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); +} 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 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(); diff --git a/benchmark/run.js b/benchmark/run.js index 52ce74024e1ae4..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) @@ -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}`); } }); 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/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'); - } -} 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/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/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); +} 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 diff --git a/doc/api/buffer.md b/doc/api/buffer.md index b9f8369335a0d6..adc9d6b104680b 100644 --- a/doc/api/buffer.md +++ b/doc/api/buffer.md @@ -348,15 +348,16 @@ deprecated: v6.0.0 > [`Buffer.from(arrayBuffer[, byteOffset [, length]])`][`Buffer.from(arrayBuffer)`] > instead. -* `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`]. The optional `byteOffset` and `length` arguments specify a memory range within the `arrayBuffer` that will be shared by the `Buffer`. @@ -719,15 +720,16 @@ A `TypeError` will be thrown if `array` is not an `Array`. added: v5.10.0 --> -* `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: diff --git a/doc/api/child_process.md b/doc/api/child_process.md index 0147242c5583a0..c541837b91e302 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) => { // ... @@ -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 @@ -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(); @@ -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. @@ -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 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 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 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: diff --git a/doc/api/process.md b/doc/api/process.md index 3e0414e59effc4..4e20399d41fade 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); @@ -1754,5 +1754,5 @@ cases: [Readable]: stream.html [Child Process]: child_process.html [Cluster]: cluster.html -[`process.exitCode`]: #processexitcode-1 +[`process.exitCode`]: #process_process_exitcode [LTS]: https://github.com/nodejs/LTS/ diff --git a/doc/api/stream.md b/doc/api/stream.md index 291cda735aee3d..1095d8e6ecb5f8 100644 --- a/doc/api/stream.md +++ b/doc/api/stream.md @@ -440,12 +440,49 @@ occurs, the `callback` *may or may not* be called with the error as its first argument. To reliably detect write errors, add a listener for the `'error'` event. -The return value is `true` if the internal buffer does not exceed +The return value is `true` if the internal buffer is less than the `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. @@ -1306,7 +1343,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. diff --git a/doc/api/tls.md b/doc/api/tls.md index c33174f250479a..f6bc19da78d264 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' @@ -587,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 @@ -604,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', @@ -620,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() Provides an object enumerating Zlib-related constants. @@ -460,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 diff --git a/doc/changelogs/CHANGELOG_V7.md b/doc/changelogs/CHANGELOG_V7.md index 1f476b8eae4649..f10ecdcc9c2b12 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) @@ -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) 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 diff --git a/doc/guides/writing-tests.md b/doc/guides/writing-tests.md index d628e3f6f5873c..f27c076590e513 100644 --- a/doc/guides/writing-tests.md +++ b/doc/guides/writing-tests.md @@ -2,26 +2,25 @@ ## 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. -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'; @@ -30,8 +29,8 @@ Let's analyze this very 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'); @@ -47,7 +46,7 @@ Let's analyze this very basic test from the Node.js test suite: 21 }); ``` -**Lines 1-2** +### **Lines 1-2** ```javascript 'use strict'; @@ -60,17 +59,18 @@ 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'); ``` -**Lines 4-5** +### **Lines 4-5** ```javascript // This test ensures that the http-parser can handle UTF-8 characters @@ -80,32 +80,35 @@ 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'); ``` -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. +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** +### **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. @@ -113,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 @@ -191,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 @@ -205,3 +208,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`. diff --git a/doc/onboarding-extras.md b/doc/onboarding-extras.md index 9e1a4a7ed7b14b..1b5d082434fd71 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 | @@ -26,10 +27,11 @@ | `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 | +| python code | @nodejs/python | | platform specific | @nodejs/platform-{aix,arm,freebsd,macos,ppc,smartos,s390,windows} | 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); diff --git a/lib/_http_client.js b/lib/_http_client.js index 1846e36e12bf88..a33a6805329ddf 100644 --- a/lib/_http_client.js +++ b/lib/_http_client.js @@ -13,7 +13,35 @@ 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\-._~!$&'()*+,;=/:@]/ +// 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; @@ -24,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); } @@ -43,14 +73,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 + '"'); } @@ -61,9 +97,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; @@ -77,10 +111,11 @@ 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++) { + for (var i = 0; i < keys.length; i++) { var key = keys[i]; self.setHeader(key, options.headers[key]); } @@ -106,7 +141,6 @@ function ClientRequest(options, cb) { } if (options.auth && !this.getHeader('Authorization')) { - //basic auth this.setHeader('Authorization', 'Basic ' + Buffer.from(options.auth).toString('base64')); } @@ -121,7 +155,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')) { @@ -129,6 +163,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; @@ -196,16 +238,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); @@ -219,7 +257,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 @@ -448,7 +486,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); 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; 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/assert.js b/lib/assert.js index 04c5cb5ad436e1..7f69ba0c60e476 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,16 +106,17 @@ 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); - +/* eslint-disable no-restricted-properties */ 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,10 +124,9 @@ 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 */ assert.deepEqual = function deepEqual(actual, expected, message) { if (!_deepEqual(actual, expected, false)) { fail(actual, expected, message, 'deepEqual', assert.deepEqual); @@ -141,18 +141,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 +166,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 +189,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 +219,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 +232,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 +257,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 +274,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 +283,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 +307,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 +365,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) { 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/lib/crypto.js b/lib/crypto.js index 6b2a04711a868a..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'; @@ -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/events.js b/lib/events.js index 6a8345ab7bc516..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'); @@ -360,6 +361,8 @@ EventEmitter.prototype.removeListener = } else { delete events[type]; } + } else if (position === 0) { + list.shift(); } else { spliceOne(list, position); } diff --git a/lib/fs.js b/lib/fs.js index d407cf1479eac0..ac0049d2576ba0 100644 --- a/lib/fs.js +++ b/lib/fs.js @@ -310,7 +310,7 @@ ReadFileContext.prototype.read = function() { req.oncomplete = readFileAfterRead; req.context = this; - binding.read(this.fd, buffer, offset, length, -1, req); + binding.read(this.fd, buffer, offset, length, this.pos, req); }; ReadFileContext.prototype.close = function(err) { @@ -450,11 +450,11 @@ function tryCreateBuffer(size, fd, isUserFd) { return buffer; } -function tryReadSync(fd, isUserFd, buffer, pos, len) { +function tryReadSync(fd, isUserFd, buffer, pos, len, offset) { var threw = true; var bytesRead; try { - bytesRead = fs.readSync(fd, buffer, pos, len); + bytesRead = fs.readSync(fd, buffer, pos, len, offset); threw = false; } finally { if (threw && !isUserFd) fs.closeSync(fd); @@ -483,7 +483,7 @@ fs.readFileSync = function(path, options) { if (size !== 0) { do { - bytesRead = tryReadSync(fd, isUserFd, buffer, pos, size - pos); + bytesRead = tryReadSync(fd, isUserFd, buffer, pos, size - pos, pos); pos += bytesRead; } while (bytesRead !== 0 && pos < size); } else { @@ -491,7 +491,7 @@ fs.readFileSync = function(path, options) { // the kernel lies about many files. // Go ahead and try to read some bytes. buffer = Buffer.allocUnsafe(8192); - bytesRead = tryReadSync(fd, isUserFd, buffer, 0, 8192); + bytesRead = tryReadSync(fd, isUserFd, buffer, 0, 8192, pos); if (bytesRead !== 0) { buffers.push(buffer.slice(0, bytesRead)); } @@ -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') { diff --git a/lib/https.js b/lib/https.js index 26b6cbf279a15f..e59e7dfcb6beeb 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'); @@ -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); @@ -143,6 +144,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; }; @@ -192,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/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) { 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) 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/internal/url.js b/lib/internal/url.js index e1e1c515f842d2..e8dcacc56dc164 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]; @@ -284,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; @@ -325,7 +327,7 @@ Object.defineProperties(URL.prototype, { enumerable: true, configurable: true, get() { - return originFor(this).toString(true); + return originFor(this).toString(); } }, protocol: { @@ -907,8 +909,32 @@ 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.originFor = originFor; exports.domainToASCII = domainToASCII; exports.domainToUnicode = domainToUnicode; exports.encodeAuth = encodeAuth; +exports.urlToOptions = urlToOptions; diff --git a/lib/internal/util.js b/lib/internal/util.js index 238eb65891365c..42a0922d304970 100644 --- a/lib/internal/util.js +++ b/lib/internal/util.js @@ -97,16 +97,22 @@ 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'); }; 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; } } }; @@ -134,20 +140,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(); @@ -158,7 +158,7 @@ exports.cachedResult = function cachedResult(fn) { return () => { if (result === undefined) result = fn(); - return result; + return result.slice(); }; }; 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/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; diff --git a/lib/repl.js b/lib/repl.js index 858ccd883850d3..a8eb83093d9574 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); @@ -728,9 +728,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) { @@ -1223,12 +1221,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' + ]); } } @@ -1272,9 +1271,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/lib/tls.js b/lib/tls.js index 32c0319754be2a..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'); @@ -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/lib/util.js b/lib/util.js index 37008b2d176062..9d5909cdc7ce30 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])); } } @@ -173,8 +170,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; @@ -403,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'); @@ -663,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(''); } @@ -674,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/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/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. 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', diff --git a/src/env-inl.h b/src/env-inl.h index 83db3d33b6d18f..1a17e2947d0597 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); @@ -316,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/inspector_agent.cc b/src/inspector_agent.cc index fc478c49a09d61..8e72b3643c872c 100644 --- a/src/inspector_agent.cc +++ b/src/inspector_agent.cc @@ -129,7 +129,6 @@ class InspectorAgentDelegate: public node::inspector::SocketServerDelegate { class AgentImpl { public: explicit AgentImpl(node::Environment* env); - ~AgentImpl(); // Start the inspector agent thread bool Start(v8::Platform* platform, const char* path, int port, bool wait); @@ -183,7 +182,6 @@ class AgentImpl { State state_; node::Environment* parent_env_; - uv_async_t* data_written_; uv_async_t io_thread_req_; V8NodeInspector* inspector_; v8::Platform* platform_; @@ -323,7 +321,6 @@ AgentImpl::AgentImpl(Environment* env) : delegate_(nullptr), shutting_down_(false), state_(State::kNew), parent_env_(env), - data_written_(new uv_async_t()), inspector_(nullptr), platform_(nullptr), dispatching_messages_(false), @@ -331,16 +328,6 @@ AgentImpl::AgentImpl(Environment* env) : delegate_(nullptr), server_(nullptr) { CHECK_EQ(0, uv_sem_init(&start_sem_, 0)); memset(&io_thread_req_, 0, sizeof(io_thread_req_)); - CHECK_EQ(0, uv_async_init(env->event_loop(), data_written_, nullptr)); - uv_unref(reinterpret_cast(data_written_)); -} - -AgentImpl::~AgentImpl() { - auto close_cb = [](uv_handle_t* handle) { - delete reinterpret_cast(handle); - }; - uv_close(reinterpret_cast(data_written_), close_cb); - data_written_ = nullptr; } void InspectorConsoleCall(const v8::FunctionCallbackInfo& info) { @@ -606,7 +593,6 @@ void AgentImpl::PostIncomingMessage(int session_id, platform_->CallOnForegroundThread(isolate, new DispatchOnInspectorBackendTask(this)); isolate->RequestInterrupt(InterruptCallback, this); - uv_async_send(data_written_); } NotifyMessageReceived(); } @@ -662,7 +648,6 @@ void AgentImpl::DispatchMessages() { } } } while (!tasks.empty()); - uv_async_send(data_written_); dispatching_messages_ = false; } 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/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); 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/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()) * 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/README.md b/test/README.md index 8d8cec44919720..94f77eda5148f2 100644 --- a/test/README.md +++ b/test/README.md @@ -163,6 +163,13 @@ A stream to push an array into a REPL Blocks for `time` amount of time. +### canCreateSymLink +API to indicate whether the current running process can create +symlinks. On Windows, this returns false if the process running +doesn't have privileges to create symlinks (specifically +[SeCreateSymbolicLinkPrivilege](https://msdn.microsoft.com/en-us/library/windows/desktop/bb530716(v=vs.85).aspx)). +On non-Windows platforms, this currently returns true. + ### ddCommand(filename, kilobytes) * return [<Object>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) @@ -366,7 +373,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/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/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/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..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,10 +28,10 @@ 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 -var addon = require(addonDestinationPath); -assert.notEqual(addon, null); +const addon = require(addonDestinationPath); +assert.notStrictEqual(addon, null); assert.strictEqual(addon.hello(), 'world'); 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 5591b4f2b38e90..95536f99711324 100644 --- a/test/addons/repl-domain-abort/test.js +++ b/test/addons/repl-domain-abort/test.js @@ -1,30 +1,30 @@ 'use strict'; -var common = require('../../common'); -var assert = require('assert'); -var repl = require('repl'); -var stream = require('stream'); -var path = require('path'); -var buildType = process.config.target_defaults.default_configuration; -var buildPath = path.join(__dirname, 'build', buildType, 'binding'); +const common = require('../../common'); +const assert = require('assert'); +const repl = require('repl'); +const stream = require('stream'); +const path = require('path'); +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/cctest/test_inspector_socket_server.cc b/test/cctest/test_inspector_socket_server.cc index 2bbc3811390fe6..3c19661f97408b 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 { @@ -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_); } diff --git a/test/common.js b/test/common.js index 0fff06bfc0944d..05ef4c9d682c0d 100644 --- a/test/common.js +++ b/test/common.js @@ -8,9 +8,10 @@ const child_process = require('child_process'); const stream = require('stream'); const util = require('util'); const Timer = process.binding('timer_wrap').Timer; +const execSync = require('child_process').execSync; 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'; @@ -202,6 +203,28 @@ exports.hasIPv6 = Object.keys(ifaces).some(function(name) { }); }); +/* + * Check that when running a test with + * `$node --abort-on-uncaught-exception $file child` + * the process aborts. + */ +exports.childShouldThrowAndAbort = function() { + 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 + testCmd += 'ulimit -c 0 && '; + } + testCmd += `${process.argv[0]} --abort-on-uncaught-exception `; + testCmd += `${process.argv[1]} child`; + const child = child_process.exec(testCmd); + child.on('exit', function onExit(exitCode, signal) { + const errMsg = 'Test should have aborted ' + + `but instead exited with exit code ${exitCode}` + + ` and signal ${signal}`; + assert(exports.nodeProcessAborted(exitCode, signal), errMsg); + }); +}; exports.ddCommand = function(filename, kilobytes) { if (exports.isWindows) { @@ -398,7 +421,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, @@ -435,6 +461,34 @@ exports.fileExists = function(pathname) { } }; +exports.canCreateSymLink = function() { + // On Windows, creating symlinks requires admin privileges. + // We'll only try to run symlink test if we have enough privileges. + // On other platforms, creating symlinks shouldn't need admin privileges + if (exports.isWindows) { + // whoami.exe needs to be the one from System32 + // 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'); + + let err = false; + let output = ''; + + try { + output = execSync(whoamiPath + ' /priv', { timout: 1000 }); + } catch (e) { + err = true; + } finally { + if (err || !output.includes('SeCreateSymbolicLinkPrivilege')) { + return false; + } + } + } + + return true; +}; + function fail(msg) { assert.fail(null, null, msg); } diff --git a/test/debugger/helper-debugger-repl.js b/test/debugger/helper-debugger-repl.js index 602ab1c05e53d6..38c65a03fa590d 100644 --- a/test/debugger/helper-debugger-repl.js +++ b/test/debugger/helper-debugger-repl.js @@ -1,15 +1,15 @@ '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; +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-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..f5de9f5ee95778 100644 --- a/test/debugger/test-debugger-repl-restart.js +++ b/test/debugger/test-debugger-repl-restart.js @@ -1,15 +1,15 @@ 'use strict'; require('../common'); -var repl = require('./helper-debugger-repl.js'); +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 6872f6ce2f9c72..4932df12e713bb 100644 --- a/test/debugger/test-debugger-repl-term.js +++ b/test/debugger/test-debugger-repl-term.js @@ -2,11 +2,11 @@ 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'); -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 6654a498219859..90214158884371 100644 --- a/test/debugger/test-debugger-repl-utf8.js +++ b/test/debugger/test-debugger-repl-utf8.js @@ -1,6 +1,6 @@ 'use strict'; -var common = require('../common'); -var script = common.fixturesDir + '/breakpoints_utf8.js'; +const common = require('../common'); +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 8a87d40d163af7..32dbfa22c0d3a9 100644 --- a/test/debugger/test-debugger-repl.js +++ b/test/debugger/test-debugger-repl.js @@ -1,10 +1,10 @@ 'use strict'; -require('../common'); -var repl = require('./helper-debugger-repl.js'); +const common = require('../common'); +const repl = require('./helper-debugger-repl.js'); repl.startDebugger('breakpoints.js'); -var addTest = repl.addTest; +const addTest = repl.addTest; // Next addTest('n', [ @@ -57,7 +57,7 @@ addTest('c', [ // Execute addTest('exec process.title', [ - /node/ + common.isFreeBSD || common.isOSX || common.isLinux ? /node/ : '' ]); // Execute 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 271e6689046a00..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); @@ -34,7 +34,7 @@ function onMessage(message, info) { } function afterSend(err) { - if (err) throw err; + assert.ifError(err); packetsSent++; } 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..3603e9bb421a26 100644 --- a/test/disabled/test-setuidgid.js +++ b/test/disabled/test-setuidgid.js @@ -1,17 +1,17 @@ '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'); 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/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/doctool/test-doctool-html.js b/test/doctool/test-doctool-html.js index bd21e21d9563d2..e5c825aebbb32c 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, ''); @@ -96,7 +96,7 @@ testData.forEach(function(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/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); })); 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..bb38793b65d7de 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()); -assert.deepEqual(module.parent.paths, expectedPaths); +const expectedPaths = require('module')._nodeModulePaths(process.cwd()); +assert.deepStrictEqual(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..4897a294eacb73 100644 --- a/test/fixtures/not-main-module.js +++ b/test/fixtures/not-main-module.js @@ -1,4 +1,4 @@ -var assert = require('assert'); -assert.notEqual(module, require.main, 'require.main should not == module'); -assert.notEqual(module, process.mainModule, - 'process.mainModule should not === module'); +const assert = require('assert'); +assert.notStrictEqual(module, require.main, 'require.main should not == module'); +assert.notStrictEqual(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/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/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/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 44d665b99f5bb6..634a8e3f663985 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", @@ -1787,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": "", @@ -1795,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": "", @@ -1810,7 +1870,7 @@ "host": "example.com", "hostname": "example.com", "port": "", - "pathname": "/..bar", + "pathname": "/%2e.bar", "search": "", "hash": "" }, @@ -2228,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": "", @@ -2236,7 +2296,7 @@ "host": "www", "hostname": "www", "port": "", - "pathname": "/foo.html", + "pathname": "/foo%2Ehtml", "search": "", "hash": "" }, @@ -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": "", 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 b7498e438ccd83..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 = [], @@ -57,7 +57,7 @@ groups.push([1, ['(', [ /* replace TryCatch with NanTryCatch once, gobbling possible namespace, key group 2 */ groups.push([2, '(?:(?:v8\\:\\:)?|(Nan)?)(TryCatch)']); -/* NanNew("string") will likely not fail a ToLocalChecked(), key group 1 */ +/* NanNew("string") will likely not fail a ToLocalChecked(), key group 1 */ groups.push([1, ['(NanNew)', '(\\("[^\\"]*"[^\\)]*\\))(?!\\.ToLocalChecked\\(\\))'].join('')]); /* Removed v8 APIs, warn that the code needs rewriting using node::Buffer, key group 2 */ 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/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 2d9bc134a30347..c797bee41c6cae 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/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-dgram-broadcast-multi-process.js b/test/internet/test-dgram-broadcast-multi-process.js index c05d0cf5b9512e..da3bd8cceb74e3 100644 --- a/test/internet/test-dgram-broadcast-multi-process.js +++ b/test/internet/test-dgram-broadcast-multi-process.js @@ -179,7 +179,7 @@ if (process.argv[2] !== 'child') { common.PORT, LOCAL_BROADCAST_HOST, function(err) { - if (err) throw err; + assert.ifError(err); console.error('[PARENT] sent %s to %s:%s', util.inspect(buf.toString()), LOCAL_BROADCAST_HOST, common.PORT); diff --git a/test/internet/test-dgram-multicast-multi-process.js b/test/internet/test-dgram-multicast-multi-process.js index 307549bba870b6..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() { @@ -160,7 +161,7 @@ if (process.argv[2] !== 'child') { common.PORT, LOCAL_BROADCAST_HOST, function(err) { - if (err) throw err; + assert.ifError(err); console.error('[PARENT] sent "%s" to %s:%s', buf.toString(), LOCAL_BROADCAST_HOST, common.PORT); diff --git a/test/internet/test-dgram-send-cb-quelches-error.js b/test/internet/test-dgram-send-cb-quelches-error.js index 56612edead4fd2..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'; -var common = require('../common'); -var mustCall = common.mustCall; -var assert = require('assert'); -var dgram = require('dgram'); -var dns = require('dns'); +const common = require('../common'); +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 76ebf0d628b1c4..5328d7e3d97925 100644 --- a/test/internet/test-dns-cares-domains.js +++ b/test/internet/test-dns-cares-domains.js @@ -1,10 +1,10 @@ '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 = [ +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-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 b2cdd14c53a60c..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); }); @@ -87,7 +87,7 @@ TEST(function test_lookup_ipv6_explicit(done) { /* This ends up just being too problematic to test TEST(function test_lookup_ipv6_implicit(done) { var req = dns.lookup('ipv6.google.com', function(err, ip, family) { - if (err) throw err; + assert.ifError(err); assert.ok(net.isIPv6(ip)); assert.strictEqual(family, 6); @@ -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); }); @@ -196,7 +198,7 @@ TEST(function test_lookupservice_ip_ipv6(done) { /* Disabled because it appears to be not working on linux. */ /* TEST(function test_lookup_localhost_ipv6(done) { var req = dns.lookup('localhost', 6, function(err, ip, family) { - if (err) throw err; + assert.ifError(err); assert.ok(net.isIPv6(ip)); assert.strictEqual(family, 6); 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-dns.js b/test/internet/test-dns.js index db3449dc727516..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,13 +103,12 @@ TEST(function test_resolve6_ttl(done) { }); TEST(function test_resolveMx(done) { - var req = dns.resolveMx('gmail.com', function(err, result) { - if (err) throw err; - + 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'); @@ -126,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'); @@ -139,13 +138,12 @@ TEST(function test_resolveMx_failure(done) { }); TEST(function test_resolveNs(done) { - var req = dns.resolveNs('rackspace.com', function(err, names) { - if (err) throw err; - + 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'); } @@ -157,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'); @@ -170,13 +168,12 @@ TEST(function test_resolveNs_failure(done) { }); TEST(function test_resolveSrv(done) { - var req = dns.resolveSrv('_jabber._tcp.google.com', function(err, result) { - if (err) throw err; - + 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'); @@ -195,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'); @@ -208,13 +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) { - if (err) throw err; - + 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'); } @@ -226,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'); @@ -239,13 +235,12 @@ TEST(function test_resolvePtr_failure(done) { }); TEST(function test_resolveNaptr(done) { - var req = dns.resolveNaptr('sip2sip.info', function(err, result) { - if (err) throw err; - + 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'); @@ -264,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'); @@ -277,9 +272,8 @@ TEST(function test_resolveNaptr_failure(done) { }); TEST(function test_resolveSoa(done) { - var req = dns.resolveSoa('nodejs.org', function(err, result) { - if (err) throw err; - + const req = dns.resolveSoa('nodejs.org', function(err, result) { + assert.ifError(err); assert.ok(result); assert.strictEqual(typeof result, 'object'); @@ -311,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'); @@ -324,13 +318,12 @@ TEST(function test_resolveSoa_failure(done) { }); TEST(function test_resolveCname(done) { - var req = dns.resolveCname('www.microsoft.com', function(err, names) { - if (err) throw err; - + 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'); } @@ -342,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'); @@ -356,8 +349,8 @@ TEST(function test_resolveCname_failure(done) { TEST(function test_resolveTxt(done) { - var req = dns.resolveTxt('google.com', function(err, records) { - if (err) throw err; + const req = dns.resolveTxt('google.com', function(err, records) { + assert.ifError(err); assert.strictEqual(records.length, 1); assert.ok(util.isArray(records[0])); assert.strictEqual(records[0][0].indexOf('v=spf1'), 0); @@ -368,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'); @@ -382,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'); @@ -397,8 +390,8 @@ TEST(function test_lookup_failure(done) { TEST(function test_lookup_null(done) { - var req = dns.lookup(null, function(err, ip, family) { - if (err) throw err; + const req = dns.lookup(null, function(err, ip, family) { + assert.ifError(err); assert.strictEqual(ip, null); assert.strictEqual(family, 4); @@ -410,8 +403,8 @@ 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) { - if (err) throw err; + 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); assert.strictEqual(ips[0].address, '127.0.0.1'); @@ -425,8 +418,8 @@ 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) { - if (err) throw err; + const req = dns.lookup(null, {all: true}, function(err, ips, family) { + assert.ifError(err); assert.ok(Array.isArray(ips)); assert.strictEqual(ips.length, 0); @@ -438,8 +431,8 @@ 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) { - if (err) throw err; + 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); @@ -460,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)); @@ -473,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'); @@ -487,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'); @@ -501,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) { @@ -523,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-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..95e25614ffa2b7 100644 --- a/test/internet/test-net-connect-timeout.js +++ b/test/internet/test-net-connect-timeout.js @@ -4,24 +4,24 @@ // 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(); +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 52929d2152774d..f3be8409844702 100644 --- a/test/internet/test-net-connect-unref.js +++ b/test/internet/test-net-connect-unref.js @@ -1,11 +1,10 @@ 'use strict'; const common = require('../common'); -var net = require('net'); +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-add-ca-cert.js b/test/internet/test-tls-add-ca-cert.js new file mode 100644 index 00000000000000..05f3b4dc10e36c --- /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'); + +const 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(); +} diff --git a/test/internet/test-tls-connnect-melissadata.js b/test/internet/test-tls-connnect-melissadata.js index 7ab7f2aa7a7895..f57b897099fc2d 100644 --- a/test/internet/test-tls-connnect-melissadata.js +++ b/test/internet/test-tls-connnect-melissadata.js @@ -2,14 +2,14 @@ // 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'); -var socket = tls.connect(443, 'address.melissadata.net', function() { +const tls = require('tls'); +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/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..d50df9081b2d25 100644 --- a/test/message/eval_messages.js +++ b/test/message/eval_messages.js @@ -2,19 +2,19 @@ require('../common'); -var spawn = require('child_process').spawn; +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 6e1ced4124f2a6..b32004c329dead 100644 --- a/test/message/stdin_messages.js +++ b/test/message/stdin_messages.js @@ -2,20 +2,20 @@ require('../common'); -var spawn = require('child_process').spawn; +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/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/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-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 eb983345418637..e00f044942059c 100644 --- a/test/parallel/test-assert.js +++ b/test/parallel/test-assert.js @@ -1,10 +1,10 @@ '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); + const args = Array.prototype.slice.call(arguments, 1); return function() { return f.apply(this, args); }; @@ -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 @@ -120,8 +120,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; @@ -131,7 +131,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; } }; @@ -149,8 +149,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)); @@ -267,8 +267,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); @@ -285,7 +285,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)); @@ -326,7 +326,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) { @@ -365,7 +365,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; @@ -394,10 +394,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'); @@ -436,7 +437,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, [])); @@ -455,7 +456,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) { @@ -489,7 +490,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 { @@ -520,7 +521,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-beforeexit-event-exit.js b/test/parallel/test-beforeexit-event-exit.js index 67676a7990041f..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'); -var 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(); 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 eecb14abb06001..06a9044bec3103 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$/); @@ -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; @@ -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(''); @@ -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 22ba1e6b7e1735..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')); @@ -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'); @@ -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 746a2723167a60..33baed7ec8458d 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')); } @@ -434,7 +434,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')); @@ -485,16 +485,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-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); 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' -); 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-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 0abf1289f0737d..d33c7ae3acf626 100644 --- a/test/parallel/test-child-process-constructor.js +++ b/test/parallel/test-child-process-constructor.js @@ -1,13 +1,13 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var child_process = require('child_process'); -var ChildProcess = child_process.ChildProcess; +const assert = require('assert'); +const child_process = require('child_process'); +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 38a1b291b9967c..37e7ea7494670e 100644 --- a/test/parallel/test-child-process-default-options.js +++ b/test/parallel/test-child-process-default-options.js @@ -1,19 +1,19 @@ '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'; -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 2ebc653e9a067d..ad41f978e21768 100644 --- a/test/parallel/test-child-process-env.js +++ b/test/parallel/test-child-process-env.js @@ -1,17 +1,17 @@ '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 = { +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 3a393f126fbe13..9596a202223993 100644 --- a/test/parallel/test-child-process-exit-code.js +++ b/test/parallel/test-child-process-exit-code.js @@ -1,20 +1,20 @@ '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]); +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 8bdf006a743e0d..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; @@ -76,7 +76,7 @@ if (process.argv[2] === 'child') { serverPort, '127.0.0.1', function(err) { - if (err) throw err; + assert.ifError(err); } ); } diff --git a/test/parallel/test-child-process-fork-exec-argv.js b/test/parallel/test-child-process-fork-exec-argv.js index 5ccc17fb3fc7c4..97d1e21a2f6d7a 100644 --- a/test/parallel/test-child-process-fork-exec-argv.js +++ b/test/parallel/test-child-process-fork-exec-argv.js @@ -1,9 +1,9 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var child_process = require('child_process'); -var spawn = child_process.spawn; -var fork = child_process.fork; +const assert = require('assert'); +const child_process = require('child_process'); +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 e2f7e4b4d20eef..5af0184a21f55d 100644 --- a/test/parallel/test-child-process-fork-exec-path.js +++ b/test/parallel/test-child-process-fork-exec-path.js @@ -1,11 +1,11 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); -var fs = require('fs'); -var path = require('path'); -var msg = {test: 'this'}; -var nodePath = process.execPath; -var copyPath = path.join(common.tmpDir, 'node-copy.exe'); +const assert = require('assert'); +const fs = require('fs'); +const path = require('path'); +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,9 +23,9 @@ 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'; - 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-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 be1ee5d3a4145a..6d20f419049c7b 100644 --- a/test/parallel/test-child-process-fork-net2.js +++ b/test/parallel/test-child-process-fork-net2.js @@ -1,13 +1,13 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); -var fork = require('child_process').fork; -var net = require('net'); -var count = 12; +const assert = require('assert'); +const fork = require('child_process').fork; +const net = require('net'); +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 50a944e71ba83c..1f8816c0cfaf1c 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'); @@ -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 42c43ed8882b78..9f59aa344aa2c9 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'); @@ -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 a7d4a995a33700..bfc68e41dc95fb 100644 --- a/test/parallel/test-child-process-fork.js +++ b/test/parallel/test-child-process-fork.js @@ -1,10 +1,10 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); -var fork = require('child_process').fork; -var args = ['foo', 'bar']; +const assert = require('assert'); +const fork = require('child_process').fork; +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-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..d795b69d7ee0e5 100644 --- a/test/parallel/test-child-process-internal.js +++ b/test/parallel/test-child-process-internal.js @@ -1,11 +1,11 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); +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 @@ -18,8 +18,8 @@ if (process.argv[2] === 'child') { } else { - var fork = require('child_process').fork; - var child = fork(process.argv[1], ['child']); + const fork = require('child_process').fork; + 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 fb0b11f433130a..54037aea69feb2 100644 --- a/test/parallel/test-child-process-set-blocking.js +++ b/test/parallel/test-child-process-set-blocking.js @@ -1,11 +1,11 @@ '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; +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 50d4ae881ad880..3bfa9f5f7d5235 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') { @@ -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-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-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 4455b867e30108..6f5ea3dc83d107 100644 --- a/test/parallel/test-child-process-spawnsync-env.js +++ b/test/parallel/test-child-process-spawnsync-env.js @@ -1,13 +1,13 @@ '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); } 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-shell.js b/test/parallel/test-child-process-spawnsync-shell.js index 620a01c4532203..70483089245c74 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-child-process-spawnsync-timeout.js b/test/parallel/test-child-process-spawnsync-timeout.js index 122a65825949df..abebe41e6e9640 100644 --- a/test/parallel/test-child-process-spawnsync-timeout.js +++ b/test/parallel/test-child-process-spawnsync-timeout.js @@ -1,11 +1,11 @@ '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; +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 2ce7c66c2053e0..2623e2deeeee8a 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 @@ -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 dc3bb3e9aa9391..d2b64aeb30dd31 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(); @@ -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-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); +} diff --git a/test/parallel/test-cli-eval.js b/test/parallel/test-cli-eval.js index 0198a0f1beda48..b1f65b204cfbb9 100644 --- a/test/parallel/test-cli-eval.js +++ b/test/parallel/test-cli-eval.js @@ -14,34 +14,38 @@ 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', - function(err, stdout, stderr) { - assert.strictEqual(stdout, ''); - assert.strictEqual(stderr, ''); - }); + 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.strictEqual(stdout, ''); - assert.strictEqual(stderr, '42\n'); - }); + function(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) { - var cmd = nodejs + ' ' + s + ' '; + const cmd = nodejs + ' ' + s + ' '; child.exec(cmd + '42', - function(err, stdout, stderr) { - assert.strictEqual(stdout, '42\n'); - assert.strictEqual(stderr, ''); - }); + 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,55 +53,69 @@ 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) { - assert.strictEqual(stderr, ''); - assert.strictEqual(stdout.trim(), require('os').platform()); - }); + 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, ''); }); // "\\-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.ifError(err); + 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(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) { - assert.strictEqual(stdout, ''); - assert.strictEqual(stderr, ''); - }); + function(err, stdout, stderr) { + assert.ifError(err); + assert.strictEqual(stdout, ''); + assert.strictEqual(stderr, ''); + }); // Regression test for https://github.com/nodejs/node/issues/8534. { 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 4c2425d82d656b..15c5898a7d6f69 100644 --- a/test/parallel/test-cluster-disconnect-with-no-workers.js +++ b/test/parallel/test-cluster-disconnect-with-no-workers.js @@ -1,9 +1,9 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var cluster = require('cluster'); +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 88b6de2dde4230..a0936ef4b9d471 100644 --- a/test/parallel/test-cluster-eaddrinuse.js +++ b/test/parallel/test-cluster-eaddrinuse.js @@ -3,17 +3,17 @@ // 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]; +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 17b7af3d061926..55ea684f3b4ce3 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({ @@ -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-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-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 0587eecb4dd4b5..5b537bbe73a755 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) { @@ -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 1328483abb72df..10b0530b505a95 100644 --- a/test/parallel/test-cluster-rr-domain-listen.js +++ b/test/parallel/test-cluster-rr-domain-listen.js @@ -1,20 +1,19 @@ '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; if (cluster.isWorker) { - var d = domain.create(); + const 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) { - 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 fa3e1138248221..3fa64ac0b5d4d0 100644 --- a/test/parallel/test-cluster-send-deadlock.js +++ b/test/parallel/test-cluster-send-deadlock.js @@ -2,20 +2,20 @@ // 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(); + 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-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..25cff7cb33e0c1 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); @@ -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 66193203fdc665..5a92b988e61e5e 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) { @@ -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 ac32705106e03c..7a33721a9aba17 100644 --- a/test/parallel/test-cluster-worker-death.js +++ b/test/parallel/test-cluster-worker-death.js @@ -1,12 +1,12 @@ '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); } 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-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'); diff --git a/test/parallel/test-cluster-worker-destroy.js b/test/parallel/test-cluster-worker-destroy.js index ca3ac77e7b25cc..62000254247a1f 100644 --- a/test/parallel/test-cluster-worker-destroy.js +++ b/test/parallel/test-cluster-worker-destroy.js @@ -9,8 +9,8 @@ const common = require('../common'); const assert = require('assert'); -var cluster = require('cluster'); -var worker1, worker2; +const cluster = require('cluster'); +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 08bf456a735b7d..6c2e278f5e4639 100644 --- a/test/parallel/test-cluster-worker-events.js +++ b/test/parallel/test-cluster-worker-events.js @@ -1,13 +1,13 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var cluster = require('cluster'); +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-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-cluster-worker-forced-exit.js b/test/parallel/test-cluster-worker-forced-exit.js index 3e1f7905ee50d1..828188254724ae 100644 --- a/test/parallel/test-cluster-worker-forced-exit.js +++ b/test/parallel/test-cluster-worker-forced-exit.js @@ -1,9 +1,9 @@ '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; +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 985d15ce6475e6..8b2ad865899c60 100644 --- a/test/parallel/test-cluster-worker-isconnected.js +++ b/test/parallel/test-cluster-worker-isconnected.js @@ -1,10 +1,10 @@ '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(); + 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 90454cb86089a7..cd360ff248aa13 100644 --- a/test/parallel/test-cluster-worker-isdead.js +++ b/test/parallel/test-cluster-worker-isdead.js @@ -1,10 +1,10 @@ '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(); + 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 0cec652b68648c..9cfd8401a0c678 100644 --- a/test/parallel/test-cluster-worker-no-exit.js +++ b/test/parallel/test-cluster-worker-no-exit.js @@ -1,13 +1,13 @@ '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; -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 bdf60971fee5c1..d1a0d73678d67a 100644 --- a/test/parallel/test-cluster-worker-wait-server-close.js +++ b/test/parallel/test-cluster-worker-wait-server-close.js @@ -1,14 +1,14 @@ '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; +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-common.js b/test/parallel/test-common.js index 5ffe2c351503c1..17f41840e4ffa5 100644 --- a/test/parallel/test-common.js +++ b/test/parallel/test-common.js @@ -1,7 +1,15 @@ '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. 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\/$/); diff --git a/test/parallel/test-console-instance.js b/test/parallel/test-console-instance.js index 4d2727d96b1a55..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; -var 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) => {}; -var c = new Console(out, err); +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); }); diff --git a/test/parallel/test-console-not-call-toString.js b/test/parallel/test-console-not-call-toString.js index f152e33e98f087..0c1c209374ac17 100644 --- a/test/parallel/test-console-not-call-toString.js +++ b/test/parallel/test-console-not-call-toString.js @@ -1,9 +1,9 @@ 'use strict'; require('../common'); -var assert = require('assert'); +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-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-authenticated.js b/test/parallel/test-crypto-authenticated.js index 4bed5aa665b64d..245783fb1b4275 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; } @@ -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-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 1dfb2c73b0eca5..ebd83b019ba146 100644 --- a/test/parallel/test-crypto-certificate.js +++ b/test/parallel/test-crypto-certificate.js @@ -1,23 +1,23 @@ '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'); -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 cb8757efff0bde..f6bfcf72c0fd7e 100644 --- a/test/parallel/test-crypto-dh-odd-key.js +++ b/test/parallel/test-crypto-dh-odd-key.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 crypto = require('crypto'); +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 ec9985719933d3..6586f7d48a94ce 100644 --- a/test/parallel/test-crypto-domain.js +++ b/test/parallel/test-crypto-domain.js @@ -1,21 +1,21 @@ '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'); - 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 5d8caf37ee2f41..2749382fa5c780 100644 --- a/test/parallel/test-crypto-domains.js +++ b/test/parallel/test-crypto-domains.js @@ -1,15 +1,15 @@ 'use strict'; -var common = require('../common'); -var domain = require('domain'); -var assert = require('assert'); -var d = domain.create(); -var expect = ['pbkdf2', 'randomBytes', 'pseudoRandomBytes']; +const common = require('../common'); +const domain = require('domain'); +const assert = require('assert'); +const d = domain.create(); +const expect = ['pbkdf2', 'randomBytes', 'pseudoRandomBytes']; 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..6fd3352740c8c3 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'); @@ -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]; } @@ -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-from-binary.js b/test/parallel/test-crypto-from-binary.js index 0889541ef6e144..485735e83ce5cc 100644 --- a/test/parallel/test-crypto-from-binary.js +++ b/test/parallel/test-crypto-from-binary.js @@ -3,19 +3,19 @@ // 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; +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 9e212443453203..0d55d4236a656e 100644 --- a/test/parallel/test-crypto-hash.js +++ b/test/parallel/test-crypto-hash.js @@ -1,44 +1,44 @@ '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'); -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', @@ -67,18 +67,18 @@ 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'); -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,24 +94,24 @@ 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' + '43a821af66afa9a45b6a78c712fecf0e56dc7f43aef4bcfc8eb5b4d8dca6ea5b'); -assert.notEqual( +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(); }, - /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 5307ea4f6f9e05..f267e8203867c7 100644 --- a/test/parallel/test-crypto-hmac.js +++ b/test/parallel/test-crypto-hmac.js @@ -1,22 +1,22 @@ '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 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. @@ -75,7 +75,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' @@ -115,7 +115,7 @@ var rfc4231 = [ key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'), data: Buffer.from('ddddddddddddddddddddddddddddddddddddddddddddddddd' + 'ddddddddddddddddddddddddddddddddddddddddddddddddddd', - 'hex'), + 'hex'), hmac: { sha224: '7fb3cb3588c6c1f6ffa9694d7d6ad2649365b0c1f65d69d1ec8333ea', sha256: @@ -132,10 +132,10 @@ var rfc4231 = [ }, { key: Buffer.from('0102030405060708090a0b0c0d0e0f10111213141516171819', - 'hex'), + 'hex'), data: Buffer.from('cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdc' + 'dcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd', - 'hex'), + 'hex'), hmac: { sha224: '6c11506874013cac6a2abc1bb382627cec6a90d86efc012de7afec5a', sha256: @@ -241,7 +241,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', @@ -256,16 +256,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' }, { @@ -278,7 +278,7 @@ var rfc2202_md5 = [ 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaa', - 'hex'), + 'hex'), data: 'Test Using Larger Than Block-Size Key - Hash Key First', hmac: '6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd' }, @@ -287,14 +287,14 @@ var rfc2202_md5 = [ 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaa', - 'hex'), + 'hex'), data: 'Test Using Larger Than Block-Size Key and Larger Than One ' + 'Block-Size Data', hmac: '6f630fad67cda0ee1fb1f562db3aa53e' } ]; -var rfc2202_sha1 = [ +const rfc2202_sha1 = [ { key: Buffer.from('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'), data: 'Hi There', @@ -310,16 +310,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' }, { @@ -332,7 +332,7 @@ var rfc2202_sha1 = [ 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaa', - 'hex'), + 'hex'), data: 'Test Using Larger Than Block-Size Key - Hash Key First', hmac: 'aa4ae5e15272d00e95705637ce8a3b55ed402112' }, @@ -341,7 +341,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-padding-aes256.js b/test/parallel/test-crypto-padding-aes256.js index e835867d61d005..40bbfed0f2824f 100644 --- a/test/parallel/test-crypto-padding-aes256.js +++ b/test/parallel/test-crypto-padding-aes256.js @@ -1,28 +1,28 @@ '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'; 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'); diff --git a/test/parallel/test-crypto-rsa-dsa.js b/test/parallel/test-crypto-rsa-dsa.js index 396717ef742a95..bb529f2454dbc8 100644 --- a/test/parallel/test-crypto-rsa-dsa.js +++ b/test/parallel/test-crypto-rsa-dsa.js @@ -1,31 +1,34 @@ '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'); -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() { - var signOptions = { key: rsaKeyPemEncrypted, passphrase: 'password' }; +assert.doesNotThrow(() => { + const 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() { - var signOptions = { key: rsaKeyPemEncrypted, passphrase: 'wrong' }; +assert.throws(() => { + const 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'); }); diff --git a/test/parallel/test-crypto-sign-verify.js b/test/parallel/test-crypto-sign-verify.js index 6df41409f0e6c1..ae78cd9d8b3420 100644 --- a/test/parallel/test-crypto-sign-verify.js +++ b/test/parallel/test-crypto-sign-verify.js @@ -1,17 +1,17 @@ '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'); -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 1720cc7c4e0aea..f558851b7940a0 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) { @@ -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 fdc27215027414..c171814dd3c3a6 100644 --- a/test/parallel/test-crypto-verify-failure.js +++ b/test/parallel/test-crypto-verify-failure.js @@ -1,25 +1,25 @@ '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'); +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-crypto.js b/test/parallel/test-crypto.js index 13401e4ac594ab..2e94397c8f22f9 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,27 @@ 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()); + +// 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. diff --git a/test/parallel/test-cwd-enoent-repl.js b/test/parallel/test-cwd-enoent-repl.js index 1d03bd3e9112c1..942fc07b64a90b 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) { @@ -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 c671ef2be4619e..736121a7c89d6e 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) { @@ -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 abec53cbd3c83a..53f35877a2f382 100644 --- a/test/parallel/test-debug-port-from-cmdline.js +++ b/test/parallel/test-debug-port-from-cmdline.js @@ -1,17 +1,17 @@ '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]; -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-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..09c5ba31f6c5b5 100644 --- a/test/parallel/test-dgram-address.js +++ b/test/parallel/test-dgram-address.js @@ -1,14 +1,14 @@ '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'); -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 0bca97fb294f79..882f2e87bdd7ee 100644 --- a/test/parallel/test-dgram-bind.js +++ b/test/parallel/test-dgram-bind.js @@ -1,14 +1,14 @@ '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'); +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 8e2233e9c4daad..07a8bb0e43452b 100644 --- a/test/parallel/test-dgram-bytes-length.js +++ b/test/parallel/test-dgram-bytes-length.js @@ -1,10 +1,10 @@ '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'); +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 61e08200360452..d0f23d5808c7b7 100644 --- a/test/parallel/test-dgram-close-is-not-callback.js +++ b/test/parallel/test-dgram-close-is-not-callback.js @@ -1,10 +1,10 @@ 'use strict'; -var common = require('../common'); -var dgram = require('dgram'); +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 8cbb3f771e2d47..bfc86803b463f1 100644 --- a/test/parallel/test-dgram-implicit-bind.js +++ b/test/parallel/test-dgram-implicit-bind.js @@ -1,10 +1,10 @@ 'use strict'; const common = require('../common'); -var dgram = require('dgram'); +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 498a17a0e5b053..e60687649cda30 100644 --- a/test/parallel/test-dgram-listen-after-bind.js +++ b/test/parallel/test-dgram-listen-after-bind.js @@ -1,14 +1,14 @@ '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'); +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-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-oob-buffer.js b/test/parallel/test-dgram-oob-buffer.js index e52bf7d69b3c6f..247a35588c3ff7 100644 --- a/test/parallel/test-dgram-oob-buffer.js +++ b/test/parallel/test-dgram-oob-buffer.js @@ -3,11 +3,11 @@ // 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]); +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-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..b4ec8195d7e7f0 100644 --- a/test/parallel/test-dgram-regress-4496.js +++ b/test/parallel/test-dgram-regress-4496.js @@ -2,11 +2,11 @@ // 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'); +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 a3918697addc4e..c7ec6b51eecfa8 100644 --- a/test/parallel/test-dgram-send-bad-arguments.js +++ b/test/parallel/test-dgram-send-bad-arguments.js @@ -1,11 +1,11 @@ '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'; -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..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() { - var result = socket.setTTL(16); +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(); -}); +})); diff --git a/test/parallel/test-dgram-unref.js b/test/parallel/test-dgram-unref.js index e5f26b6f3387b8..ee463d7ab8da77 100644 --- a/test/parallel/test-dgram-unref.js +++ b/test/parallel/test-dgram-unref.js @@ -1,8 +1,8 @@ 'use strict'; const common = require('../common'); -var dgram = require('dgram'); +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 a9cd95225abedb..1d9d47ec0e10a3 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: @@ -45,7 +45,7 @@ try { * } */ -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 deleted file mode 100644 index 212f037868309e..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(() => { - var 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; +}); 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-abort-on-uncaught.js b/test/parallel/test-domain-abort-on-uncaught.js index d61debc06067f6..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() { @@ -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!'); }); @@ -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-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..4a11c3a206a5fe 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) { @@ -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 b1911bb40e0c93..542950f8af428e 100644 --- a/test/parallel/test-domain-exit-dispose-again.js +++ b/test/parallel/test-domain-exit-dispose-again.js @@ -6,22 +6,22 @@ // the same invocation of listOnTimeout, _are_ called. require('../common'); -var assert = require('assert'); -var domain = require('domain'); -var disposalFailed = false; +const assert = require('assert'); +const domain = require('domain'); +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 508cec18dccb7d..e1797cb660a0c0 100644 --- a/test/parallel/test-domain-exit-dispose.js +++ b/test/parallel/test-domain-exit-dispose.js @@ -1,11 +1,11 @@ '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; +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 26264e8ec987d8..d8bb5c843662b8 100644 --- a/test/parallel/test-domain-http-server.js +++ b/test/parallel/test-domain-http-server.js @@ -1,17 +1,17 @@ '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] }; +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 a92653aff1de1c..265d291f61941b 100644 --- a/test/parallel/test-domain-implicit-fs.js +++ b/test/parallel/test-domain-implicit-fs.js @@ -2,10 +2,10 @@ // 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(); +const d = new domain.Domain(); d.on('error', common.mustCall(function(er) { console.error('caught', er); @@ -28,10 +28,10 @@ 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) { - if (er) throw er; + assert.ifError(er); throw new Error('should not get here!'); }); }); diff --git a/test/parallel/test-domain-multi.js b/test/parallel/test-domain-multi.js index cf85dbca460146..a38b6a2bc42bdf 100644 --- a/test/parallel/test-domain-multi.js +++ b/test/parallel/test-domain-multi.js @@ -1,28 +1,18 @@ 'use strict'; // Tests of multiple domains happening at once. -require('../common'); -var assert = require('assert'); -var domain = require('domain'); +const common = require('../common'); +const domain = require('domain'); +const http = require('http'); -var caughtA = false; -var caughtB = false; -var 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; - console.log('This should not happen'); - throw er; -}); +a.on('error', common.fail); -var http = require('http'); -var server = http.createServer(function(req, res) { +const server = http.createServer((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 @@ -31,47 +21,34 @@ var 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() { - var c = domain.create(); - var req = http.get({ host: 'localhost', port: this.address().port }); +}).listen(0, () => { + const c = domain.create(); + 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) => { })); }); diff --git a/test/parallel/test-domain-nested-throw.js b/test/parallel/test-domain-nested-throw.js index 69a80b7ab104d0..39507446a3acfc 100644 --- a/test/parallel/test-domain-nested-throw.js +++ b/test/parallel/test-domain-nested-throw.js @@ -1,10 +1,10 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); -var domain = require('domain'); +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; - var spawn = require('child_process').spawn; - var opt = { stdio: 'inherit' }; - var child = spawn(node, [__filename, 'true'], opt); + const node = process.execPath; + const spawn = require('child_process').spawn; + 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-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-0.js b/test/parallel/test-domain-no-error-handler-abort-on-uncaught-0.js new file mode 100644 index 00000000000000..6a3a670b9204c2 --- /dev/null +++ b/test/parallel/test-domain-no-error-handler-abort-on-uncaught-0.js @@ -0,0 +1,18 @@ +'use strict'; + +const common = require('../common'); +const domain = require('domain'); + +function test() { + const d = domain.create(); + + d.run(function() { + throw new Error('boom!'); + }); +} + +if (process.argv[2] === 'child') { + test(); +} else { + common.childShouldThrowAndAbort(); +} diff --git a/test/parallel/test-domain-no-error-handler-abort-on-uncaught-1.js b/test/parallel/test-domain-no-error-handler-abort-on-uncaught-1.js new file mode 100644 index 00000000000000..e32245176571ef --- /dev/null +++ b/test/parallel/test-domain-no-error-handler-abort-on-uncaught-1.js @@ -0,0 +1,21 @@ +'use strict'; + +const common = require('../common'); +const domain = require('domain'); + +function test() { + const d = domain.create(); + const d2 = domain.create(); + + d.run(function() { + d2.run(function() { + throw new Error('boom!'); + }); + }); +} + +if (process.argv[2] === 'child') { + test(); +} else { + common.childShouldThrowAndAbort(); +} diff --git a/test/parallel/test-domain-no-error-handler-abort-on-uncaught-2.js b/test/parallel/test-domain-no-error-handler-abort-on-uncaught-2.js new file mode 100644 index 00000000000000..ff0fd5eec35f6b --- /dev/null +++ b/test/parallel/test-domain-no-error-handler-abort-on-uncaught-2.js @@ -0,0 +1,20 @@ +'use strict'; + +const common = require('../common'); +const domain = require('domain'); + +function test() { + const d = domain.create(); + + d.run(function() { + setTimeout(function() { + throw new Error('boom!'); + }, 1); + }); +} + +if (process.argv[2] === 'child') { + test(); +} else { + common.childShouldThrowAndAbort(); +} diff --git a/test/parallel/test-domain-no-error-handler-abort-on-uncaught-3.js b/test/parallel/test-domain-no-error-handler-abort-on-uncaught-3.js new file mode 100644 index 00000000000000..cbe5f3ed8dc4a1 --- /dev/null +++ b/test/parallel/test-domain-no-error-handler-abort-on-uncaught-3.js @@ -0,0 +1,20 @@ +'use strict'; + +const common = require('../common'); +const domain = require('domain'); + +function test() { + const d = domain.create(); + + d.run(function() { + setImmediate(function() { + throw new Error('boom!'); + }); + }); +} + +if (process.argv[2] === 'child') { + test(); +} else { + common.childShouldThrowAndAbort(); +} diff --git a/test/parallel/test-domain-no-error-handler-abort-on-uncaught-4.js b/test/parallel/test-domain-no-error-handler-abort-on-uncaught-4.js new file mode 100644 index 00000000000000..4d0dd39454d2b2 --- /dev/null +++ b/test/parallel/test-domain-no-error-handler-abort-on-uncaught-4.js @@ -0,0 +1,20 @@ +'use strict'; + +const common = require('../common'); +const domain = require('domain'); + +function test() { + const d = domain.create(); + + d.run(function() { + process.nextTick(function() { + throw new Error('boom!'); + }); + }); +} + +if (process.argv[2] === 'child') { + test(); +} else { + common.childShouldThrowAndAbort(); +} 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 new file mode 100644 index 00000000000000..ade72147e148e7 --- /dev/null +++ b/test/parallel/test-domain-no-error-handler-abort-on-uncaught-5.js @@ -0,0 +1,21 @@ +'use strict'; + +const common = require('../common'); +const domain = require('domain'); + +function test() { + const d = domain.create(); + + d.run(function() { + const fs = require('fs'); + fs.exists('/non/existing/file', function onExists() { + throw new Error('boom!'); + }); + }); +} + +if (process.argv[2] === 'child') { + test(); +} else { + common.childShouldThrowAndAbort(); +} diff --git a/test/parallel/test-domain-no-error-handler-abort-on-uncaught-6.js b/test/parallel/test-domain-no-error-handler-abort-on-uncaught-6.js new file mode 100644 index 00000000000000..c3a91379319db5 --- /dev/null +++ b/test/parallel/test-domain-no-error-handler-abort-on-uncaught-6.js @@ -0,0 +1,26 @@ +'use strict'; + +const common = require('../common'); +const domain = require('domain'); + +function test() { + const d = domain.create(); + const d2 = domain.create(); + + d.on('error', function errorHandler() { + }); + + d.run(function() { + d2.run(function() { + setTimeout(function() { + throw new Error('boom!'); + }, 1); + }); + }); +} + +if (process.argv[2] === 'child') { + test(); +} else { + common.childShouldThrowAndAbort(); +} diff --git a/test/parallel/test-domain-no-error-handler-abort-on-uncaught-7.js b/test/parallel/test-domain-no-error-handler-abort-on-uncaught-7.js new file mode 100644 index 00000000000000..9debc754cea3d1 --- /dev/null +++ b/test/parallel/test-domain-no-error-handler-abort-on-uncaught-7.js @@ -0,0 +1,26 @@ +'use strict'; + +const common = require('../common'); +const domain = require('domain'); + +function test() { + const d = domain.create(); + const d2 = domain.create(); + + d.on('error', function errorHandler() { + }); + + d.run(function() { + d2.run(function() { + setImmediate(function() { + throw new Error('boom!'); + }); + }); + }); +} + +if (process.argv[2] === 'child') { + test(); +} else { + common.childShouldThrowAndAbort(); +} diff --git a/test/parallel/test-domain-no-error-handler-abort-on-uncaught-8.js b/test/parallel/test-domain-no-error-handler-abort-on-uncaught-8.js new file mode 100644 index 00000000000000..f1670cbd300bdf --- /dev/null +++ b/test/parallel/test-domain-no-error-handler-abort-on-uncaught-8.js @@ -0,0 +1,26 @@ +'use strict'; + +const common = require('../common'); +const domain = require('domain'); + +function test() { + const d = domain.create(); + const d2 = domain.create(); + + d.on('error', function errorHandler() { + }); + + d.run(function() { + d2.run(function() { + process.nextTick(function() { + throw new Error('boom!'); + }); + }); + }); +} + +if (process.argv[2] === 'child') { + test(); +} else { + common.childShouldThrowAndAbort(); +} 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 new file mode 100644 index 00000000000000..2e86a2125e86ee --- /dev/null +++ b/test/parallel/test-domain-no-error-handler-abort-on-uncaught-9.js @@ -0,0 +1,27 @@ +'use strict'; + +const common = require('../common'); +const domain = require('domain'); + +function test() { + const d = domain.create(); + const d2 = domain.create(); + + d.on('error', function errorHandler() { + }); + + d.run(function() { + d2.run(function() { + const fs = require('fs'); + fs.exists('/non/existing/file', function onExists() { + throw new Error('boom!'); + }); + }); + }); +} + +if (process.argv[2] === 'child') { + test(); +} else { + common.childShouldThrowAndAbort(); +} diff --git a/test/parallel/test-domain-no-error-handler-abort-on-uncaught.js b/test/parallel/test-domain-no-error-handler-abort-on-uncaught.js deleted file mode 100644 index 833e7374d7f2ab..00000000000000 --- a/test/parallel/test-domain-no-error-handler-abort-on-uncaught.js +++ /dev/null @@ -1,168 +0,0 @@ -'use strict'; - -/* - * This test makes sure that when using --abort-on-uncaught-exception and - * when throwing an error from within a domain that does not have an error - * handler setup, the process aborts. - */ -const common = require('../common'); -const assert = require('assert'); -const domain = require('domain'); -const child_process = require('child_process'); - -const tests = [ - function() { - const d = domain.create(); - - d.run(function() { - throw new Error('boom!'); - }); - }, - - function() { - const d = domain.create(); - const d2 = domain.create(); - - d.run(function() { - d2.run(function() { - throw new Error('boom!'); - }); - }); - }, - - function() { - const d = domain.create(); - - d.run(function() { - setTimeout(function() { - throw new Error('boom!'); - }, 1); - }); - }, - - function() { - const d = domain.create(); - - d.run(function() { - setImmediate(function() { - throw new Error('boom!'); - }); - }); - }, - - function() { - const d = domain.create(); - - d.run(function() { - process.nextTick(function() { - throw new Error('boom!'); - }); - }); - }, - - function() { - const d = domain.create(); - - d.run(function() { - var fs = require('fs'); - fs.exists('/non/existing/file', function onExists() { - throw new Error('boom!'); - }); - }); - }, - - function() { - const d = domain.create(); - const d2 = domain.create(); - - d.on('error', function errorHandler() { - }); - - d.run(function() { - d2.run(function() { - setTimeout(function() { - throw new Error('boom!'); - }, 1); - }); - }); - }, - - function() { - const d = domain.create(); - const d2 = domain.create(); - - d.on('error', function errorHandler() { - }); - - d.run(function() { - d2.run(function() { - setImmediate(function() { - throw new Error('boom!'); - }); - }); - }); - }, - - function() { - const d = domain.create(); - const d2 = domain.create(); - - d.on('error', function errorHandler() { - }); - - d.run(function() { - d2.run(function() { - process.nextTick(function() { - throw new Error('boom!'); - }); - }); - }); - }, - - function() { - const d = domain.create(); - const d2 = domain.create(); - - d.on('error', function errorHandler() { - }); - - d.run(function() { - d2.run(function() { - var fs = require('fs'); - fs.exists('/non/existing/file', function onExists() { - throw new Error('boom!'); - }); - }); - }); - }, -]; - -if (process.argv[2] === 'child') { - const testIndex = +process.argv[3]; - tests[testIndex](); -} else { - - tests.forEach(function(test, testIndex) { - var testCmd = ''; - if (!common.isWindows) { - // Do not create core files, as it can take a lot of disk space on - // continuous testing and developers' machines - testCmd += 'ulimit -c 0 && '; - } - - testCmd += process.argv[0]; - testCmd += ' ' + '--abort-on-uncaught-exception'; - testCmd += ' ' + process.argv[1]; - testCmd += ' ' + 'child'; - testCmd += ' ' + testIndex; - - var child = child_process.exec(testCmd); - - child.on('exit', function onExit(exitCode, signal) { - const errMsg = 'Test at index ' + testIndex + ' should have aborted ' + - 'but instead exited with exit code ' + exitCode + - ' and signal ' + signal; - assert(common.nodeProcessAborted(exitCode, signal), errMsg); - }); - }); -} diff --git a/test/parallel/test-domain-safe-exit.js b/test/parallel/test-domain-safe-exit.js index 399ae37bcd94c5..bbc3b2fe22cae8 100644 --- a/test/parallel/test-domain-safe-exit.js +++ b/test/parallel/test-domain-safe-exit.js @@ -2,11 +2,11 @@ // 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(); +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 e30d3b21f3af57..43152a4a3bb1c9 100644 --- a/test/parallel/test-domain-stack.js +++ b/test/parallel/test-domain-stack.js @@ -2,9 +2,9 @@ // 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(); +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 fc6a93ccdca8ef..c106e40e27b2d3 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,38 +49,40 @@ 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'); + 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'); - }); + assert.notStrictEqual(err.code, 0, + 'child process should have exited with a ' + + 'non-zero exit code, but did not'); + } + ); } 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'); }); } 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 d42afa7471791a..79bd300545bf96 100644 --- a/test/parallel/test-domain-timers.js +++ b/test/parallel/test-domain-timers.js @@ -1,11 +1,9 @@ 'use strict'; const common = require('../common'); -var domain = require('domain'); -var assert = require('assert'); +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 b65b94012393c6..53a73eac426232 100644 --- a/test/parallel/test-domain-top-level-error-handler-throw.js +++ b/test/parallel/test-domain-top-level-error-handler-throw.js @@ -13,8 +13,8 @@ const domainErrHandlerExMessage = 'exception from domain error handler'; const internalExMessage = 'You should NOT see me'; if (process.argv[2] === 'child') { - var domain = require('domain'); - var d = domain.create(); + const domain = require('domain'); + const d = domain.create(); d.on('error', function() { throw new Error(domainErrHandlerExMessage); @@ -26,11 +26,11 @@ 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 = ''; + 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 6fb3912e5b8d9c..0da8f1368f7c98 100644 --- a/test/parallel/test-domain-with-abort-on-uncaught-exception.js +++ b/test/parallel/test-domain-with-abort-on-uncaught-exception.js @@ -29,8 +29,8 @@ const fs = require('fs'); const domainErrHandlerExMessage = 'exception from domain error handler'; if (process.argv[2] === 'child') { - var domain = require('domain'); - var d = domain.create(); + const domain = require('domain'); + const d = domain.create(); process.on('uncaughtException', function onUncaughtException() { // The process' uncaughtException event must not be emitted when @@ -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') { @@ -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 ede3adab66c527..6055a9b4c47862 100644 --- a/test/parallel/test-dsa-fips-invalid-key.js +++ b/test/parallel/test-dsa-fips-invalid-key.js @@ -1,20 +1,20 @@ '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'; +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 62525a5494d5a0..fa7332a67a482b 100644 --- a/test/parallel/test-error-reporting.js +++ b/test/parallel/test-error-reporting.js @@ -1,12 +1,12 @@ '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] + '" "' + - 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 3effb999b37e8c..2b4a93ae9808df 100644 --- a/test/parallel/test-event-emitter-errors.js +++ b/test/parallel/test-event-emitter-errors.js @@ -1,9 +1,9 @@ 'use strict'; require('../common'); -var EventEmitter = require('events'); -var assert = require('assert'); +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 34ffee3600e5e9..9acc71fd7920e3 100644 --- a/test/parallel/test-event-emitter-get-max-listeners.js +++ b/test/parallel/test-event-emitter-get-max-listeners.js @@ -1,9 +1,9 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var EventEmitter = require('events'); +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 906138af2367c3..022750da406500 100644 --- a/test/parallel/test-event-emitter-listeners-side-effects.js +++ b/test/parallel/test-event-emitter-listeners-side-effects.js @@ -1,12 +1,12 @@ '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 +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 e268e229b06b5b..d0464b80a44fe1 100644 --- a/test/parallel/test-event-emitter-method-names.js +++ b/test/parallel/test-event-emitter-method-names.js @@ -1,9 +1,9 @@ '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; +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-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); 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..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 @@ -1,11 +1,11 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); -var events = require('events'); -var domain = require('domain'); -var e = new events.EventEmitter(); +const assert = require('assert'); +const events = require('events'); +const domain = require('domain'); +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 d858692aad338e..d1027befa3f4ad 100644 --- a/test/parallel/test-event-emitter-num-args.js +++ b/test/parallel/test-event-emitter-num-args.js @@ -1,13 +1,13 @@ '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 = []; 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 e32a0e3f94f5b4..38f9b7101eb775 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); } { @@ -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 cadaf3adc36014..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 @@ -1,9 +1,9 @@ '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(); +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 d2651defeeaa23..d35802b413136b 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); @@ -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 e0e1b0086d9a7f..506fbaed0ebf63 100644 --- a/test/parallel/test-exception-handler.js +++ b/test/parallel/test-exception-handler.js @@ -1,8 +1,8 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); +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 6da26fe47beb92..4157f92f8b9021 100644 --- a/test/parallel/test-fs-access.js +++ b/test/parallel/test-fs-access.js @@ -1,13 +1,13 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var fs = require('fs'); -var 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'); - -var removeFile = function(file) { +const common = require('../common'); +const assert = require('assert'); +const fs = require('fs'); +const path = require('path'); +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'); + +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) { - assert.notEqual(err, null, 'error should exist'); +fs.access(doesNotExist, common.mustCall((err) => { + assert.notStrictEqual(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.notStrictEqual(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() { - var mode = fs.F_OK | fs.R_OK | fs.W_OK; +assert.doesNotThrow(() => { + const 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); }); diff --git a/test/parallel/test-fs-buffer.js b/test/parallel/test-fs-buffer.js index 6f142310f5e418..1452143a91c238 100644 --- a/test/parallel/test-fs-buffer.js +++ b/test/parallel/test-fs-buffer.js @@ -9,14 +9,14 @@ common.refreshTmpDir(); assert.doesNotThrow(() => { fs.access(Buffer.from(common.tmpDir), common.mustCall((err) => { - if (err) throw err; + assert.ifError(err); })); }); assert.doesNotThrow(() => { const buf = Buffer.from(path.join(common.tmpDir, 'a.txt')); fs.open(buf, 'w+', common.mustCall((err, fd) => { - if (err) throw err; + assert.ifError(err); assert(fd); fs.close(fd, common.mustCall(() => { fs.unlinkSync(buf); @@ -30,12 +30,12 @@ assert.throws(() => { const dir = Buffer.from(common.fixturesDir); fs.readdir(dir, 'hex', common.mustCall((err, list) => { - if (err) throw err; + assert.ifError(err); list = list.map((i) => { return Buffer.from(i, 'hex').toString(); }); fs.readdir(dir, common.mustCall((err, list2) => { - if (err) throw err; + assert.ifError(err); assert.deepStrictEqual(list, list2); })); })); 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 83e6adaf1100f7..14e1446f5a6d3d 100644 --- a/test/parallel/test-fs-exists.js +++ b/test/parallel/test-fs-exists.js @@ -1,8 +1,8 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); -var fs = require('fs'); -var f = __filename; +const assert = require('assert'); +const fs = require('fs'); +const f = __filename; fs.exists(f, common.mustCall(function(y) { assert.strictEqual(y, true); diff --git a/test/parallel/test-fs-link.js b/test/parallel/test-fs-link.js index 2cba47bfec83df..d110ff80fe0341 100644 --- a/test/parallel/test-fs-link.js +++ b/test/parallel/test-fs-link.js @@ -12,7 +12,7 @@ const dstPath = path.join(common.tmpDir, 'link1.js'); fs.writeFileSync(srcPath, 'hello world'); const callback = function(err) { - if (err) throw err; + assert.ifError(err); const dstContent = fs.readFileSync(dstPath, 'utf8'); assert.strictEqual('hello world', dstContent); }; diff --git a/test/parallel/test-fs-long-path.js b/test/parallel/test-fs-long-path.js index 64585467ed6a77..7082e740ed47c9 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.'); @@ -9,9 +9,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-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-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-null-bytes.js b/test/parallel/test-fs-null-bytes.js index 3c70d2953ca0f4..fa29e64c9b2382 100644 --- a/test/parallel/test-fs-null-bytes.js +++ b/test/parallel/test-fs-null-bytes.js @@ -1,19 +1,18 @@ '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) { - 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')); diff --git a/test/parallel/test-fs-open-flags.js b/test/parallel/test-fs-open-flags.js index ce7eaad580c008..e15d36c249692e 100644 --- a/test/parallel/test-fs-open-flags.js +++ b/test/parallel/test-fs-open-flags.js @@ -1,17 +1,17 @@ // 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; -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-options-immutable.js b/test/parallel/test-fs-options-immutable.js index 47796a94a5e79e..185d14c4721d74 100644 --- a/test/parallel/test-fs-options-immutable.js +++ b/test/parallel/test-fs-options-immutable.js @@ -29,7 +29,7 @@ common.refreshTmpDir(); assert.doesNotThrow(() => fs.readdirSync(__dirname, options)); } -{ +if (common.canCreateSymLink()) { const sourceFile = path.resolve(common.tmpDir, 'test-readlink'); const linkFile = path.resolve(common.tmpDir, 'test-readlink-link'); 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-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-fd.js b/test/parallel/test-fs-read-stream-fd.js index 5af5200e30eb68..a9ff56ee93fd91 100644 --- a/test/parallel/test-fs-read-stream-fd.js +++ b/test/parallel/test-fs-read-stream-fd.js @@ -1,23 +1,22 @@ 'use strict'; const common = require('../common'); -var fs = require('fs'); -var assert = require('assert'); -var path = require('path'); -var file = path.join(common.tmpDir, '/read_stream_fd_test.txt'); -var input = 'hello world'; -var output = ''; -var fd, stream; +const fs = require('fs'); +const assert = require('assert'); +const path = require('path'); +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); }); 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-readdir-ucs2.js b/test/parallel/test-fs-readdir-ucs2.js index 916758fe943f86..53b16de4b9bea0 100644 --- a/test/parallel/test-fs-readdir-ucs2.js +++ b/test/parallel/test-fs-readdir-ucs2.js @@ -19,7 +19,7 @@ const fullpath = Buffer.concat([root, filebuff]); fs.closeSync(fs.openSync(fullpath, 'w+')); fs.readdir(common.tmpDir, 'ucs2', (err, list) => { - if (err) throw err; + assert.ifError(err); assert.equal(1, list.length); const fn = list[0]; assert.deepStrictEqual(filebuff, Buffer.from(fn, 'ucs2')); diff --git a/test/parallel/test-fs-readfile-fd-offset.js b/test/parallel/test-fs-readfile-fd-offset.js new file mode 100644 index 00000000000000..0a02685319369e --- /dev/null +++ b/test/parallel/test-fs-readfile-fd-offset.js @@ -0,0 +1,23 @@ +'use strict'; +const common = require('../common'); +const assert = require('assert'); +const fs = require('fs'); +const path = require('path'); + +const filename = path.join(common.tmpDir, 'readfile.txt'); +const dataExpected = 'a'.repeat(100); +fs.writeFileSync(filename, dataExpected); +const fileLength = dataExpected.length; + +['r', 'a+'].forEach((mode) => { + const fd = fs.openSync(filename, mode); + assert.strictEqual(fs.readFileSync(fd).length, fileLength); + + // Reading again should result in the same length. + assert.strictEqual(fs.readFileSync(fd).length, fileLength); + + fs.readFile(fd, common.mustCall((err, buf) => { + assert.ifError(err); + assert.strictEqual(buf.length, fileLength); + })); +}); diff --git a/test/parallel/test-fs-readfile-fd.js b/test/parallel/test-fs-readfile-fd.js index 6420dbfdd004e5..85fc6ebef5235d 100644 --- a/test/parallel/test-fs-readfile-fd.js +++ b/test/parallel/test-fs-readfile-fd.js @@ -29,18 +29,17 @@ tempFdSync(function(fd) { function tempFd(callback) { fs.open(fn, 'r', function(err, fd) { - if (err) throw err; - + assert.ifError(err); callback(fd, function() { fs.close(fd, function(err) { - if (err) throw err; + assert.ifError(err); }); }); }); } 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-readfile-pipe-large.js b/test/parallel/test-fs-readfile-pipe-large.js index 1b1523cb132e4c..926cc318c4f63a 100644 --- a/test/parallel/test-fs-readfile-pipe-large.js +++ b/test/parallel/test-fs-readfile-pipe-large.js @@ -14,7 +14,7 @@ const fs = require('fs'); if (process.argv[2] === 'child') { fs.readFile('/dev/stdin', function(er, data) { - if (er) throw er; + assert.ifError(er); process.stdout.write(data); }); return; @@ -30,8 +30,7 @@ const f = JSON.stringify(__filename); const node = JSON.stringify(process.execPath); const cmd = `cat ${filename} | ${node} ${f} child`; exec(cmd, { maxBuffer: 1000000 }, function(err, stdout, stderr) { - if (err) console.error(err); - assert(!err, 'it exits normally'); + assert.ifError(err); assert.strictEqual(stdout, dataExpected, 'it reads the file and outputs it'); assert.strictEqual(stderr, '', 'it does not write to stderr'); console.log('ok'); diff --git a/test/parallel/test-fs-readfile-pipe.js b/test/parallel/test-fs-readfile-pipe.js index 54fb1fbe104fae..91465a261c8f96 100644 --- a/test/parallel/test-fs-readfile-pipe.js +++ b/test/parallel/test-fs-readfile-pipe.js @@ -26,8 +26,7 @@ const f = JSON.stringify(__filename); const node = JSON.stringify(process.execPath); const cmd = `cat ${f} | ${node} ${f} child`; exec(cmd, function(err, stdout, stderr) { - if (err) console.error(err); - assert(!err, 'it exits normally'); + assert.ifError(err); assert.strictEqual(stdout, dataExpected, 'it reads the file and outputs it'); assert.strictEqual(stderr, '', 'it does not write to stderr'); console.log('ok'); diff --git a/test/parallel/test-fs-readfile-zero-byte-liar.js b/test/parallel/test-fs-readfile-zero-byte-liar.js index 283a986f8a038a..82037a77e62122 100644 --- a/test/parallel/test-fs-readfile-zero-byte-liar.js +++ b/test/parallel/test-fs-readfile-zero-byte-liar.js @@ -1,31 +1,31 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); -var fs = require('fs'); +const assert = require('assert'); +const 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); })); diff --git a/test/parallel/test-fs-readfilesync-pipe-large.js b/test/parallel/test-fs-readfilesync-pipe-large.js index 9108118b87e2e6..e791618b4999fe 100644 --- a/test/parallel/test-fs-readfilesync-pipe-large.js +++ b/test/parallel/test-fs-readfilesync-pipe-large.js @@ -27,8 +27,7 @@ const f = JSON.stringify(__filename); const node = JSON.stringify(process.execPath); const cmd = `cat ${filename} | ${node} ${f} child`; exec(cmd, { maxBuffer: 1000000 }, function(err, stdout, stderr) { - if (err) console.error(err); - assert(!err, 'it exits normally'); + assert.ifError(err); assert.strictEqual(stdout, dataExpected, 'it reads the file and outputs it'); assert.strictEqual(stderr, '', 'it does not write to stderr'); console.log('ok'); diff --git a/test/parallel/test-fs-realpath-buffer-encoding.js b/test/parallel/test-fs-realpath-buffer-encoding.js index 78ec02549bbd27..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; @@ -50,39 +51,39 @@ for (encoding in expected) { const expected_value = expected[encoding]; fs.realpath(string_dir, {encoding: encoding}, common.mustCall((err, res) => { - assert(!err); + assert.ifError(err); assert.strictEqual(res, expected_value); })); fs.realpath(string_dir, encoding, common.mustCall((err, res) => { - assert(!err); + assert.ifError(err); assert.strictEqual(res, expected_value); })); fs.realpath(buffer_dir, {encoding: encoding}, common.mustCall((err, res) => { - assert(!err); + assert.ifError(err); assert.strictEqual(res, expected_value); })); fs.realpath(buffer_dir, encoding, common.mustCall((err, res) => { - assert(!err); + assert.ifError(err); assert.strictEqual(res, expected_value); })); } fs.realpath(string_dir, {encoding: 'buffer'}, common.mustCall((err, res) => { - assert(!err); + assert.ifError(err); assert.deepStrictEqual(res, buffer_dir); })); fs.realpath(string_dir, 'buffer', common.mustCall((err, res) => { - assert(!err); + assert.ifError(err); assert.deepStrictEqual(res, buffer_dir); })); fs.realpath(buffer_dir, {encoding: 'buffer'}, common.mustCall((err, res) => { - assert(!err); + assert.ifError(err); assert.deepStrictEqual(res, buffer_dir); })); fs.realpath(buffer_dir, 'buffer', common.mustCall((err, res) => { - assert(!err); + assert.ifError(err); assert.deepStrictEqual(res, buffer_dir); })); diff --git a/test/parallel/test-fs-realpath-on-substed-drive.js b/test/parallel/test-fs-realpath-on-substed-drive.js index c9109362691845..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) @@ -42,12 +43,12 @@ assert(Buffer.isBuffer(result)); assert(result.equals(filenameBuffer)); fs.realpath(filename, common.mustCall(function(err, result) { - assert(!err); + assert.ifError(err); assert.strictEqual(result, filename); })); fs.realpath(filename, 'buffer', common.mustCall(function(err, result) { - assert(!err); + assert.ifError(err); assert(Buffer.isBuffer(result)); assert(result.equals(filenameBuffer)); })); diff --git a/test/parallel/test-fs-realpath.js b/test/parallel/test-fs-realpath.js index dcaf8177c9499c..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); @@ -137,13 +138,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 +171,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); @@ -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'); @@ -237,7 +238,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 +293,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 +362,7 @@ function test_up_multiple(cb) { } function cleanup() { ['a/b', - 'a' + 'a' ].forEach(function(folder) { try { fs.rmdirSync(tmp(folder)); } catch (ex) {} }); @@ -386,10 +387,10 @@ function test_up_multiple(cb) { assertEqualPath(fs.realpathSync(abedabeda), abedabeda_real); assertEqualPath(fs.realpathSync(abedabed), abedabed_real); fs.realpath(abedabeda, function(er, real) { - if (er) throw er; + assert.ifError(er); assertEqualPath(abedabeda_real, real); fs.realpath(abedabed, function(er, real) { - if (er) throw er; + assert.ifError(er); assertEqualPath(abedabed_real, real); cb(); cleanup(); @@ -418,14 +419,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 +434,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); @@ -474,9 +475,9 @@ const tests = [ test_up_multiple ]; const numtests = tests.length; -var testsRun = 0; +let testsRun = 0; function runNextTest(err) { - if (err) throw err; + assert.ifError(err); const test = tests.shift(); if (!test) { return console.log(numtests + diff --git a/test/parallel/test-fs-sir-writes-alot.js b/test/parallel/test-fs-sir-writes-alot.js index 8e1385ed4da2a0..7bf97ff1d5cba3 100644 --- a/test/parallel/test-fs-sir-writes-alot.js +++ b/test/parallel/test-fs-sir-writes-alot.js @@ -1,36 +1,38 @@ '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'); +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 2c844452f05540..32ba47c2fe0c1e 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); @@ -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-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..9244dd20b4349c 100644 --- a/test/parallel/test-fs-symlink-dir-junction-relative.js +++ b/test/parallel/test-fs-symlink-dir-junction-relative.js @@ -1,15 +1,15 @@ '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'); -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 ab52ba22923f3d..c8c6fc933d367b 100644 --- a/test/parallel/test-fs-symlink.js +++ b/test/parallel/test-fs-symlink.js @@ -3,20 +3,13 @@ const common = require('../common'); const assert = require('assert'); const path = require('path'); const fs = require('fs'); -const exec = require('child_process').exec; - -var linkTime; -var fileTime; - -if (common.isWindows) { - // On Windows, creating symlinks requires admin privileges. - // We'll only try to run symlink test if we have enough privileges. - exec('whoami /priv', function(err, o) { - if (err || !o.includes('SeCreateSymbolicLinkPrivilege')) { - common.skip('insufficient privileges'); - return; - } - }); + +let linkTime; +let fileTime; + +if (!common.canCreateSymLink()) { + common.skip('insufficient privileges'); + return; } common.refreshTmpDir(); diff --git a/test/parallel/test-fs-sync-fd-leak.js b/test/parallel/test-fs-sync-fd-leak.js index f7cfd25f4b9b4c..353519593e2c4e 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() { @@ -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 acfdd1ccae1259..95eaf12cbb77f9 100644 --- a/test/parallel/test-fs-truncate-GH-6233.js +++ b/test/parallel/test-fs-truncate-GH-6233.js @@ -1,9 +1,9 @@ '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'; +const filename = common.tmpDir + '/truncate-file.txt'; common.refreshTmpDir(); diff --git a/test/parallel/test-fs-truncate.js b/test/parallel/test-fs-truncate.js index 1ba0db7f012fe4..80c938b8d43a03 100644 --- a/test/parallel/test-fs-truncate.js +++ b/test/parallel/test-fs-truncate.js @@ -43,9 +43,9 @@ fs.closeSync(fd); // async tests testTruncate(common.mustCall(function(er) { - if (er) throw er; + assert.ifError(er); testFtruncate(common.mustCall(function(er) { - if (er) throw er; + assert.ifError(er); })); })); diff --git a/test/parallel/test-fs-utimes.js b/test/parallel/test-fs-utimes.js index f245a7962da0f4..b28a2b96e2075e 100644 --- a/test/parallel/test-fs-utimes.js +++ b/test/parallel/test-fs-utimes.js @@ -1,14 +1,14 @@ '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'); -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); }); 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 0e24f33872825f..89570314cc504c 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); + const found = fs.readFileSync(filename, 'utf8'); + 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); diff --git a/test/parallel/test-fs-write-file-buffer.js b/test/parallel/test-fs-write-file-buffer.js index a23ccc21336976..409ddf1d51f557 100644 --- a/test/parallel/test-fs-write-file-buffer.js +++ b/test/parallel/test-fs-write-file-buffer.js @@ -1,10 +1,10 @@ '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 = [ +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-file-sync.js b/test/parallel/test-fs-write-file-sync.js index 7ae9e122cae8be..ca6324ac1ff789 100644 --- a/test/parallel/test-fs-write-file-sync.js +++ b/test/parallel/test-fs-write-file-sync.js @@ -1,11 +1,11 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var path = require('path'); -var fs = require('fs'); -var openCount = 0; -var mode; -var content; +const common = require('../common'); +const assert = require('assert'); +const path = require('path'); +const fs = require('fs'); +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++; diff --git a/test/parallel/test-fs-write-stream-autoclose-option.js b/test/parallel/test-fs-write-stream-autoclose-option.js index c7d21db2b4b531..4bfa4ba5341e1e 100644 --- a/test/parallel/test-fs-write-stream-autoclose-option.js +++ b/test/parallel/test-fs-write-stream-autoclose-option.js @@ -32,7 +32,7 @@ function next() { function next2() { // This will test if after reusing the fd data is written properly fs.readFile(file, function(err, data) { - assert(!err); + assert.ifError(err); assert.strictEqual(data.toString(), 'Test2'); process.nextTick(common.mustCall(next3)); }); 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-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..d50fd07103222e 100644 --- a/test/parallel/test-fs-write-stream-err.js +++ b/test/parallel/test-fs-write-stream-err.js @@ -1,17 +1,17 @@ '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(); -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-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); 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 5c7999e9b1158c..2694312b863571 100644 --- a/test/parallel/test-fs-write-string-coerce.js +++ b/test/parallel/test-fs-write-string-coerce.js @@ -1,22 +1,22 @@ '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(); -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) { - if (err) throw err; + assert.ifError(err); console.log('open done'); fs.write(fd, data, 0, 'utf8', common.mustCall(function(err, written) { console.log('write done'); - if (err) throw err; + assert.ifError(err); assert.equal(Buffer.byteLength(expected), written); fs.closeSync(fd); const found = fs.readFileSync(fn, 'utf8'); diff --git a/test/parallel/test-fs-write.js b/test/parallel/test-fs-write.js index 9960a91a4f7515..81f5cf707bf00a 100644 --- a/test/parallel/test-fs-write.js +++ b/test/parallel/test-fs-write.js @@ -12,14 +12,14 @@ const constants = fs.constants; common.refreshTmpDir(); fs.open(fn, 'w', 0o644, common.mustCall(function(err, fd) { - if (err) throw err; + assert.ifError(err); console.log('open done'); fs.write(fd, '', 0, 'utf8', function(err, written) { assert.strictEqual(0, written); }); fs.write(fd, expected, 0, 'utf8', common.mustCall(function(err, written) { console.log('write done'); - if (err) throw err; + assert.ifError(err); assert.strictEqual(Buffer.byteLength(expected), written); fs.closeSync(fd); const found = fs.readFileSync(fn, 'utf8'); @@ -33,14 +33,14 @@ fs.open(fn, 'w', 0o644, common.mustCall(function(err, fd) { fs.open(fn2, constants.O_CREAT | constants.O_WRONLY | constants.O_TRUNC, 0o644, common.mustCall((err, fd) => { - if (err) throw err; + assert.ifError(err); console.log('open done'); fs.write(fd, '', 0, 'utf8', (err, written) => { assert.strictEqual(0, written); }); fs.write(fd, expected, 0, 'utf8', common.mustCall((err, written) => { console.log('write done'); - if (err) throw err; + assert.ifError(err); assert.strictEqual(Buffer.byteLength(expected), written); fs.closeSync(fd); const found = fs.readFileSync(fn2, 'utf8'); 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-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-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-http-1.0-keep-alive.js b/test/parallel/test-http-1.0-keep-alive.js index 383f67c90a31b5..dea5f65c54184d 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([{ @@ -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 d01613de45452d..d98da182a9fee5 100644 --- a/test/parallel/test-http-1.0.js +++ b/test/parallel/test-http-1.0.js @@ -1,20 +1,20 @@ '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'; +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 ee22dc847b5882..046f439cb33195 100644 --- a/test/parallel/test-http-abort-before-end.js +++ b/test/parallel/test-http-abort-before-end.js @@ -1,12 +1,12 @@ '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); +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 addcec1ef3e9f9..6c00a1e6c64328 100644 --- a/test/parallel/test-http-abort-client.js +++ b/test/parallel/test-http-abort-client.js @@ -1,8 +1,8 @@ 'use strict'; const common = require('../common'); -var http = require('http'); +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 a2693637728439..d983d447934e41 100644 --- a/test/parallel/test-http-agent-destroyed-socket.js +++ b/test/parallel/test-http-agent-destroyed-socket.js @@ -1,28 +1,28 @@ '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) { +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 59b0109ef1c398..b2bf6334dcbc1b 100644 --- a/test/parallel/test-http-agent-error-on-idle.js +++ b/test/parallel/test-http-agent-error-on-idle.js @@ -1,38 +1,38 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var http = require('http'); -var Agent = http.Agent; +const assert = require('assert'); +const http = require('http'); +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 96606028bf7a45..5c9907bb706d32 100644 --- a/test/parallel/test-http-agent-false.js +++ b/test/parallel/test-http-agent-false.js @@ -1,12 +1,12 @@ '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 // 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 ea443ff9bd1107..6814aca3e76fbc 100644 --- a/test/parallel/test-http-agent-maxsockets.js +++ b/test/parallel/test-http-agent-maxsockets.js @@ -1,16 +1,16 @@ '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({ +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 94fd525b908c30..a11489b6c5bc2b 100644 --- a/test/parallel/test-http-agent-no-protocol.js +++ b/test/parallel/test-http-agent-no-protocol.js @@ -1,12 +1,12 @@ '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) { +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 f1dfeddea8b0e3..9071b88b98997a 100644 --- a/test/parallel/test-http-agent-null.js +++ b/test/parallel/test-http-agent-null.js @@ -1,11 +1,11 @@ 'use strict'; const common = require('../common'); -var http = require('http'); +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 dae982ed51a302..85975979cb3265 100644 --- a/test/parallel/test-http-agent.js +++ b/test/parallel/test-http-agent.js @@ -1,22 +1,22 @@ '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) { +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 600be8e43ee23c..5fc8d780af9396 100644 --- a/test/parallel/test-http-automatic-headers.js +++ b/test/parallel/test-http-automatic-headers.js @@ -1,9 +1,9 @@ '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) { +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 13b1a2f3b0d449..2a6bf482077166 100644 --- a/test/parallel/test-http-blank-header.js +++ b/test/parallel/test-http-blank-header.js @@ -1,10 +1,10 @@ '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) { +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 542d4ad5af2cbc..c240cd13b1825c 100644 --- a/test/parallel/test-http-buffer-sanity.js +++ b/test/parallel/test-http-buffer-sanity.js @@ -1,28 +1,28 @@ '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; +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 bb914439a76b78..3b295ebdcc1c49 100644 --- a/test/parallel/test-http-byteswritten.js +++ b/test/parallel/test-http-byteswritten.js @@ -1,11 +1,11 @@ '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'; +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-chunk-problem.js b/test/parallel/test-http-chunk-problem.js index 9bb004dc973f5c..82e8534af9e334 100644 --- a/test/parallel/test-http-chunk-problem.js +++ b/test/parallel/test-http-chunk-problem.js @@ -51,7 +51,7 @@ function executeRequest(cb) { __filename, 'shasum' ].join(' '), (err, stdout, stderr) => { - if (err) throw err; + assert.ifError(err); assert.equal('8c206a1a87599f532ce68675536f0b1546900d7a', stdout.slice(0, 40)); cb(); @@ -65,7 +65,7 @@ common.refreshTmpDir(); const ddcmd = common.ddCommand(filename, 10240); cp.exec(ddcmd, function(err, stdout, stderr) { - if (err) throw err; + assert.ifError(err); server = http.createServer(function(req, res) { res.writeHead(200); diff --git a/test/parallel/test-http-chunked-304.js b/test/parallel/test-http-chunked-304.js index 5ea1912b72dfee..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: // @@ -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); + })); + }) + ); + })); } diff --git a/test/parallel/test-http-chunked.js b/test/parallel/test-http-chunked.js index bb91dadd159de5..516523221133ec 100644 --- a/test/parallel/test-http-chunked.js +++ b/test/parallel/test-http-chunked.js @@ -1,25 +1,25 @@ '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年存在于岭南地区的一个国家,' + - '国都位于番禺,疆域包括今天中国的广东、广西两省区的大部份地区,福建省、湖南、' + - '贵州、云南的一小部份地区和越南的北部。南越国是秦朝灭亡后,' + - '由南海郡尉赵佗于前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 c0c1f9e4c73c92..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'); -var http = require('http'); -var server = http.createServer(function(req, res) { +const http = require('http'); +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 30269a193f0eab..7c7be9b530e2d2 100644 --- a/test/parallel/test-http-client-abort2.js +++ b/test/parallel/test-http-client-abort2.js @@ -1,13 +1,13 @@ 'use strict'; require('../common'); -var http = require('http'); +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 36ed24ec526255..3c2b9c89727467 100644 --- a/test/parallel/test-http-client-agent.js +++ b/test/parallel/test-http-client-agent.js @@ -1,13 +1,13 @@ '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; -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 9b73f2db32aad6..2271944773d9db 100644 --- a/test/parallel/test-http-client-default-headers-exist.js +++ b/test/parallel/test-http-client-default-headers-exist.js @@ -1,9 +1,9 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var http = require('http'); +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-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'); +} 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..9311110bdc041c 100644 --- a/test/parallel/test-http-client-get-url.js +++ b/test/parallel/test-http-client-get-url.js @@ -1,17 +1,22 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); -var http = require('http'); +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) { +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'}); 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-http-client-parse-error.js b/test/parallel/test-http-client-parse-error.js index cd6f135d889534..0d8f577a78566c 100644 --- a/test/parallel/test-http-client-parse-error.js +++ b/test/parallel/test-http-client-parse-error.js @@ -1,12 +1,12 @@ '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; +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 5b2db49435a1b6..d4ccba8d55b036 100644 --- a/test/parallel/test-http-client-pipe-end.js +++ b/test/parallel/test-http-client-pipe-end.js @@ -1,10 +1,10 @@ '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) { +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 632b9f4a219a92..d9e89b85eca1ed 100644 --- a/test/parallel/test-http-client-race-2.js +++ b/test/parallel/test-http-client-race-2.js @@ -1,22 +1,22 @@ '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 // 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 30ebb34fc7fcff..14e3300f20a436 100644 --- a/test/parallel/test-http-client-race.js +++ b/test/parallel/test-http-client-race.js @@ -1,25 +1,25 @@ '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'; +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 142c0ee3715aed..69b24f73771d41 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); @@ -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 4ed217c171f28a..16a18342468f94 100644 --- a/test/parallel/test-http-client-timeout-agent.js +++ b/test/parallel/test-http-client-timeout-agent.js @@ -1,11 +1,11 @@ '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; -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 402736e9b7d47c..0caae0d04c333c 100644 --- a/test/parallel/test-http-client-timeout.js +++ b/test/parallel/test-http-client-timeout.js @@ -1,22 +1,22 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var http = require('http'); +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 512a438ef82115..338aab9cc59ba0 100644 --- a/test/parallel/test-http-client-upload-buf.js +++ b/test/parallel/test-http-client-upload-buf.js @@ -1,14 +1,14 @@ '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; +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 a5c8f5b92bc761..ba60681776ba49 100644 --- a/test/parallel/test-http-client-upload.js +++ b/test/parallel/test-http-client-upload.js @@ -1,13 +1,13 @@ '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) { +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-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); diff --git a/test/parallel/test-http-conn-reset.js b/test/parallel/test-http-conn-reset.js index d7852bf32c9ec3..f7f08a6bf42c81 100644 --- a/test/parallel/test-http-conn-reset.js +++ b/test/parallel/test-http-conn-reset.js @@ -1,16 +1,16 @@ '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 = { +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 9104e5ba0d74cb..3d6882d92f04b3 100644 --- a/test/parallel/test-http-content-length.js +++ b/test/parallel/test-http-content-length.js @@ -1,27 +1,27 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var http = require('http'); +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 19e90e151382be..46eec45ed2757f 100644 --- a/test/parallel/test-http-contentLength0.js +++ b/test/parallel/test-http-contentLength0.js @@ -1,19 +1,19 @@ '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. // 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 e0b93c1f8718f5..e14a92b310f2d1 100644 --- a/test/parallel/test-http-date-header.js +++ b/test/parallel/test-http-date-header.js @@ -1,11 +1,11 @@ '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'; +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 4fb386bf4bb0e8..46327085184069 100644 --- a/test/parallel/test-http-default-encoding.js +++ b/test/parallel/test-http-default-encoding.js @@ -1,12 +1,12 @@ '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 = ''; +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-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..01023a088576ef 100644 --- a/test/parallel/test-http-destroyed-socket-write2.js +++ b/test/parallel/test-http-destroyed-socket-write2.js @@ -1,19 +1,19 @@ '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'); -var server = http.createServer(function(req, res) { +const http = require('http'); +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-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-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-eof-on-connect.js b/test/parallel/test-http-eof-on-connect.js index 6f70dc239172ee..f67e45ed403225 100644 --- a/test/parallel/test-http-eof-on-connect.js +++ b/test/parallel/test-http-eof-on-connect.js @@ -1,13 +1,13 @@ '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 // 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 b9958007609fd0..c003db131065a3 100644 --- a/test/parallel/test-http-exceptions.js +++ b/test/parallel/test-http-exceptions.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var http = require('http'); +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 a0ebf83b3301a5..0cf90e3b115e60 100644 --- a/test/parallel/test-http-expect-continue.js +++ b/test/parallel/test-http-expect-continue.js @@ -1,13 +1,13 @@ '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'; -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 8364684a1ec23f..6ebecaad1300de 100644 --- a/test/parallel/test-http-extra-response.js +++ b/test/parallel/test-http-extra-response.js @@ -1,15 +1,15 @@ '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. // 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 8b3dacb803d9bd..e8f5782c2f7857 100644 --- a/test/parallel/test-http-flush.js +++ b/test/parallel/test-http-flush.js @@ -1,12 +1,12 @@ 'use strict'; require('../common'); -var http = require('http'); +const http = require('http'); 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 e59456a710aac3..c834c6e6545320 100644 --- a/test/parallel/test-http-full-response.js +++ b/test/parallel/test-http-full-response.js @@ -1,15 +1,15 @@ '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; +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 cc681f675a791e..15c96a9a4e12ea 100644 --- a/test/parallel/test-http-get-pipeline-problem.js +++ b/test/parallel/test-http-get-pipeline-problem.js @@ -2,23 +2,23 @@ // 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; 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 e8626b18811bda..de94dfb8b7d6e7 100644 --- a/test/parallel/test-http-head-request.js +++ b/test/parallel/test-http-head-request.js @@ -1,11 +1,11 @@ 'use strict'; const common = require('../common'); -var http = require('http'); +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 87ce957df3499f..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 @@ -1,19 +1,19 @@ '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, // 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 445b522b8dea51..b2eb98b1eea06c 100644 --- a/test/parallel/test-http-head-response-has-no-body.js +++ b/test/parallel/test-http-head-response-has-no-body.js @@ -1,19 +1,19 @@ '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. // 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 b726fe130f0ee4..3d9e756d505238 100644 --- a/test/parallel/test-http-header-read.js +++ b/test/parallel/test-http-header-read.js @@ -1,14 +1,14 @@ '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. -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 adfe18077a8259..211f818e566699 100644 --- a/test/parallel/test-http-hex-write.js +++ b/test/parallel/test-http-hex-write.js @@ -1,10 +1,10 @@ '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'; +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 a9f12d6819314e..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--; @@ -39,9 +39,7 @@ function testHttp() { httpServer.listen(0, function(er) { console.error(`test http server listening on ${this.address().port}`); - - if (er) throw er; - + assert.ifError(er); http.get({ method: 'GET', path: '/' + (counter++), 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'); 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 d9396b258e7515..15d5d62d429658 100644 --- a/test/parallel/test-http-keep-alive-close-on-header.js +++ b/test/parallel/test-http-keep-alive-close-on-header.js @@ -1,24 +1,24 @@ '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'}; +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 955fc006e22d58..c9cf7bba96a7db 100644 --- a/test/parallel/test-http-keepalive-client.js +++ b/test/parallel/test-http-keepalive-client.js @@ -1,12 +1,12 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); -var http = require('http'); +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 6f1476d0ce3aed..14e9e88ef7fd09 100644 --- a/test/parallel/test-http-keepalive-maxsockets.js +++ b/test/parallel/test-http-keepalive-maxsockets.js @@ -1,25 +1,25 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); -var http = require('http'); +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 daae5aa9944294..dc9bdefb333d13 100644 --- a/test/parallel/test-http-keepalive-request.js +++ b/test/parallel/test-http-keepalive-request.js @@ -1,12 +1,12 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); -var http = require('http'); +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 0b828910f12873..a23c6f2a4452a6 100644 --- a/test/parallel/test-http-localaddress-bind-error.js +++ b/test/parallel/test-http-localaddress-bind-error.js @@ -1,10 +1,10 @@ 'use strict'; const common = require('../common'); -var http = require('http'); +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 fd38f8a901fe81..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 647b67bcd3ff78..a36c9fdbe29451 100644 --- a/test/parallel/test-http-malformed-request.js +++ b/test/parallel/test-http-malformed-request.js @@ -1,17 +1,17 @@ '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. -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 7966f47a9efa19..b4af99ef00a9d4 100644 --- a/test/parallel/test-http-many-ended-pipelines.js +++ b/test/parallel/test-http-many-ended-pipelines.js @@ -2,19 +2,19 @@ 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'); }; -var http = require('http'); -var net = require('net'); +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 2d68ead110fc6c..018ed33c1b9e49 100644 --- a/test/parallel/test-http-max-headers-count.js +++ b/test/parallel/test-http-max-headers-count.js @@ -1,26 +1,26 @@ '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; +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-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..2096f533a196d1 100644 --- a/test/parallel/test-http-multi-line-headers.js +++ b/test/parallel/test-http-multi-line-headers.js @@ -1,14 +1,14 @@ '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.'; +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-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..a6cfad13aa2b44 100644 --- a/test/parallel/test-http-no-content-length.js +++ b/test/parallel/test-http-no-content-length.js @@ -1,15 +1,15 @@ '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) { +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 56ce777cb3eaaf..73654909d88e1b 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(); @@ -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 73d5f7eb13049c..69682128fadbdf 100644 --- a/test/parallel/test-http-parser-bad-ref.js +++ b/test/parallel/test-http-parser-bad-ref.js @@ -5,16 +5,16 @@ // Flags: --expose_gc require('../common'); -var assert = require('assert'); -var HTTPParser = process.binding('http_parser').HTTPParser; +const assert = require('assert'); +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 125374bbedde63..80cc3cc64ee5b3 100644 --- a/test/parallel/test-http-parser-free.js +++ b/test/parallel/test-http-parser-free.js @@ -1,20 +1,20 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var http = require('http'); -var N = 100; -var responses = 0; +const assert = require('assert'); +const http = require('http'); +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 abc1d096dff0d8..e1215fbd13ae40 100644 --- a/test/parallel/test-http-parser.js +++ b/test/parallel/test-http-parser.js @@ -1,19 +1,19 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); 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 f6562b3afc94ae..8bb8dd4b5da25c 100644 --- a/test/parallel/test-http-pause.js +++ b/test/parallel/test-http-pause.js @@ -1,14 +1,14 @@ '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 = ''; -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 3205802d7ab0f2..5348637bd07145 100644 --- a/test/parallel/test-http-pipe-fs.js +++ b/test/parallel/test-http-pipe-fs.js @@ -1,15 +1,15 @@ '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(); -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 43feb1e3b3838c..8e7fd55a0ed6ea 100644 --- a/test/parallel/test-http-proxy.js +++ b/test/parallel/test-http-proxy.js @@ -1,26 +1,26 @@ '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 = [ +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 2e2e9631490395..7ae0c35e3d8d11 100644 --- a/test/parallel/test-http-raw-headers.js +++ b/test/parallel/test-http-raw-headers.js @@ -1,11 +1,11 @@ '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 = [ + 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 9b8ff35b0fe5d3..077ff0f5b33f40 100644 --- a/test/parallel/test-http-remove-header-stays-removed.js +++ b/test/parallel/test-http-remove-header-stays-removed.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 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 230175be8e95c1..ab30c0a1eef8a1 100644 --- a/test/parallel/test-http-request-end-twice.js +++ b/test/parallel/test-http-request-end-twice.js @@ -1,14 +1,14 @@ '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) { +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 6beedae20d9e00..dd4a8caf105329 100644 --- a/test/parallel/test-http-request-end.js +++ b/test/parallel/test-http-request-end.js @@ -1,12 +1,12 @@ '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'; +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 7f42a9c00a85f3..e4579791ef301a 100644 --- a/test/parallel/test-http-request-methods.js +++ b/test/parallel/test-http-request-methods.js @@ -1,13 +1,13 @@ '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 ['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 @@ var 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 5a91c556340b1c..2ee0e4e29d95e4 100644 --- a/test/parallel/test-http-res-write-after-end.js +++ b/test/parallel/test-http-res-write-after-end.js @@ -1,9 +1,9 @@ '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) { +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 5c14b0678520c4..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 @@ -1,11 +1,11 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var http = require('http'); +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 54ee61efccf1ea..de179c113e1db1 100644 --- a/test/parallel/test-http-response-close.js +++ b/test/parallel/test-http-response-close.js @@ -1,8 +1,8 @@ 'use strict'; const common = require('../common'); -var http = require('http'); +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 4a3460bc645140..3f44b4ef5fde0b 100644 --- a/test/parallel/test-http-response-no-headers.js +++ b/test/parallel/test-http-response-no-headers.js @@ -1,31 +1,31 @@ '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 = { +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 1d561ca4704808..07c0a40e4bf1a8 100644 --- a/test/parallel/test-http-response-readable.js +++ b/test/parallel/test-http-response-readable.js @@ -1,9 +1,9 @@ '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) { +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 b14c1f2faf0fce..d17dfb24c6b4c8 100644 --- a/test/parallel/test-http-response-status-message.js +++ b/test/parallel/test-http-response-status-message.js @@ -1,12 +1,12 @@ '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; +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 3314506339b564..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; -var reqNum = 0; +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: 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 5b41ee89d87e50..189ab0657bacb0 100644 --- a/test/parallel/test-http-server-multiheaders.js +++ b/test/parallel/test-http-server-multiheaders.js @@ -4,10 +4,10 @@ // 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) { +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 9f6d41e6a10cea..82cc9960329a11 100644 --- a/test/parallel/test-http-server-multiheaders2.js +++ b/test/parallel/test-http-server-multiheaders2.js @@ -4,10 +4,10 @@ // 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 = [ +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 819f503de547e4..3728453c039447 100644 --- a/test/parallel/test-http-server-stale-close.js +++ b/test/parallel/test-http-server-stale-close.js @@ -1,11 +1,11 @@ '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({ + 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 76238380c7cfde..fca2691aacc25d 100644 --- a/test/parallel/test-http-server-unconsume.js +++ b/test/parallel/test-http-server-unconsume.js @@ -1,12 +1,12 @@ '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 = ''; +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 1870bcc7170726..90c2709ebdbc5c 100644 --- a/test/parallel/test-http-server.js +++ b/test/parallel/test-http-server.js @@ -1,17 +1,17 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var net = require('net'); -var http = require('http'); -var url = require('url'); -var qs = require('querystring'); - -var request_number = 0; -var requests_sent = 0; -var server_response = ''; -var client_got_eof = false; - -var server = http.createServer(function(req, res) { +const assert = require('assert'); +const net = require('net'); +const http = require('http'); +const url = require('url'); +const qs = require('querystring'); + +let request_number = 0; +let requests_sent = 0; +let server_response = ''; +let client_got_eof = false; + +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 1f00ebb65e34de..cb06352b3ca85d 100644 --- a/test/parallel/test-http-set-cookies.js +++ b/test/parallel/test-http-set-cookies.js @@ -1,11 +1,11 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var http = require('http'); +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 d530503aa1e9aa..7a2447763e4cf9 100644 --- a/test/parallel/test-http-set-timeout-server.js +++ b/test/parallel/test-http-set-timeout-server.js @@ -1,10 +1,10 @@ '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 = []; +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 b3f331c6d8b172..7b66933ecd12cd 100644 --- a/test/parallel/test-http-set-trailers.js +++ b/test/parallel/test-http-set-trailers.js @@ -1,12 +1,12 @@ '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; +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 3aaa2d3d73acdc..77a3c3922a20f0 100644 --- a/test/parallel/test-http-should-keep-alive.js +++ b/test/parallel/test-http-should-keep-alive.js @@ -1,10 +1,10 @@ '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 = [ +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 c0086a3e3d672f..b5060109bf4985 100644 --- a/test/parallel/test-http-status-code.js +++ b/test/parallel/test-http-status-code.js @@ -1,17 +1,17 @@ '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 -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 6da4b6e4281171..668b02ee0780b4 100644 --- a/test/parallel/test-http-status-message.js +++ b/test/parallel/test-http-status-message.js @@ -1,10 +1,10 @@ '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) { +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 49cf3ec0278fca..39b4550d57e529 100644 --- a/test/parallel/test-http-timeout-overflow.js +++ b/test/parallel/test-http-timeout-overflow.js @@ -1,13 +1,13 @@ '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; +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 b8a28fc2c4cf32..63f87ed63089ee 100644 --- a/test/parallel/test-http-timeout.js +++ b/test/parallel/test-http-timeout.js @@ -1,24 +1,24 @@ 'use strict'; require('../common'); -var http = require('http'); +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 48eaa16f898021..a196ba904905a3 100644 --- a/test/parallel/test-http-upgrade-agent.js +++ b/test/parallel/test-http-upgrade-agent.js @@ -3,14 +3,14 @@ // 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) { +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 51c70122b99d87..34e3e8f24158e7 100644 --- a/test/parallel/test-http-upgrade-client.js +++ b/test/parallel/test-http-upgrade-client.js @@ -3,14 +3,14 @@ // 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) { +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 0c229a354add48..fa14f8ca51f030 100644 --- a/test/parallel/test-http-upgrade-client2.js +++ b/test/parallel/test-http-upgrade-client2.js @@ -1,10 +1,10 @@ 'use strict'; const common = require('../common'); -var http = require('http'); +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 8570dec899b672..221263e98ce9cd 100644 --- a/test/parallel/test-http-upgrade-server.js +++ b/test/parallel/test-http-upgrade-server.js @@ -1,15 +1,15 @@ '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; -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 1644f54977af85..c64b2e843637af 100644 --- a/test/parallel/test-http-upgrade-server2.js +++ b/test/parallel/test-http-upgrade-server2.js @@ -1,10 +1,10 @@ '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) { +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 fa930bd5ec2e34..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 @@ -1,15 +1,15 @@ '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 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 0e901ebb599b00..25913f4e49a12a 100644 --- a/test/parallel/test-http-url.parse-auth.js +++ b/test/parallel/test-http-url.parse-auth.js @@ -1,15 +1,15 @@ '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 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 b0d1274b594d7e..ac22b6e38d80e1 100644 --- a/test/parallel/test-http-url.parse-basic.js +++ b/test/parallel/test-http-url.parse-basic.js @@ -1,10 +1,10 @@ '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; +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 edd83a2d1306f5..ad40e76debee90 100644 --- a/test/parallel/test-http-url.parse-https.request.js +++ b/test/parallel/test-http-url.parse-https.request.js @@ -1,18 +1,18 @@ '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 = { +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-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..6fab8bb0eb3b6b 100644 --- a/test/parallel/test-http-url.parse-path.js +++ b/test/parallel/test-http-url.parse-path.js @@ -1,15 +1,15 @@ '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 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 0af482c94a875d..d63f404c5403dd 100644 --- a/test/parallel/test-http-url.parse-post.js +++ b/test/parallel/test-http-url.parse-post.js @@ -1,10 +1,10 @@ '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; +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 9a1e7565572fcc..f2a5d1806d89a2 100644 --- a/test/parallel/test-http-url.parse-search.js +++ b/test/parallel/test-http-url.parse-search.js @@ -1,15 +1,15 @@ '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 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 f7fb1a3656c623..a633873c8bb16f 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 // @@ -19,7 +19,7 @@ var 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 b89cdf89af7b90..3783dc305e39a7 100644 --- a/test/parallel/test-http-write-callbacks.js +++ b/test/parallel/test-http-write-callbacks.js @@ -1,16 +1,16 @@ '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 = ''; -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 534a55823accee..69463fb3a50852 100644 --- a/test/parallel/test-http-write-empty-string.js +++ b/test/parallel/test-http-write-empty-string.js @@ -1,10 +1,10 @@ '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) { +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 32fff6042e7178..12f5e00b0db493 100644 --- a/test/parallel/test-http-write-head.js +++ b/test/parallel/test-http-write-head.js @@ -1,16 +1,16 @@ '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. -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 b928aaeb341a88..63446e460471e4 100644 --- a/test/parallel/test-http-zero-length-write.js +++ b/test/parallel/test-http-zero-length-write.js @@ -1,18 +1,18 @@ '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. // 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 dc9878d4a1c1ed..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, @@ -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-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(); + })); + })); + })); + })); +})); diff --git a/test/parallel/test-https-agent-servername.js b/test/parallel/test-https-agent-servername.js index 348cf499b65f56..a321f7140396a3 100644 --- a/test/parallel/test-https-agent-servername.js +++ b/test/parallel/test-https-agent-servername.js @@ -1,22 +1,22 @@ '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 = { +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-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-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 58dfb12dbe2eda..cdea4d1ee930f3 100644 --- a/test/parallel/test-https-byteswritten.js +++ b/test/parallel/test-https-byteswritten.js @@ -1,22 +1,22 @@ '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 = { +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 053a5630050748..688c7e22706e0e 100644 --- a/test/parallel/test-https-client-checkServerIdentity.js +++ b/test/parallel/test-https-client-checkServerIdentity.js @@ -1,22 +1,22 @@ '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 = { +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 1a9fdf5f3f808e..1f4f6ff748b410 100644 --- a/test/parallel/test-https-client-get-url.js +++ b/test/parallel/test-https-client-get-url.js @@ -3,30 +3,35 @@ 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'); +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'}); 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-https-client-reject.js b/test/parallel/test-https-client-reject.js index b1708f24b10b83..92bbabe8b3be90 100644 --- a/test/parallel/test-https-client-reject.js +++ b/test/parallel/test-https-client-reject.js @@ -1,22 +1,22 @@ '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 = { +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 734e8069021f78..79e1a716bd77cf 100644 --- a/test/parallel/test-https-client-resume.js +++ b/test/parallel/test-https-client-resume.js @@ -2,33 +2,33 @@ // 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 = { +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 53158595054714..ae8507f99cbc00 100644 --- a/test/parallel/test-https-connecting-to-http.js +++ b/test/parallel/test-https-connecting-to-http.js @@ -1,19 +1,19 @@ '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); +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 7648469b0f54a7..0b18795078fd1f 100644 --- a/test/parallel/test-https-drain.js +++ b/test/parallel/test-https-drain.js @@ -1,38 +1,38 @@ '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 = { +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 1c814714bfef96..d5e896c7695cfd 100644 --- a/test/parallel/test-https-eof-for-eom.js +++ b/test/parallel/test-https-eof-for-eom.js @@ -7,25 +7,25 @@ // 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 = { +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 5c9fb613e6fa95..f1b8d442e27893 100644 --- a/test/parallel/test-https-foafssl.js +++ b/test/parallel/test-https-foafssl.js @@ -1,24 +1,24 @@ '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 = { +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 e4fd6dfe92ef15..190f15f29a8078 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 = { @@ -37,7 +37,7 @@ testHttps(); function testHttps() { - var counter = 0; + let counter = 0; function cb(res) { counter--; @@ -51,9 +51,7 @@ function testHttps() { httpsServer.listen(0, function(er) { console.log(`test https server listening on port ${this.address().port}`); - - if (er) throw er; - + assert.ifError(er); https.get({ method: 'GET', path: '/' + (counter++), diff --git a/test/parallel/test-https-localaddress-bind-error.js b/test/parallel/test-https-localaddress-bind-error.js index 91c3062a6e1896..662d6f080a0fff 100644 --- a/test/parallel/test-https-localaddress-bind-error.js +++ b/test/parallel/test-https-localaddress-bind-error.js @@ -1,21 +1,21 @@ '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 = { +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 e6aa0c93a2aaaa..78583b38ecf1cf 100644 --- a/test/parallel/test-https-localaddress.js +++ b/test/parallel/test-https-localaddress.js @@ -7,19 +7,19 @@ if (!common.hasCrypto) { common.skip('missing crypto'); return; } -var https = require('https'); +const https = require('https'); if (!common.hasMultiLocalhost()) { common.skip('platform-specific test.'); 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 02715de60da3c8..c30bbc0848d137 100644 --- a/test/parallel/test-https-pfx.js +++ b/test/parallel/test-https-pfx.js @@ -1,17 +1,17 @@ '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'); +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 b49c17f28879be..4298abe5eff43d 100644 --- a/test/parallel/test-https-req-split.js +++ b/test/parallel/test-https-req-split.js @@ -7,12 +7,12 @@ 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 = { +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 0efe467932915a..cc712b312485b2 100644 --- a/test/parallel/test-https-resume-after-renew.js +++ b/test/parallel/test-https-resume-after-renew.js @@ -5,28 +5,29 @@ 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 = { +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 fd00a521a03cb5..4cf999667d7384 100644 --- a/test/parallel/test-https-set-timeout-server.js +++ b/test/parallel/test-https-set-timeout-server.js @@ -1,19 +1,19 @@ '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 = []; +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 70013d1770ff98..05137b35c437ff 100644 --- a/test/parallel/test-https-socket-options.js +++ b/test/parallel/test-https-socket-options.js @@ -1,26 +1,26 @@ '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 = { +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-strict.js b/test/parallel/test-https-strict.js index 871d9ef94e6960..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); @@ -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); }); diff --git a/test/parallel/test-https-timeout-server-2.js b/test/parallel/test-https-timeout-server-2.js index 07b7984f2d644b..8729af1ae8b4ba 100644 --- a/test/parallel/test-https-timeout-server-2.js +++ b/test/parallel/test-https-timeout-server-2.js @@ -1,26 +1,26 @@ '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 = { +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-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); }); -} +}); diff --git a/test/parallel/test-icu-transcode.js b/test/parallel/test-icu-transcode.js index c099e754ca55d6..3d889ac7d8cf5f 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 @@ -18,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-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-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 ' + diff --git a/test/parallel/test-listen-fd-cluster.js b/test/parallel/test-listen-fd-cluster.js index 606109030b51d0..de1fbed7b56aff 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'); @@ -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,15 +61,15 @@ 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() { const port = this.address().port; console.error('server listening on %d', port); - var spawn = require('child_process').spawn; - var master = spawn(process.execPath, [__filename, 'master'], { + const spawn = require('child_process').spawn; + 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 5dfe346a49f441..2ac4d83dba6691 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.'); @@ -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 0629f7ea7970d7..1194d001610fce 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.'); @@ -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); - var spawn = require('child_process').spawn; - var child = spawn(process.execPath, [__filename, 'child'], { + const spawn = require('child_process').spawn; + 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 eda75e5c723261..60aa8717a8c24e 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.'); @@ -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,15 +67,15 @@ 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() { const port = this.address().port; console.error('server listening on %d', port); - var spawn = require('child_process').spawn; - var child = spawn(process.execPath, [__filename, 'child'], { + const spawn = require('child_process').spawn; + 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 92c103669a9a85..09ab270b70fa21 100644 --- a/test/parallel/test-memory-usage-emfile.js +++ b/test/parallel/test-memory-usage-emfile.js @@ -1,13 +1,13 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); -var fs = require('fs'); +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 c5905c537ac613..cba3f9a5172a07 100644 --- a/test/parallel/test-memory-usage.js +++ b/test/parallel/test-memory-usage.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var assert = require('assert'); +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 1e07fa5d415ba3..7110af7648ae8a 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 @@ -9,21 +9,21 @@ var 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 2cc608d96aec3d..d212bbae96b001 100644 --- a/test/parallel/test-microtask-queue-integration.js +++ b/test/parallel/test-microtask-queue-integration.js @@ -1,22 +1,22 @@ 'use strict'; require('../common'); -var assert = require('assert'); +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 fb5139f71d65aa..7d34ec829a003c 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 @@ -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 4a7729ab98a062..e09087f74e32a9 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 @@ -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 479062ad4710f4..c5ed6c6dcbc1ae 100644 --- a/test/parallel/test-microtask-queue-run-immediate.js +++ b/test/parallel/test-microtask-queue-run-immediate.js @@ -1,12 +1,12 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); 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 ce743d93003249..71e1fbedbaecbd 100644 --- a/test/parallel/test-microtask-queue-run.js +++ b/test/parallel/test-microtask-queue-run.js @@ -1,12 +1,12 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); 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 3369df0676015b..ec90f1a3e2c868 100644 --- a/test/parallel/test-module-globalpaths-nodepath.js +++ b/test/parallel/test-module-globalpaths-nodepath.js @@ -1,11 +1,10 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); +const mod = require('module'); -var module = require('module'); - -var partA, partB; -var partC = ''; +let partA, partB; +const partC = ''; if (common.isWindows) { partA = 'C:\\Users\\Rocko Artischocko\\AppData\\Roaming\\npm'; @@ -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..d78f61de60fa14 100644 --- a/test/parallel/test-module-loading-error.js +++ b/test/parallel/test-module-loading-error.js @@ -1,16 +1,16 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); +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.'); @@ -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-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..d46f096116d02e 100644 --- a/test/parallel/test-net-after-close.js +++ b/test/parallel/test-net-after-close.js @@ -1,15 +1,15 @@ '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) { +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 9222a1cc758aaa..2f821ef5d703be 100644 --- a/test/parallel/test-net-better-error-messages-path.js +++ b/test/parallel/test-net-better-error-messages-path.js @@ -1,9 +1,9 @@ 'use strict'; -var common = require('../common'); -var net = require('net'); -var assert = require('assert'); -var fp = '/tmp/fadagagsdfgsdf'; -var c = net.connect(fp); +const common = require('../common'); +const net = require('net'); +const assert = require('assert'); +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 9b9fc7c5db37dd..17fdc90cb3742b 100644 --- a/test/parallel/test-net-bind-twice.js +++ b/test/parallel/test-net-bind-twice.js @@ -1,11 +1,11 @@ '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); +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 872d8de7b42f3b..e8ba17a76e6c69 100644 --- a/test/parallel/test-net-buffersize.js +++ b/test/parallel/test-net-buffersize.js @@ -1,11 +1,11 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var net = require('net'); +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 a8643b03b97250..4cc6eee8373e86 100644 --- a/test/parallel/test-net-bytes-stats.js +++ b/test/parallel/test-net-bytes-stats.js @@ -1,13 +1,13 @@ '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; -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 7dbd5cad2ae6bb..faa460e847aa08 100644 --- a/test/parallel/test-net-can-reset-timeout.js +++ b/test/parallel/test-net-can-reset-timeout.js @@ -1,8 +1,8 @@ 'use strict'; const common = require('../common'); -var net = require('net'); +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 3ef5b0ea9f075d..c43ee1abd0e305 100644 --- a/test/parallel/test-net-connect-buffer.js +++ b/test/parallel/test-net-connect-buffer.js @@ -1,17 +1,17 @@ '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; +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 3446790d7b3c4a..e794c40859856a 100644 --- a/test/parallel/test-net-connect-options.js +++ b/test/parallel/test-net-connect-options.js @@ -1,9 +1,9 @@ '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({ +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-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-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 07eb71c5ed5811..c7a01f5fa6faec 100644 --- a/test/parallel/test-net-dns-custom-lookup.js +++ b/test/parallel/test-net-dns-custom-lookup.js @@ -1,16 +1,16 @@ '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) { + 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 b36d84d3e9e214..aa288c5fde1ffa 100644 --- a/test/parallel/test-net-dns-error.js +++ b/test/parallel/test-net-dns-error.js @@ -1,16 +1,16 @@ '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); +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 513a6d0422498e..0997e6cc6c1c5d 100644 --- a/test/parallel/test-net-dns-lookup-skip.js +++ b/test/parallel/test-net-dns-lookup-skip.js @@ -1,14 +1,14 @@ '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) { + 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 4f3cd2991cf925..8d9930f4b7a366 100644 --- a/test/parallel/test-net-dns-lookup.js +++ b/test/parallel/test-net-dns-lookup.js @@ -1,9 +1,9 @@ '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) { +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 2649995f89a02f..e8723fb1a692a8 100644 --- a/test/parallel/test-net-during-close.js +++ b/test/parallel/test-net-during-close.js @@ -1,14 +1,14 @@ '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) { +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 4741c820797154..3d7ceb8d5e38f7 100644 --- a/test/parallel/test-net-eaddrinuse.js +++ b/test/parallel/test-net-eaddrinuse.js @@ -1,11 +1,11 @@ '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) { +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 69abf486316ff2..99324b071d27d6 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(); +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-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-keepalive.js b/test/parallel/test-net-keepalive.js index e466f0ff580d06..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 @@ -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-large-string.js b/test/parallel/test-net-large-string.js index b469b0289546a1..83612111e2a0aa 100644 --- a/test/parallel/test-net-large-string.js +++ b/test/parallel/test-net-large-string.js @@ -1,14 +1,14 @@ '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); -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 03c08d4f51bf15..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 @@ -1,8 +1,8 @@ 'use strict'; const common = require('../common'); -var net = require('net'); +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 92c7274f328918..0a45adecbe83e7 100644 --- a/test/parallel/test-net-listen-close-server.js +++ b/test/parallel/test-net-listen-close-server.js @@ -1,8 +1,8 @@ 'use strict'; const common = require('../common'); -var net = require('net'); +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 9523fcb2e7f456..7b721d1004f37f 100644 --- a/test/parallel/test-net-listen-error.js +++ b/test/parallel/test-net-listen-error.js @@ -1,8 +1,8 @@ 'use strict'; const common = require('../common'); -var net = require('net'); +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 f46f9a01d773ce..cc1ab4d805994f 100644 --- a/test/parallel/test-net-listen-exclusive-random-ports.js +++ b/test/parallel/test-net-listen-exclusive-random-ports.js @@ -1,27 +1,27 @@ '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() {} 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'); - assert.notEqual(port1, port2, 'ports should not be equal'); + assert.notStrictEqual(port1, port2, 'ports should not be equal'); worker1.kill(); worker2.kill(); }); }); } 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 2062dd0ce136bb..ce344be4a6f492 100644 --- a/test/parallel/test-net-listen-shared-ports.js +++ b/test/parallel/test-net-listen-shared-ports.js @@ -1,17 +1,17 @@ '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() {} 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 4af9dcfd08aeca..b100e4ae768c29 100644 --- a/test/parallel/test-net-localport.js +++ b/test/parallel/test-net-localport.js @@ -1,9 +1,9 @@ '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) { +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 d1dfb370167714..6338b5932de1fa 100644 --- a/test/parallel/test-net-persistent-keepalive.js +++ b/test/parallel/test-net-persistent-keepalive.js @@ -1,11 +1,11 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var net = require('net'); +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 e23b8718dfee6d..3f94424b0e1197 100644 --- a/test/parallel/test-net-persistent-nodelay.js +++ b/test/parallel/test-net-persistent-nodelay.js @@ -1,18 +1,18 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var net = require('net'); -var TCPWrap = process.binding('tcp_wrap').TCP; +const assert = require('assert'); +const net = require('net'); +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 32782e7c591444..1d3cbc6ffaef18 100644 --- a/test/parallel/test-net-persistent-ref-unref.js +++ b/test/parallel/test-net-persistent-ref-unref.js @@ -1,17 +1,17 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var net = require('net'); -var TCPWrap = process.binding('tcp_wrap').TCP; +const assert = require('assert'); +const net = require('net'); +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 980de2637b18bf..47171093ca13f9 100644 --- a/test/parallel/test-net-reconnect.js +++ b/test/parallel/test-net-reconnect.js @@ -1,15 +1,15 @@ '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; -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 62a7ebfe572908..a9d02631be5194 100644 --- a/test/parallel/test-net-remote-address-port.js +++ b/test/parallel/test-net-remote-address-port.js @@ -4,50 +4,50 @@ 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) { - assert.notEqual(-1, remoteAddrCandidates.indexOf(socket.remoteAddress)); - assert.notEqual(-1, remoteFamilyCandidates.indexOf(socket.remoteFamily)); +const server = net.createServer(common.mustCall(function(socket) { + 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)); 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.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-net-server-bind.js b/test/parallel/test-net-server-bind.js index c77341418c2c6d..e4dc64216441cf 100644 --- a/test/parallel/test-net-server-bind.js +++ b/test/parallel/test-net-server-bind.js @@ -1,13 +1,13 @@ '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 -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 006ca529c79ab3..d52cccaacfd8e6 100644 --- a/test/parallel/test-net-server-close.js +++ b/test/parallel/test-net-server-close.js @@ -1,10 +1,10 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var net = require('net'); +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 ae89d9aac7b3f7..4e41d29a505199 100644 --- a/test/parallel/test-net-server-connections.js +++ b/test/parallel/test-net-server-connections.js @@ -1,12 +1,12 @@ '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 -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 9bdfd628072798..a678922683eeb1 100644 --- a/test/parallel/test-net-server-listen-remove-callback.js +++ b/test/parallel/test-net-server-listen-remove-callback.js @@ -1,13 +1,13 @@ '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(); +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 fb9831d05b3e50..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 @@ -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). @@ -13,16 +13,16 @@ var 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 d68e94cfbda8c8..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'); -var net = require('net'); -var server = net.createServer(); +const net = require('net'); +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 91b25887a28d3e..60df9fc700ec64 100644 --- a/test/parallel/test-net-server-unref.js +++ b/test/parallel/test-net-server-unref.js @@ -1,8 +1,8 @@ 'use strict'; const common = require('../common'); -var net = require('net'); +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 917e9849999b05..998ad05a1d6487 100644 --- a/test/parallel/test-net-socket-destroy-twice.js +++ b/test/parallel/test-net-socket-destroy-twice.js @@ -1,8 +1,8 @@ 'use strict'; -var common = require('../common'); -var net = require('net'); +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 d090038ce753be..9d091bd66f3a1e 100644 --- a/test/parallel/test-net-stream.js +++ b/test/parallel/test-net-stream.js @@ -1,9 +1,9 @@ '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(); +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 e01aef80f3635b..0a1dcd98b2b3c7 100644 --- a/test/parallel/test-net-write-after-close.js +++ b/test/parallel/test-net-write-after-close.js @@ -1,8 +1,8 @@ 'use strict'; const common = require('../common'); -var net = require('net'); +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 315db6bc02b309..ee20ede49fb5a5 100644 --- a/test/parallel/test-net-write-connect-write.js +++ b/test/parallel/test-net-write-connect-write.js @@ -1,13 +1,13 @@ '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) { +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 6054e2b7882ac2..c1b2c60e2e202a 100644 --- a/test/parallel/test-net-write-slow.js +++ b/test/parallel/test-net-write-slow.js @@ -1,22 +1,22 @@ '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; -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 8f9d9bb4aa50f7..6edb7e3050c067 100644 --- a/test/parallel/test-next-tick-domain.js +++ b/test/parallel/test-next-tick-domain.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); -var origNextTick = process.nextTick; +const origNextTick = process.nextTick; require('domain'); 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..ee829c94ab6929 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 @@ -9,14 +9,14 @@ var 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 63f8d37828e53c..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'); -var assert = require('assert'); -var i; +const assert = require('assert'); +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 11ac84b5319dda..7cfec867f3ed01 100644 --- a/test/parallel/test-next-tick-ordering2.js +++ b/test/parallel/test-next-tick-ordering2.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var assert = require('assert'); +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 2a98b46da10f17..3001ad0e561a77 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() { @@ -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-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-path-makelong.js b/test/parallel/test-path-makelong.js index 50a77e9d87b8dc..293d6284f173bc 100644 --- a/test/parallel/test-path-makelong.js +++ b/test/parallel/test-path-makelong.js @@ -1,11 +1,11 @@ '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'); - 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 85e3daa3522e78..49f6802d3f7c7a 100644 --- a/test/parallel/test-pipe-address.js +++ b/test/parallel/test-pipe-address.js @@ -1,8 +1,8 @@ 'use strict'; -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); -var server = net.createServer(common.fail); +const common = require('../common'); +const assert = require('assert'); +const net = require('net'); +const server = net.createServer(common.fail); common.refreshTmpDir(); diff --git a/test/parallel/test-pipe-file-to-http.js b/test/parallel/test-pipe-file-to-http.js index f72cfe7d793348..0ea9244ff76946 100644 --- a/test/parallel/test-pipe-file-to-http.js +++ b/test/parallel/test-pipe-file-to-http.js @@ -38,7 +38,7 @@ server.on('listening', function() { const cmd = common.ddCommand(filename, 10240); cp.exec(cmd, function(err) { - if (err) throw err; + assert.ifError(err); makeRequest(); }); }); diff --git a/test/parallel/test-pipe-return-val.js b/test/parallel/test-pipe-return-val.js index a14f925916bee0..5e6e83dbc7a952 100644 --- a/test/parallel/test-pipe-return-val.js +++ b/test/parallel/test-pipe-return-val.js @@ -2,11 +2,11 @@ // 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(); -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 6298495087ac06..5e3774fc99d535 100644 --- a/test/parallel/test-pipe-stream.js +++ b/test/parallel/test-pipe-stream.js @@ -1,13 +1,13 @@ '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(); 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 35c25524b4cfc8..34b5ef651bf6aa 100644 --- a/test/parallel/test-pipe-unref.js +++ b/test/parallel/test-pipe-unref.js @@ -1,10 +1,10 @@ 'use strict'; -var common = require('../common'); -var net = require('net'); +const common = require('../common'); +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-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(); + }); +}); diff --git a/test/parallel/test-preload.js b/test/parallel/test-preload.js index 4ee564f0520cc5..922f5d9fb83a58 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 + ' '; }); @@ -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) { - if (err) throw 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) { 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) { if (err) throw err; assert.strictEqual(stdout, 'A\nhello\n'); - }); + } +); // test that preload can be used with stdin const stdinProc = childProcess.spawn( @@ -77,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; }); @@ -93,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; }); @@ -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) { 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) { 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) { if (err) throw err; assert.ok(/worker terminated with code 43/.test(stdout)); - }); + } +); diff --git a/test/parallel/test-process-argv-0.js b/test/parallel/test-process-argv-0.js index c3aacb60fa5403..d6b4bfe232323e 100644 --- a/test/parallel/test-process-argv-0.js +++ b/test/parallel/test-process-argv-0.js @@ -1,15 +1,15 @@ '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'], { + 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-before-exit.js b/test/parallel/test-process-before-exit.js deleted file mode 100644 index 5d8855869a8e4a..00000000000000 --- a/test/parallel/test-process-before-exit.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict'; -require('../common'); -var 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); +} 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..a1767464fd5978 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')); @@ -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-cpuUsage.js b/test/parallel/test-process-cpuUsage.js index 92dc71918585c3..062dac31cf7b5e 100644 --- a/test/parallel/test-process-cpuUsage.js +++ b/test/parallel/test-process-cpuUsage.js @@ -33,31 +33,61 @@ 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) { - assert.notEqual(result, null); + assert.notStrictEqual(result, null); assert(Number.isFinite(result.user)); assert(Number.isFinite(result.system)); diff --git a/test/parallel/test-process-exec-argv.js b/test/parallel/test-process-exec-argv.js index e32971ae81a893..8125850b424d84 100644 --- a/test/parallel/test-process-exec-argv.js +++ b/test/parallel/test-process-exec-argv.js @@ -1,15 +1,15 @@ '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)); } 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 8d657528d05561..337502ffcb30e8 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,10 +70,10 @@ function parent() { } function test(arg, exit) { - var spawn = require('child_process').spawn; - var node = process.execPath; - var f = __filename; - var option = { stdio: [ 0, 1, 'ignore' ] }; + const spawn = require('child_process').spawn; + 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-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..1634aad15497f5 100644 --- a/test/parallel/test-process-exit-recursive.js +++ b/test/parallel/test-process-exit-recursive.js @@ -1,9 +1,9 @@ 'use strict'; require('../common'); -var assert = require('assert'); +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 0ea36f158eaf9b..f7df7737ed1531 100644 --- a/test/parallel/test-process-exit.js +++ b/test/parallel/test-process-exit.js @@ -1,9 +1,9 @@ '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; +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 002ec7c1ab4c7c..e92f04853976f7 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.'); @@ -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) { - if (err) throw err; - var real_groups = stdout.match(/\d+/g).map(Number); + assert.ifError(err); + 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-hrtime.js b/test/parallel/test-process-hrtime.js index db16be0ad9e812..faa598d0a57362 100644 --- a/test/parallel/test-process-hrtime.js +++ b/test/parallel/test-process-hrtime.js @@ -1,9 +1,9 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const 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); }); } diff --git a/test/parallel/test-process-kill-null.js b/test/parallel/test-process-kill-null.js index 2516773f08786a..6c0ee8fa049a50 100644 --- a/test/parallel/test-process-kill-null.js +++ b/test/parallel/test-process-kill-null.js @@ -1,10 +1,10 @@ '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; +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 ee0554c32083f6..2c6ef37fc120df 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 // @@ -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 ab461902911a93..74c99b1f8f8058 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,10 +13,10 @@ switch (process.argv[2]) { } function parent() { - var spawn = require('child_process').spawn; - var child = spawn(process.execPath, [__filename, 'child']); + const spawn = require('child_process').spawn; + 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 b5d4dc35e4fe00..326854e98335df 100644 --- a/test/parallel/test-process-wrap.js +++ b/test/parallel/test-process-wrap.js @@ -1,14 +1,14 @@ 'use strict'; require('../common'); -var 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 assert = require('assert'); +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 b827dd9e368a94..27cb94bf704eb4 100644 --- a/test/parallel/test-promises-unhandled-rejections.js +++ b/test/parallel/test-promises-unhandled-rejections.js @@ -1,17 +1,17 @@ '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; - 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-punycode.js b/test/parallel/test-punycode.js index 7d969c66ee4e13..f895e2fc0e2607 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'), '日本語'); // http://tools.ietf.org/html/rfc3492#section-7.1 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 37cf66705d56d7..8cc589944b0508 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); @@ -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'}])], @@ -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, '', {}], @@ -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': ''}], @@ -87,10 +87,10 @@ var qsWeirdObjects = [ ]; // }}} -var vm = require('vm'); -var foreignObject = vm.runInNewContext('({"foo": ["bar", "baz"]})'); +const vm = require('vm'); +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 59b75cd0a86231..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,14 +55,14 @@ 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(); rli = new readline.Interface({ input: fi, output: fi, terminal: terminal, - historySize: 0 }); + historySize: 0 }); assert.strictEqual(rli.historySize, 0); fi.emit('data', 'asdf\n'); @@ -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 6bbbb2e918470d..258127655606f1 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() { @@ -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 acf0dc44a631c7..78c42f5f5f627d 100644 --- a/test/parallel/test-readline-set-raw-mode.js +++ b/test/parallel/test-readline-set-raw-mode.js @@ -1,14 +1,14 @@ '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; -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-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..5189e50929105c 100644 --- a/test/parallel/test-regress-GH-1531.js +++ b/test/parallel/test-regress-GH-1531.js @@ -1,20 +1,20 @@ '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 = { +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 7ce83e00092449..838391acd23b5f 100644 --- a/test/parallel/test-regress-GH-1899.js +++ b/test/parallel/test-regress-GH-1899.js @@ -1,13 +1,13 @@ '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], [ +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 7558529f9fc50c..c5b0ae4982d993 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 @@ -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 aef54c3ea6c7c4..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'); @@ -27,5 +27,5 @@ assert(common.fileExists(dir), 'Directory is not accessible'); // Test if file exists asynchronously fs.access(dir, function(err) { - assert(!err, 'Directory is not accessible'); + assert.ifError(err); }); diff --git a/test/parallel/test-regress-GH-4948.js b/test/parallel/test-regress-GH-4948.js index 0317778787c2e2..196c973cd093e3 100644 --- a/test/parallel/test-regress-GH-4948.js +++ b/test/parallel/test-regress-GH-4948.js @@ -2,10 +2,10 @@ // 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) { +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(); @@ -31,9 +31,9 @@ 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(); + 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 a23c947c320cfc..7f55356a15e027 100644 --- a/test/parallel/test-regress-GH-5927.js +++ b/test/parallel/test-regress-GH-5927.js @@ -1,20 +1,20 @@ '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); +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-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..9a6e0e8980f311 100644 --- a/test/parallel/test-regress-GH-746.js +++ b/test/parallel/test-regress-GH-746.js @@ -3,11 +3,11 @@ // This is a regression test for GH-746. const common = require('../common'); -var net = require('net'); +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 d18a3ae02c0d03..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); - assert.notEqual(undefined, result); + 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 20ca75c793ce24..719d4398251eab 100644 --- a/test/parallel/test-regress-GH-819.js +++ b/test/parallel/test-regress-GH-819.js @@ -1,7 +1,7 @@ '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'); +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 bb55050d2ce55e..78565e3f596594 100644 --- a/test/parallel/test-regress-GH-node-9326.js +++ b/test/parallel/test-regress-GH-node-9326.js @@ -1,14 +1,14 @@ '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, [ +const cp = child_process.spawn(process.execPath, [ '-e', 'process.kill(process.pid, "SIGINT")' ]); cp.on('exit', function(code) { - assert.notEqual(code, 0); + assert.notStrictEqual(code, 0); }); diff --git a/test/parallel/test-repl-.save.load.js b/test/parallel/test-repl-.save.load.js index 247f359e829d25..00d5f6791d54a5 100644 --- a/test/parallel/test-repl-.save.load.js +++ b/test/parallel/test-repl-.save.load.js @@ -1,24 +1,24 @@ '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']; +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 15f779d3b12269..e0554831cdca50 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; @@ -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-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-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-envvars.js b/test/parallel/test-repl-envvars.js index b08f6cbaf621e6..e8c369b244c607 100644 --- a/test/parallel/test-repl-envvars.js +++ b/test/parallel/test-repl-envvars.js @@ -45,7 +45,7 @@ function run(test) { }; REPL.createInternalRepl(env, opts, function(err, repl) { - if (err) throw err; + assert.ifError(err); // The REPL registers 'module' and 'require' globals common.allowGlobals(repl.context.module, repl.context.require); diff --git a/test/parallel/test-repl-harmony.js b/test/parallel/test-repl-harmony.js index a5928800381cfe..743bbe4fabfcd1 100644 --- a/test/parallel/test-repl-harmony.js +++ b/test/parallel/test-repl-harmony.js @@ -1,13 +1,13 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); -var spawn = require('child_process').spawn; -var args = ['-i']; -var child = spawn(process.execPath, args); +const spawn = require('child_process').spawn; +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 4a374cb0ab12e8..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() { @@ -33,8 +33,7 @@ common.refreshTmpDir(); const replHistoryPath = path.join(common.tmpDir, '.node_repl_history'); const checkResults = common.mustCall(function(err, r) { - if (err) - throw err; + assert.ifError(err); // The REPL registers 'module' and 'require' globals common.allowGlobals(r.context.module, r.context.require); 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 10166b4f06a692..6a65d53a029379 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,8 +12,8 @@ switch (process.argv[2]) { } function parent() { - var spawn = require('child_process').spawn; - var child = spawn(process.execPath, [__filename, 'child']); + const spawn = require('child_process').spawn; + 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; }); @@ -38,11 +38,12 @@ function parent() { } function child() { - var vm = require('vm'); + 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 b5f1d3856d3c71..835634b0a4ac1e 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); @@ -290,7 +290,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-repl-tab.js b/test/parallel/test-repl-tab.js index c075b8d4f1125f..7baa7d0aace812 100644 --- a/test/parallel/test-repl-tab.js +++ b/test/parallel/test-repl-tab.js @@ -1,12 +1,13 @@ '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(); -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-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 }); } diff --git a/test/parallel/test-repl-unexpected-token-recoverable.js b/test/parallel/test-repl-unexpected-token-recoverable.js index 84668c8657c453..0f783d3dcaf27b 100644 --- a/test/parallel/test-repl-unexpected-token-recoverable.js +++ b/test/parallel/test-repl-unexpected-token-recoverable.js @@ -3,16 +3,16 @@ * 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); +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-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..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 @@ -1,10 +1,10 @@ /* 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'); +assert.notStrictEqual(content.rocko, 'artischocko'); assert.equal(content, 'hello from module-stub!'); 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-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-sigint-infinite-loop.js b/test/parallel/test-sigint-infinite-loop.js index ecd64802acb627..30eb98ecb8a265 100644 --- a/test/parallel/test-sigint-infinite-loop.js +++ b/test/parallel/test-sigint-infinite-loop.js @@ -3,14 +3,14 @@ // 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'); -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 7938ae04d6591b..34722b712f8889 100644 --- a/test/parallel/test-signal-safety.js +++ b/test/parallel/test-signal-safety.js @@ -1,12 +1,12 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var Signal = process.binding('signal_wrap').Signal; +const assert = require('assert'); +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 480d5d2edc321e..f21b52d519b2ba 100644 --- a/test/parallel/test-socket-write-after-fin-error.js +++ b/test/parallel/test-socket-write-after-fin-error.js @@ -1,20 +1,20 @@ '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'); -var serverData = ''; -var gotServerEnd = false; -var clientData = ''; -var gotClientEnd = false; -var gotServerError = false; +const net = require('net'); +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; @@ -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-socket-write-after-fin.js b/test/parallel/test-socket-write-after-fin.js index 70f0d9bf843f9b..c8ff56871734af 100644 --- a/test/parallel/test-socket-write-after-fin.js +++ b/test/parallel/test-socket-write-after-fin.js @@ -1,13 +1,13 @@ '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({ +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-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-stdin-pipe-resume.js b/test/parallel/test-stdin-pipe-resume.js index cb288070450a1f..06cce3edfe403f 100644 --- a/test/parallel/test-stdin-pipe-resume.js +++ b/test/parallel/test-stdin-pipe-resume.js @@ -1,19 +1,19 @@ '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; - var buffers = []; - var child = spawn(process.execPath, [__filename, 'child']); + const spawn = require('child_process').spawn; + 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-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..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 @@ -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,10 +8,10 @@ else parent(); function parent() { - var spawn = require('child_process').spawn; - var child = spawn(process.execPath, [__filename, 'child']); - var out = ''; - var err = ''; + const spawn = require('child_process').spawn; + 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 e154d41b6bb8d1..6aa961301349fc 100644 --- a/test/parallel/test-stdout-stderr-reading.js +++ b/test/parallel/test-stdout-stderr-reading.js @@ -1,10 +1,10 @@ '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'); -var read = net.Socket.prototype.read; +const net = require('net'); +const read = net.Socket.prototype.read; net.Socket.prototype.read = function() { if (this.fd === 1) @@ -20,11 +20,11 @@ else parent(); function parent() { - var spawn = require('child_process').spawn; - var node = process.execPath; + const spawn = require('child_process').spawn; + 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 10391c481a826d..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); @@ -28,11 +28,10 @@ function test(size, useBuffer, cb) { console.log(`${size} chars to ${tmpFile}...`); childProcess.exec(cmd, common.mustCall(function(err) { - if (err) throw err; - + 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-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-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); diff --git a/test/parallel/test-stream-pipe-event.js b/test/parallel/test-stream-pipe-event.js index d8601dd04a4d8e..1b5447eaa21ff9 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; @@ -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 22a3156f62f502..5fc1f5e89cf156 100644 --- a/test/parallel/test-stream-push-order.js +++ b/test/parallel/test-stream-push-order.js @@ -1,21 +1,21 @@ '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({ +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 a5ebe4d3e917f6..7bce493bbd33ce 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) { @@ -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 fb2114f44dad19..a5d7e48bfb3fa9 100644 --- a/test/parallel/test-stream-readable-constructor-set-methods.js +++ b/test/parallel/test-stream-readable-constructor-set-methods.js @@ -1,16 +1,16 @@ '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; +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-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-stream-readable-flow-recursion.js b/test/parallel/test-stream-readable-flow-recursion.js index 0c0b16e8f5ca7e..b1e421a71fd15b 100644 --- a/test/parallel/test-stream-readable-flow-recursion.js +++ b/test/parallel/test-stream-readable-flow-recursion.js @@ -1,20 +1,20 @@ '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; -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 720357a01b9839..7be673c517b30b 100644 --- a/test/parallel/test-stream-transform-constructor-set-methods.js +++ b/test/parallel/test-stream-transform-constructor-set-methods.js @@ -1,22 +1,22 @@ '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; +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-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); diff --git a/test/parallel/test-stream-transform-split-objectmode.js b/test/parallel/test-stream-transform-split-objectmode.js index 610f234bead901..52185e18711090 100644 --- a/test/parallel/test-stream-transform-split-objectmode.js +++ b/test/parallel/test-stream-transform-split-objectmode.js @@ -1,10 +1,10 @@ '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 }); +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 477f5c4be56bac..d555fd7cae2330 100644 --- a/test/parallel/test-stream-unshift-empty-chunk.js +++ b/test/parallel/test-stream-unshift-empty-chunk.js @@ -1,14 +1,14 @@ '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; -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 d1d4af5b824baf..9eac52bc1aea44 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); @@ -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 7d7dfb5f1ccfa0..9b344487f61580 100644 --- a/test/parallel/test-stream-writable-constructor-set-methods.js +++ b/test/parallel/test-stream-writable-constructor-set-methods.js @@ -1,25 +1,25 @@ '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; +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-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-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 92479fc88f2958..4e05d2ba8e70e8 100644 --- a/test/parallel/test-stream-writev.js +++ b/test/parallel/test-stream-writev.js @@ -1,13 +1,13 @@ '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++) { - 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,25 +25,24 @@ 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) { - if (er) - throw er; + assert.ifError(er); counter++; assert.equal(counter, expect); }; } - 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', @@ -62,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 50bafc3737385d..da63644de099a1 100644 --- a/test/parallel/test-stream2-base64-single-char-read-end.js +++ b/test/parallel/test-stream2-base64-single-char-read-end.js @@ -1,14 +1,13 @@ '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(); -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 77312456590b25..f7c980791311da 100644 --- a/test/parallel/test-stream2-compatibility.js +++ b/test/parallel/test-stream2-compatibility.js @@ -1,12 +1,12 @@ '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; +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 fb489978f498ad..87edf5a5fa6437 100644 --- a/test/parallel/test-stream2-finish-pipe.js +++ b/test/parallel/test-stream2-finish-pipe.js @@ -1,14 +1,14 @@ '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(); +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 d674086055e431..6d3da191b06cb9 100644 --- a/test/parallel/test-stream2-httpclient-response-end.js +++ b/test/parallel/test-stream2-httpclient-response-end.js @@ -1,14 +1,14 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); -var http = require('http'); -var msg = 'Hello'; -var server = http.createServer(function(req, res) { +const assert = require('assert'); +const http = require('http'); +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 823407d396afb6..88fef4f24b6c30 100644 --- a/test/parallel/test-stream2-large-read-stall.js +++ b/test/parallel/test-stream2-large-read-stall.js @@ -1,28 +1,29 @@ '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. -var READSIZE = 100; -var PUSHSIZE = 20; -var PUSHCOUNT = 1000; -var HWM = 50; +const READSIZE = 100; +const PUSHSIZE = 20; +const PUSHCOUNT = 1000; +const HWM = 50; -var Readable = require('stream').Readable; -var r = new Readable({ +const Readable = require('stream').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; @@ -46,7 +47,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-objects.js b/test/parallel/test-stream2-objects.js index b18be26dc530fb..6c00f1b8691364 100644 --- a/test/parallel/test-stream2-objects.js +++ b/test/parallel/test-stream2-objects.js @@ -1,12 +1,12 @@ '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 = []; -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-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..908ac1bdb8e4ab 100644 --- a/test/parallel/test-stream2-pipe-error-once-listener.js +++ b/test/parallel/test-stream2-pipe-error-once-listener.js @@ -1,11 +1,11 @@ 'use strict'; require('../common'); -var util = require('util'); -var stream = require('stream'); +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 445a186715b659..95a98450a3034e 100644 --- a/test/parallel/test-stream2-push.js +++ b/test/parallel/test-stream2-push.js @@ -1,34 +1,33 @@ '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' }); -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(); @@ -38,7 +37,7 @@ source.on('end', function() { stream.push(null); }); -var reading = false; +let reading = false; function readStart() { console.error('readStart'); @@ -49,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', @@ -80,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 b2cfd05f872e30..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'); -var Readable = require('stream').Readable; -var r = new Readable(); -var N = 256 * 1024; +const Readable = require('stream').Readable; +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 2aa0725f734117..f3f39507e89dab 100644 --- a/test/parallel/test-stream2-readable-from-list.js +++ b/test/parallel/test-stream2-readable-from-list.js @@ -1,13 +1,13 @@ // 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 = []; -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 8a0687a6ebd90c..d6db6ba232c693 100644 --- a/test/parallel/test-stream2-readable-legacy-drain.js +++ b/test/parallel/test-stream2-readable-legacy-drain.js @@ -1,22 +1,22 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); +const assert = require('assert'); -var Stream = require('stream'); -var Readable = Stream.Readable; +const Stream = require('stream'); +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 c08cc287ce1cbf..66fae8274ecf3c 100644 --- a/test/parallel/test-stream2-readable-non-empty-end.js +++ b/test/parallel/test-stream2-readable-non-empty-end.js @@ -1,22 +1,22 @@ '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); -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); }; test.on('end', thrower); @@ -24,14 +24,14 @@ 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); - setTimeout(next); + setTimeout(next, 1); } test.read(0); }); @@ -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 02de3cf5b4cb23..5b2dae3c5327fa 100644 --- a/test/parallel/test-stream2-readable-wrap-empty.js +++ b/test/parallel/test-stream2-readable-wrap-empty.js @@ -1,14 +1,14 @@ '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(); +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-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'); -}); diff --git a/test/parallel/test-stream2-set-encoding.js b/test/parallel/test-stream2-set-encoding.js index 3deb67d48e7156..fdbd81e61332b1 100644 --- a/test/parallel/test-stream2-set-encoding.js +++ b/test/parallel/test-stream2-set-encoding.js @@ -1,12 +1,12 @@ '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 = []; -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 6a4036681f90b7..d66f1f064375e4 100644 --- a/test/parallel/test-stream2-transform.js +++ b/test/parallel/test-stream2-transform.js @@ -1,12 +1,12 @@ '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 = []; -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 d94e39f7667df4..1a1599ca32b4c7 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'); +const chunk = Buffer.from('hallo'); -var util = require('util'); +const util = require('util'); function TestWriter() { stream.Writable.call(this); @@ -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 5ecdd0f76ecb5a..c377ce9a510caa 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() { @@ -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 64d25fefc94c86..5a9550bcd41d7f 100644 --- a/test/parallel/test-stream3-pause-then-read.js +++ b/test/parallel/test-stream3-pause-then-read.js @@ -1,18 +1,18 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); -var stream = require('stream'); -var Readable = stream.Readable; -var Writable = stream.Writable; +const stream = require('stream'); +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 33b47a034a93bc..2c187d60142bbf 100644 --- a/test/parallel/test-string-decoder-end.js +++ b/test/parallel/test-string-decoder-end.js @@ -4,17 +4,17 @@ // result of the entire buffer. require('../common'); -var assert = require('assert'); -var SD = require('string_decoder').StringDecoder; -var encodings = ['base64', 'hex', 'utf8', 'utf16le', 'ucs2']; +const assert = require('assert'); +const SD = require('string_decoder').StringDecoder; +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 151ae8b4e0b11a..77ffbfcc73b1e1 100644 --- a/test/parallel/test-string-decoder.js +++ b/test/parallel/test-string-decoder.js @@ -1,11 +1,11 @@ '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(); +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 a34612f75d71f6..a242b943c91a4d 100644 --- a/test/parallel/test-stringbytes-external.js +++ b/test/parallel/test-stringbytes-external.js @@ -1,18 +1,18 @@ '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; +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-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..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'); -var 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 assert = require('assert'); +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,11 +35,11 @@ function makeConnection() { ///// -var connectCount = 0; -var endCount = 0; -var shutdownCount = 0; +let connectCount = 0; +let endCount = 0; +let 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..6b9dbd90a4c113 100644 --- a/test/parallel/test-tcp-wrap.js +++ b/test/parallel/test-tcp-wrap.js @@ -1,18 +1,18 @@ 'use strict'; require('../common'); -var assert = require('assert'); +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-timer-close.js b/test/parallel/test-timer-close.js index f13078e5a5bed1..aae93f25c55ec0 100644 --- a/test/parallel/test-timer-close.js +++ b/test/parallel/test-timer-close.js @@ -1,16 +1,11 @@ 'use strict'; -require('../common'); -var 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')); 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-args.js b/test/parallel/test-timers-args.js index 21eafd1bcd9ea6..1ba44d8bcf3664 100644 --- a/test/parallel/test-timers-args.js +++ b/test/parallel/test-timers-args.js @@ -1,13 +1,13 @@ '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; }); } 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-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 62482d510a6608..103cd964511a53 100644 --- a/test/parallel/test-timers-immediate-queue.js +++ b/test/parallel/test-timers-immediate-queue.js @@ -1,20 +1,18 @@ '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 // 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) @@ -26,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-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 c23af9d8307e9a..853f80a66a2384 100644 --- a/test/parallel/test-timers-ordering.js +++ b/test/parallel/test-timers-ordering.js @@ -1,22 +1,22 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var Timer = process.binding('timer_wrap').Timer; +const assert = require('assert'); -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-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-uncaught-exception.js b/test/parallel/test-timers-uncaught-exception.js index 6b6dc583715849..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'); -var assert = require('assert'); - -var exceptions = 0; -var timer1 = 0; -var timer2 = 0; +const common = require('../common'); +const assert = require('assert'); +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)); 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 a1b1265763bf1d..d970910b24abe6 100644 --- a/test/parallel/test-timers-unref-leak.js +++ b/test/parallel/test-timers-unref-leak.js @@ -1,17 +1,17 @@ 'use strict'; require('../common'); -var assert = require('assert'); +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 971c485a4cf986..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() { @@ -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-timers-unref.js b/test/parallel/test-timers-unref.js index 801b34792a1f73..2bde08f914d790 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; @@ -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 0b379e0eb45ad0..33f1706e3d399a 100644 --- a/test/parallel/test-timers.js +++ b/test/parallel/test-timers.js @@ -1,8 +1,8 @@ 'use strict'; require('../common'); -var assert = require('assert'); +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-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-alert.js b/test/parallel/test-tls-alert.js index db22443918453b..a8c6016f6218b7 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,12 +11,12 @@ 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; +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 dcde224e04344c..be499b84503472 100644 --- a/test/parallel/test-tls-async-cb-after-socket-end.js +++ b/test/parallel/test-tls-async-cb-after-socket-end.js @@ -10,19 +10,19 @@ 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 = { +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-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(); +}); 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(); +}); diff --git a/test/parallel/test-tls-cert-regression.js b/test/parallel/test-tls-cert-regression.js index a26bab7c46e107..ff5827bcf844ee 100644 --- a/test/parallel/test-tls-cert-regression.js +++ b/test/parallel/test-tls-cert-regression.js @@ -1,14 +1,14 @@ '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 = +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 d2fcf3e687e676..21ee41e927873b 100644 --- a/test/parallel/test-tls-client-abort.js +++ b/test/parallel/test-tls-client-abort.js @@ -1,20 +1,20 @@ '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')); +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 f3295f6d854a72..3247a2899acdfb 100644 --- a/test/parallel/test-tls-client-abort2.js +++ b/test/parallel/test-tls-client-abort2.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 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 33766dfd5b13b2..618178d4a497ad 100644 --- a/test/parallel/test-tls-client-default-ciphers.js +++ b/test/parallel/test-tls-client-default-ciphers.js @@ -1,17 +1,17 @@ '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() {} 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 171aa328142e13..016fcfa4da6a95 100644 --- a/test/parallel/test-tls-client-destroy-soon.js +++ b/test/parallel/test-tls-client-destroy-soon.js @@ -3,40 +3,40 @@ // 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 = { +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 c1e6597245a612..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,22 +40,22 @@ 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(); }); server.on('close', common.mustCall(function(err) { - assert(!err); + assert.ifError(err); if (next) 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 1d812a72093ba9..76e1034621f031 100644 --- a/test/parallel/test-tls-client-mindhsize.js +++ b/test/parallel/test-tls-client-mindhsize.js @@ -1,35 +1,35 @@ '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'); -var key = fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'); -var cert = fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem'); +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 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 75524a3a189b3e..96109d7656dd19 100644 --- a/test/parallel/test-tls-client-resume.js +++ b/test/parallel/test-tls-client-resume.js @@ -3,32 +3,32 @@ // 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 = { +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 983d88296eb26f..70d96ef1545ede 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'); @@ -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 2da7a192c30ebc..6172be813e97ce 100644 --- a/test/parallel/test-tls-close-error.js +++ b/test/parallel/test-tls-close-error.js @@ -1,22 +1,22 @@ '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({ +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 51b16746e30533..5d5bc1007749a7 100644 --- a/test/parallel/test-tls-close-notify.js +++ b/test/parallel/test-tls-close-notify.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 fs = require('fs'); +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 e2e0238ff8d0ad..2e4bcfbc6d4787 100644 --- a/test/parallel/test-tls-connect-no-host.js +++ b/test/parallel/test-tls-connect-no-host.js @@ -1,18 +1,18 @@ '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')); +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 6ec218e00366f6..de60ae084624cf 100644 --- a/test/parallel/test-tls-connect-pipe.js +++ b/test/parallel/test-tls-connect-pipe.js @@ -1,27 +1,27 @@ '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 = { +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-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-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-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..47be3f201b463e 100644 --- a/test/parallel/test-tls-delayed-attach-error.js +++ b/test/parallel/test-tls-delayed-attach-error.js @@ -1,24 +1,24 @@ '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); +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 b1e4beb2313c9a..d757ca756c3a09 100644 --- a/test/parallel/test-tls-delayed-attach.js +++ b/test/parallel/test-tls-delayed-attach.js @@ -1,27 +1,27 @@ '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 = ''; +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 92ab415e3ba0a6..4bc81af6e1f8a2 100644 --- a/test/parallel/test-tls-dhe.js +++ b/test/parallel/test-tls-dhe.js @@ -1,55 +1,55 @@ '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'); -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 spawn = require('child_process').spawn; +const fs = require('fs'); +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(); }); server.on('close', function(err) { - assert(!err); + assert.ifError(err); if (cb) 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 c2a7440a686a10..a0555e87781f59 100644 --- a/test/parallel/test-tls-ecdh-disable.js +++ b/test/parallel/test-tls-ecdh-disable.js @@ -1,27 +1,27 @@ '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 = { +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-ecdh.js b/test/parallel/test-tls-ecdh.js index 99c6e108ab736a..2c68e3d706406e 100644 --- a/test/parallel/test-tls-ecdh.js +++ b/test/parallel/test-tls-ecdh.js @@ -33,7 +33,7 @@ server.listen(0, '127.0.0.1', common.mustCall(function() { cmd += ' -no_rand_screen'; exec(cmd, common.mustCall(function(err, stdout, stderr) { - if (err) throw err; + assert.ifError(err); assert(stdout.includes(reply)); server.close(); })); diff --git a/test/parallel/test-tls-econnreset.js b/test/parallel/test-tls-econnreset.js index d9f6fffd326409..c0df9948f489ea 100644 --- a/test/parallel/test-tls-econnreset.js +++ b/test/parallel/test-tls-econnreset.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 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 034a6296659bdd..b2d6fe6eee88a3 100644 --- a/test/parallel/test-tls-fast-writing.js +++ b/test/parallel/test-tls-fast-writing.js @@ -1,23 +1,23 @@ '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'), - 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 e76a0961fb7ad6..4909fa45e160fb 100644 --- a/test/parallel/test-tls-handshake-error.js +++ b/test/parallel/test-tls-handshake-error.js @@ -1,23 +1,23 @@ '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({ +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() { @@ -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-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..f7894e46706da9 100644 --- a/test/parallel/test-tls-honorcipherorder.js +++ b/test/parallel/test-tls-honorcipherorder.js @@ -1,27 +1,27 @@ '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 nconns = 0; +const fs = require('fs'); +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 4008e5f099e4bc..bd3ad43fe653e5 100644 --- a/test/parallel/test-tls-invoke-queued.js +++ b/test/parallel/test-tls-invoke-queued.js @@ -1,19 +1,19 @@ '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 = ''; +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 08095fa99538cf..e1b580da303f8d 100644 --- a/test/parallel/test-tls-js-stream.js +++ b/test/parallel/test-tls-js-stream.js @@ -1,23 +1,23 @@ '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 = { +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 72c748248e448d..9af65c43a0661c 100644 --- a/test/parallel/test-tls-legacy-onselect.js +++ b/test/parallel/test-tls-legacy-onselect.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'); -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); +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 64dd14698916c8..4b81be35e34522 100644 --- a/test/parallel/test-tls-max-send-fragment.js +++ b/test/parallel/test-tls-max-send-fragment.js @@ -1,20 +1,20 @@ '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; -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 e29f5ee522829e..e3d5d661a799a7 100644 --- a/test/parallel/test-tls-multi-key.js +++ b/test/parallel/test-tls-multi-key.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'); -var fs = require('fs'); +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 cc04534bf91973..233d8453db1318 100644 --- a/test/parallel/test-tls-no-rsa-key.js +++ b/test/parallel/test-tls-no-rsa-key.js @@ -1,24 +1,24 @@ '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 = { +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-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-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-npn-server-client.js b/test/parallel/test-tls-npn-server-client.js index a5fe2da3a2a607..1b622cc8f72c20 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) { @@ -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 c030c7482ff6dd..4e03bcaf537f26 100644 --- a/test/parallel/test-tls-over-http-tunnel.js +++ b/test/parallel/test-tls-over-http-tunnel.js @@ -1,28 +1,28 @@ '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; +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 7f4e02a1bfa96d..911ea7097b1e70 100644 --- a/test/parallel/test-tls-pause.js +++ b/test/parallel/test-tls-pause.js @@ -1,26 +1,26 @@ '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 = { +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 b59d10faa78bc1..545caf403e103c 100644 --- a/test/parallel/test-tls-peer-certificate-encoding.js +++ b/test/parallel/test-tls-peer-certificate-encoding.js @@ -1,32 +1,32 @@ '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 = { +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 55bc9f40d3a240..693bb4cb3fa812 100644 --- a/test/parallel/test-tls-peer-certificate-multi-keys.js +++ b/test/parallel/test-tls-peer-certificate-multi-keys.js @@ -1,31 +1,31 @@ '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 = { +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-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(); +}); 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 fc793def177f3a..4873a3c696458f 100644 --- a/test/parallel/test-tls-request-timeout.js +++ b/test/parallel/test-tls-request-timeout.js @@ -1,22 +1,22 @@ '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 = { +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 24ac2177c54536..65a7d91a0ca606 100644 --- a/test/parallel/test-tls-securepair-server.js +++ b/test/parallel/test-tls-securepair-server.js @@ -1,31 +1,31 @@ '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(); +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-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 04c1547384c61e..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'); @@ -282,7 +282,7 @@ function runTest(port, testIndex) { requestCert: true, rejectUnauthorized: false }, function(err) { - assert(!err); + assert.ifError(err); c.write('\n_renegotiated\n'); handleConnection(c); }); 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 5a85e3b22e4c62..a1af1a917eb826 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) { @@ -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 @@ -42,7 +42,7 @@ server.listen(0, '127.0.0.1', function() { cmd += ' -no_rand_screen'; exec(cmd, function(err, stdout, stderr) { - if (err) throw err; + assert.ifError(err); response = stdout; server.close(); }); diff --git a/test/parallel/test-tls-sni-option.js b/test/parallel/test-tls-sni-option.js index d9823fa3dabdc4..2e7245336b8b98 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'); @@ -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 7a8046c743893d..93fffd3888ffd1 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'); @@ -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-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-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 62f9d82b3312ef..1c870893a3bced 100644 --- a/test/parallel/test-umask.js +++ b/test/parallel/test-umask.js @@ -1,16 +1,16 @@ '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; +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-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-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 ]'); diff --git a/test/parallel/test-util-inspect.js b/test/parallel/test-util-inspect.js index 1118065f1a09da..62743ebd19d16a 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\' }' ); @@ -232,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] }'); @@ -270,11 +271,11 @@ assert.strictEqual(util.inspect(value), '{ 2010-02-14T11:48:40.000Z aprop: 42 }' ); // test the internal isDate implementation -var Date2 = require('vm').runInNewContext('Date'); -var d = new Date2(); -var orig = util.inspect(d); +const Date2 = vm.runInNewContext('Date'); +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 @@ -282,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\' ]'); @@ -294,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); @@ -308,27 +309,27 @@ 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 -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() {} @@ -355,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]')); @@ -379,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); }); @@ -410,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( @@ -431,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, @@ -592,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; @@ -632,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\' }'); @@ -674,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), @@ -706,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()), @@ -743,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'); @@ -755,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 91f77d994da847..d45ebf2fc0b729 100644 --- a/test/parallel/test-util-log.js +++ b/test/parallel/test-util-log.js @@ -1,19 +1,19 @@ '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); -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-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-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..5b756f35962525 100644 --- a/test/parallel/test-v8-stats.js +++ b/test/parallel/test-v8-stats.js @@ -1,10 +1,10 @@ '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 = [ +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 b2b280c21bd173..2d57cc0d4ba328 100644 --- a/test/parallel/test-vm-basic.js +++ b/test/parallel/test-vm-basic.js @@ -1,11 +1,11 @@ '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 = {}; -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-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..1e9ed629fb114f 100644 --- a/test/parallel/test-vm-context-async-script.js +++ b/test/parallel/test-vm-context-async-script.js @@ -1,11 +1,11 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var vm = require('vm'); +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 4034441615ca9e..b77fc45217039f 100644 --- a/test/parallel/test-vm-context-property-forwarding.js +++ b/test/parallel/test-vm-context-property-forwarding.js @@ -1,11 +1,11 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var vm = require('vm'); +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 d3269d9035d010..e4f6960259abe2 100644 --- a/test/parallel/test-vm-context.js +++ b/test/parallel/test-vm-context.js @@ -1,14 +1,14 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); -var vm = require('vm'); -var Script = vm.Script; -var script = new Script('"passed";'); +const vm = require('vm'); +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) { @@ -48,14 +48,14 @@ 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 }); // 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 fc92cf2f6cb6eb..a0026102b578f8 100644 --- a/test/parallel/test-vm-create-and-run-in-context.js +++ b/test/parallel/test-vm-create-and-run-in-context.js @@ -1,13 +1,13 @@ '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(); -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 497bab1a57225f..27d7e6d7fc0274 100644 --- a/test/parallel/test-vm-create-context-accessors.js +++ b/test/parallel/test-vm-create-context-accessors.js @@ -1,9 +1,9 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var vm = require('vm'); +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 a0c29762330133..91bbbc3b7793bc 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'); @@ -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 248ef24f69ca07..13680c4c4e11ef 100644 --- a/test/parallel/test-vm-create-context-circular-reference.js +++ b/test/parallel/test-vm-create-context-circular-reference.js @@ -1,9 +1,9 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var vm = require('vm'); +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 5674f582426f1f..bafb32accb6a0e 100644 --- a/test/parallel/test-vm-cross-context.js +++ b/test/parallel/test-vm-cross-context.js @@ -1,9 +1,9 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); -var vm = require('vm'); -var ctx = vm.createContext(global); +const vm = require('vm'); +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 fd41be7564aab0..9f27723a0421a9 100644 --- a/test/parallel/test-vm-function-declaration.js +++ b/test/parallel/test-vm-function-declaration.js @@ -1,12 +1,12 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); -var vm = require('vm'); -var o = vm.createContext({ console: console }); +const vm = require('vm'); +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 73d1520e0dad69..62a714615ddc31 100644 --- a/test/parallel/test-vm-global-define-property.js +++ b/test/parallel/test-vm-global-define-property.js @@ -1,10 +1,10 @@ 'use strict'; require('../common'); -var assert = require('assert'); +const assert = require('assert'); -var vm = require('vm'); +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 7d90408b64c2c7..ae9fd71b3109ee 100644 --- a/test/parallel/test-vm-global-identity.js +++ b/test/parallel/test-vm-global-identity.js @@ -1,11 +1,11 @@ 'use strict'; require('../common'); -var assert = require('assert'); -var vm = require('vm'); +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 1c1274ef3543f6..80c1a2127f918c 100644 --- a/test/parallel/test-vm-harmony-symbols.js +++ b/test/parallel/test-vm-harmony-symbols.js @@ -1,10 +1,10 @@ '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 = {}; +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 cc106a15fbfc61..e58b896fccaa43 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'); @@ -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 d908d713748f7f..25e16e8f5ccc55 100644 --- a/test/parallel/test-vm-proxies.js +++ b/test/parallel/test-vm-proxies.js @@ -1,12 +1,12 @@ '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. -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 c4f10c183b6ef2..076f81dbf6ff15 100644 --- a/test/parallel/test-vm-static-this.js +++ b/test/parallel/test-vm-static-this.js @@ -1,12 +1,12 @@ /* 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; // 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 75748b24e193ee..1a97393d6d97a7 100644 --- a/test/parallel/test-vm-syntax-error-message.js +++ b/test/parallel/test-vm-syntax-error-message.js @@ -1,9 +1,9 @@ '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, [ +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 0536ae37a1b489..5260ca7dc28572 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() { @@ -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-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(); diff --git a/test/parallel/test-whatwg-url-properties.js b/test/parallel/test-whatwg-url-properties.js index 60cf581ad8da4d..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] @@ -19,9 +21,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); @@ -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'); +} diff --git a/test/parallel/test-whatwg-url-searchparams-constructor.js b/test/parallel/test-whatwg-url-searchparams-constructor.js index 98349021586f1a..34ccb4c37d55f3 100644 --- a/test/parallel/test-whatwg-url-searchparams-constructor.js +++ b/test/parallel/test-whatwg-url-searchparams-constructor.js @@ -30,7 +30,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.'); @@ -40,19 +40,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"'); @@ -68,7 +68,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 667738f817b707..cfc6c345a6b3ee 100644 --- a/test/parallel/test-whatwg-url-searchparams-get.js +++ b/test/parallel/test-whatwg-url-searchparams-get.js @@ -24,7 +24,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-whatwg-url-searchparams.js b/test/parallel/test-whatwg-url-searchparams.js index 54743b97a31da9..ca8f4ff070bfeb 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 3b2aca2afd89d7..20544dbb7f50ac 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 43784fb390a1f9..838b1ce4798b75 100644 --- a/test/parallel/test-writeint.js +++ b/test/parallel/test-writeint.js @@ -4,9 +4,10 @@ */ require('../common'); 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); @@ -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,15 +31,15 @@ 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); } function test16(clazz) { - var buffer = new clazz(6); + const buffer = new clazz(6); buffer.writeInt16BE(0x0023, 0); buffer.writeInt16LE(0x0023, 2); @@ -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,15 +84,15 @@ 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); } function test32(clazz) { - var buffer = new clazz(8); + const buffer = new clazz(8); buffer.writeInt32BE(0x23, 0); buffer.writeInt32LE(0x23, 4); @@ -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); } 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 9e2cde6b2fadae..42e6994e1b6389 100644 --- a/test/parallel/test-zerolengthbufferbug.js +++ b/test/parallel/test-zerolengthbufferbug.js @@ -2,13 +2,13 @@ // 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); +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}); + 'Content-Length': buffer.length}); res.end(buffer); }); 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-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); })); 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 ee2ee85d73ff09..7b0e1fcaae8ce6 100644 --- a/test/parallel/test-zlib-invalid-input.js +++ b/test/parallel/test-zlib-invalid-input.js @@ -21,10 +21,10 @@ 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() ]; -var hadError = []; + zlib.Gunzip(), + zlib.Inflate(), + zlib.InflateRaw() ]; +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-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); diff --git a/test/parallel/test-zlib-truncated.js b/test/parallel/test-zlib-truncated.js index 92a18a538c1ee4..c7b84c0d703711 100644 --- a/test/parallel/test-zlib-truncated.js +++ b/test/parallel/test-zlib-truncated.js @@ -22,7 +22,7 @@ const inputString = 'ΩΩLorem ipsum dolor sit amet, consectetur adipiscing eli' { comp: 'deflateRaw', decomp: 'inflateRaw', decompSync: 'inflateRawSync' } ].forEach(function(methods) { zlib[methods.comp](inputString, function(err, compressed) { - assert(!err); + assert.ifError(err); const truncated = compressed.slice(0, compressed.length / 2); const toUTF8 = (buffer) => buffer.toString('utf-8'); 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 ea158ded48b5c1..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/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 diff --git a/test/pummel/test-abort-fatal-error.js b/test/pummel/test-abort-fatal-error.js index 0bb2cb2c39998e..d1a8d3daa65e4c 100644 --- a/test/pummel/test-abort-fatal-error.js +++ b/test/pummel/test-abort-fatal-error.js @@ -1,15 +1,15 @@ '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; +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-child-process-spawn-loop.js b/test/pummel/test-child-process-spawn-loop.js index 7e686cada244b3..41d9ff1e49c17b 100644 --- a/test/pummel/test-child-process-spawn-loop.js +++ b/test/pummel/test-child-process-spawn-loop.js @@ -1,29 +1,29 @@ '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 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); }); 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 448319318b44a4..5be6abb9a8b29c 100644 --- a/test/pummel/test-dh-regr.js +++ b/test/pummel/test-dh-regr.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'); -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 1949045888c138..d1615a3855af43 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'); @@ -11,37 +11,37 @@ 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); 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 * 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 6f6e1511b14442..131b214fc53f42 100644 --- a/test/pummel/test-exec.js +++ b/test/pummel/test-exec.js @@ -1,9 +1,9 @@ '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; +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,19 +55,21 @@ 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); assert.ok(err.killed); assert.strictEqual(err.signal, 'SIGTERM'); + assert.strictEqual(stdout, ''); + assert.strictEqual(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); @@ -79,12 +81,14 @@ 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); 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, ''); }); diff --git a/test/pummel/test-fs-watch-file-slow.js b/test/pummel/test-fs-watch-file-slow.js index 508de487f6dc23..78c36152ecd315 100644 --- a/test/pummel/test-fs-watch-file-slow.js +++ b/test/pummel/test-fs-watch-file-slow.js @@ -1,13 +1,13 @@ '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; +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 4e08e9e9d1cc9b..7713fe74ed99aa 100644 --- a/test/pummel/test-fs-watch-file.js +++ b/test/pummel/test-fs-watch-file.js @@ -1,26 +1,26 @@ '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; -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); @@ -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); diff --git a/test/pummel/test-fs-watch-non-recursive.js b/test/pummel/test-fs-watch-non-recursive.js index ead7de9e28dc47..b7c19b9c360818 100644 --- a/test/pummel/test-fs-watch-non-recursive.js +++ b/test/pummel/test-fs-watch-non-recursive.js @@ -1,11 +1,11 @@ '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'); -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 293c6ab748e9c2..e465c02a90161c 100644 --- a/test/pummel/test-http-many-keep-alive-connections.js +++ b/test/pummel/test-http-many-keep-alive-connections.js @@ -1,14 +1,14 @@ '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; -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 8bda7cc10286e9..850e0949c4a64a 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.'); @@ -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 a122e47bc57a57..39256aa6304b74 100644 --- a/test/pummel/test-https-large-response.js +++ b/test/pummel/test-https-large-response.js @@ -1,25 +1,25 @@ '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 = { +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 fab59591993a69..a08676277af6ce 100644 --- a/test/pummel/test-https-no-reader.js +++ b/test/pummel/test-https-no-reader.js @@ -1,34 +1,34 @@ '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 = { +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-keep-alive.js b/test/pummel/test-keep-alive.js index 1861b2df970e18..a9e91e201bb19b 100644 --- a/test/pummel/test-keep-alive.js +++ b/test/pummel/test-keep-alive.js @@ -1,19 +1,19 @@ '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'); 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); }); diff --git a/test/pummel/test-net-connect-econnrefused.js b/test/pummel/test-net-connect-econnrefused.js index 2b6dc84f37195c..30da36d983e4f7 100644 --- a/test/pummel/test-net-connect-econnrefused.js +++ b/test/pummel/test-net-connect-econnrefused.js @@ -1,21 +1,22 @@ '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; -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 3b91a110eaa585..f16034e4773510 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, @@ -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 52d05b35cbe2c4..a92ae033a09a17 100644 --- a/test/pummel/test-net-many-clients.js +++ b/test/pummel/test-net-many-clients.js @@ -1,19 +1,19 @@ '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; -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 b0c51260436e0c..db426edbe9c507 100644 --- a/test/pummel/test-net-pause.js +++ b/test/pummel/test-net-pause.js @@ -1,12 +1,12 @@ '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; +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 c9cac778d59f4e..9a598435d1bd28 100644 --- a/test/pummel/test-net-pingpong-delay.js +++ b/test/pummel/test-net-pingpong-delay.js @@ -1,15 +1,15 @@ '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; - 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 85dce02b6cf635..6ede6f9fcb2763 100644 --- a/test/pummel/test-net-pingpong.js +++ b/test/pummel/test-net-pingpong.js @@ -1,19 +1,19 @@ '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; +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 415523763eef3c..d6dd8e489cc116 100644 --- a/test/pummel/test-net-timeout.js +++ b/test/pummel/test-net-timeout.js @@ -1,14 +1,14 @@ '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; -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 7af47a47a8b634..a3d0abceb6c765 100644 --- a/test/pummel/test-net-timeout2.js +++ b/test/pummel/test-net-timeout2.js @@ -2,16 +2,16 @@ // 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; +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 21eae0f5ab72d0..6c3c1f202a81c3 100644 --- a/test/pummel/test-net-write-callbacks.js +++ b/test/pummel/test-net-write-callbacks.js @@ -1,12 +1,12 @@ '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; +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 04225bae421b1a..d02b9c79822a88 100644 --- a/test/pummel/test-process-hrtime.js +++ b/test/pummel/test-process-hrtime.js @@ -1,18 +1,18 @@ 'use strict'; require('../common'); -var assert = require('assert'); +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 8d2d88b74f736f..5c09d59b06d55c 100644 --- a/test/pummel/test-process-uptime.js +++ b/test/pummel/test-process-uptime.js @@ -1,14 +1,14 @@ 'use strict'; require('../common'); -var assert = require('assert'); +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 7bbd13dd196457..a3700c500b4f53 100644 --- a/test/pummel/test-regress-GH-814.js +++ b/test/pummel/test-regress-GH-814.js @@ -4,7 +4,7 @@ const common = require('../common'); function newBuffer(size, value) { - var buffer = Buffer.allocUnsafe(size); + const buffer = Buffer.allocUnsafe(size); while (size--) { buffer[size] = value; } @@ -13,19 +13,19 @@ function newBuffer(size, value) { return buffer; } -var fs = require('fs'); -var testFileName = require('path').join(common.tmpDir, 'GH-814_testFile.txt'); -var testFileFD = fs.openSync(testFileName, 'w'); +const fs = require('fs'); +const testFileName = require('path').join(common.tmpDir, 'GH-814_testFile.txt'); +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 = []; -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) { @@ -33,13 +33,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 7909a461f37956..ba7d45124bf9fa 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'); -var testFD = fs.openSync(testFileName, 'w'); +const fs = require('fs'); +const testFileName = require('path').join(common.tmpDir, 'GH-814_test.txt'); +const 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) { @@ -26,12 +26,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() { @@ -50,7 +50,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; @@ -74,7 +74,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 8bbf3c8f1a0ff4..0619fd84de3b5e 100644 --- a/test/pummel/test-regress-GH-892.js +++ b/test/pummel/test-regress-GH-892.js @@ -5,39 +5,40 @@ // 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; +const bytesExpected = 1024 * 1024 * 32; -var started = false; +let 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; 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)); @@ -58,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 897b9d6dc27d46..e1e5e011020fe2 100644 --- a/test/pummel/test-stream-pipe-multi.js +++ b/test/pummel/test-stream-pipe-multi.js @@ -3,16 +3,16 @@ // doesn't break anything. require('../common'); -var assert = require('assert'); -var 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 assert = require('assert'); +const Stream = require('stream').Stream; +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 6bb2386b0b17dc..073c1d8e35ad36 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); @@ -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 588d2327ff37dd..4555582371b9ff 100644 --- a/test/pummel/test-timers.js +++ b/test/pummel/test-timers.js @@ -1,21 +1,21 @@ '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? +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 5075806c1085b6..dd2b43ed60278f 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.'); @@ -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 b55e33cee0afc4..b1d1f05190c39d 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, @@ -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 7a1b8770132e96..75e7b400592191 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(); @@ -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 66d700ae4bc6a9..f02eb51a2f6742 100644 --- a/test/pummel/test-tls-server-large-request.js +++ b/test/pummel/test-tls-server-large-request.js @@ -1,20 +1,20 @@ '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 +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 c23a8afcf7fe9a..c194188b3682a9 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,19 +22,19 @@ 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; + 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 a93793989f0b2b..574a83b18f2846 100644 --- a/test/pummel/test-tls-throttle.js +++ b/test/pummel/test-tls-throttle.js @@ -2,33 +2,33 @@ // 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); +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 c6623991922da9..8503e2389b44a7 100644 --- a/test/pummel/test-vm-memleak.js +++ b/test/pummel/test-vm-memleak.js @@ -2,23 +2,23 @@ // Flags: --max_old_space_size=32 require('../common'); -var assert = require('assert'); +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/pummel/test-watch-file.js b/test/pummel/test-watch-file.js index 8fdf6b32b2d78c..90909875d74a15 100644 --- a/test/pummel/test-watch-file.js +++ b/test/pummel/test-watch-file.js @@ -1,18 +1,15 @@ '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'); -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); diff --git a/test/sequential/test-child-process-execsync.js b/test/sequential/test-child-process-execsync.js index 137ddbda425f2c..20a35b98b36c6f 100644 --- a/test/sequential/test-child-process-execsync.js +++ b/test/sequential/test-child-process-execsync.js @@ -1,16 +1,16 @@ '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; +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-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'); diff --git a/test/sequential/test-debugger-debug-brk.js b/test/sequential/test-debugger-debug-brk.js index 3b54f853bc8de3..26c3418171e8df 100644 --- a/test/sequential/test-debugger-debug-brk.js +++ b/test/sequential/test-debugger-debug-brk.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; -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/parallel/test-fs-readfile-tostring-fail.js b/test/sequential/test-fs-readfile-tostring-fail.js similarity index 97% rename from test/parallel/test-fs-readfile-tostring-fail.js rename to test/sequential/test-fs-readfile-tostring-fail.js index 8ed9658a25889a..593b8da0fd8afa 100644 --- a/test/parallel/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-fs-watch.js b/test/sequential/test-fs-watch.js index 43b23bd5bd0a79..34e53f59aa0961 100644 --- a/test/sequential/test-fs-watch.js +++ b/test/sequential/test-fs-watch.js @@ -1,25 +1,25 @@ '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 expectFilePath = common.isWindows || - common.isLinux || - common.isOSX; +const expectFilePath = common.isWindows || + common.isLinux || + common.isOSX; -var watchSeenOne = 0; -var watchSeenTwo = 0; -var watchSeenThree = 0; +let watchSeenOne = 0; +let watchSeenTwo = 0; +let watchSeenThree = 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); process.on('exit', function() { assert.ok(watchSeenOne > 0); @@ -33,12 +33,12 @@ fs.writeFileSync(filepathOne, 'hello'); assert.doesNotThrow( function() { - var watcher = fs.watch(filepathOne); + const watcher = fs.watch(filepathOne); watcher.on('change', function(event, filename) { - assert.equal('change', event); + assert.strictEqual('change', event); if (expectFilePath) { - assert.equal('watch.txt', filename); + assert.strictEqual('watch.txt', filename); } watcher.close(); ++watchSeenOne; @@ -57,11 +57,11 @@ fs.writeFileSync(filepathTwoAbs, 'howdy'); assert.doesNotThrow( function() { - var watcher = fs.watch(filepathTwo, function(event, filename) { - assert.equal('change', event); + const watcher = fs.watch(filepathTwo, function(event, filename) { + assert.strictEqual('change', event); if (expectFilePath) { - assert.equal('hasOwnProperty', filename); + assert.strictEqual('hasOwnProperty', filename); } watcher.close(); ++watchSeenTwo; @@ -79,13 +79,13 @@ const filepathThree = path.join(testsubdir, filenameThree); assert.doesNotThrow( function() { - var watcher = fs.watch(testsubdir, function(event, filename) { - var renameEv = common.isSunOS ? 'change' : 'rename'; - assert.equal(renameEv, event); + const watcher = fs.watch(testsubdir, function(event, filename) { + const renameEv = common.isSunOS ? 'change' : 'rename'; + assert.strictEqual(renameEv, event); if (expectFilePath) { - assert.equal('newfile.txt', filename); + assert.strictEqual('newfile.txt', filename); } else { - assert.equal(null, filename); + assert.strictEqual(null, filename); } watcher.close(); ++watchSeenThree; @@ -94,7 +94,7 @@ assert.doesNotThrow( ); setImmediate(function() { - var fd = fs.openSync(filepathThree, 'w'); + const fd = fs.openSync(filepathThree, 'w'); fs.closeSync(fd); }); @@ -106,9 +106,9 @@ fs.watch(__filename, {persistent: false}, function() { // whitebox test to ensure that wrapped FSEvent is safe // https://github.com/joyent/node/issues/6690 -var oldhandle; +let oldhandle; assert.throws(function() { - var w = fs.watch(__filename, function(event, filename) { }); + const w = fs.watch(__filename, function(event, filename) { }); oldhandle = w._handle; w._handle = { close: w._handle.close }; w.close(); @@ -116,7 +116,7 @@ assert.throws(function() { oldhandle.close(); // clean up assert.throws(function() { - var w = fs.watchFile(__filename, {persistent: false}, function() {}); + const w = fs.watchFile(__filename, {persistent: false}, function() {}); oldhandle = w._handle; w._handle = { stop: w._handle.stop }; w.stop(); 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 61746a282f5eaa..dd4e7ba76b611f 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,12 +96,12 @@ 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'); }); -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\''); @@ -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', @@ -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 3ebf9db548d4db..a7f64c2e73da10 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,8 +18,8 @@ switch (process.argv[2]) { } function server() { - var net = require('net'); - var content = Buffer.alloc(64 * 1024 * 1024, '#'); + const net = require('net'); + const content = Buffer.alloc(64 * 1024 * 1024, '#'); net.createServer(function(socket) { this.close(); socket.on('end', function() { @@ -35,8 +35,8 @@ function server() { } function client() { - var net = require('net'); - var client = net.connect({ + const net = require('net'); + const client = net.connect({ host: common.localhostIPv4, port: common.PORT }, function() { @@ -45,15 +45,15 @@ function client() { } function parent() { - var spawn = require('child_process').spawn; - var node = process.execPath; + const spawn = require('child_process').spawn; + 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 c5f0bba1335264..c464193b23f3e4 100644 --- a/test/sequential/test-regress-GH-1726.js +++ b/test/sequential/test-regress-GH-1726.js @@ -5,11 +5,11 @@ // 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; +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 7f0e03f9ac08e1..249817de1d2068 100644 --- a/test/sequential/test-regress-GH-4015.js +++ b/test/sequential/test-regress-GH-4015.js @@ -1,10 +1,10 @@ '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"'; +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 aa1ec12c30f609..87a8861ac35477 100644 --- a/test/sequential/test-regress-GH-4027.js +++ b/test/sequential/test-regress-GH-4027.js @@ -1,12 +1,12 @@ '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(); -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 0c70337de7f146..c9b630b0c81755 100644 --- a/test/sequential/test-regress-GH-784.js +++ b/test/sequential/test-regress-GH-784.js @@ -7,13 +7,13 @@ // 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) { - 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 5b0aac802e16a3..06c839aa483fa8 100644 --- a/test/sequential/test-regress-GH-877.js +++ b/test/sequential/test-regress-GH-877.js @@ -1,30 +1,30 @@ '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; -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 0188b3b8c502d8..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,14 +30,14 @@ 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); } 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' + @@ -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 2571583f7690b5..b591f1746b62d4 100644 --- a/test/sequential/test-require-cache-without-stat.js +++ b/test/sequential/test-require-cache-without-stat.js @@ -2,17 +2,17 @@ // 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; +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 7baba6e63b81b0..2891335c813562 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'); -var FSReadable = fs.ReadStream; +const fs = require('fs'); +const FSReadable = fs.ReadStream; -var path = require('path'); -var file = path.resolve(common.fixturesDir, 'x1024.txt'); +const path = require('path'); +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]; -var util = require('util'); -var Stream = require('stream'); +const util = require('util'); +const Stream = require('stream'); util.inherits(TestWriter, 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 c7daaa6b083205..e37a5f2cd1b38e 100644 --- a/test/sequential/test-stream2-stderr-sync.js +++ b/test/sequential/test-stream2-stderr-sync.js @@ -4,12 +4,12 @@ require('../common'); function parent() { - var spawn = require('child_process').spawn; - var assert = require('assert'); - var i = 0; + const spawn = require('child_process').spawn; + const assert = require('assert'); + 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; @@ -42,8 +42,8 @@ function child1() { // using a net socket function child2() { - var net = require('net'); - var socket = new net.Socket({ + const net = require('net'); + 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-util-debug.js b/test/sequential/test-util-debug.js index 1159278efa475d..08988997e735a6 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(); @@ -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'; - var spawn = require('child_process').spawn; - var child = spawn(process.execPath, [__filename, 'child'], { + const spawn = require('child_process').spawn; + 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() { - var util = require('util'); - var debug = util.debuglog('tud'); + const util = require('util'); + const debug = util.debuglog('tud'); debug('this', { is: 'a' }, /debugging/); debug('number=%d string=%s obj=%j', 1234, 'asdf', { foo: 'bar' }); console.log('ok'); diff --git a/test/sequential/test-vm-timeout-rethrow.js b/test/sequential/test-vm-timeout-rethrow.js index f0f9c0b9c51063..a434e2ae3e6978 100644 --- a/test/sequential/test-vm-timeout-rethrow.js +++ b/test/sequential/test-vm-timeout-rethrow.js @@ -1,15 +1,15 @@ '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' + - '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 0626c45826781b..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; -var assert = require('assert'); +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); 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) 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) - }; -}; 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 - }; - } -}; 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`); + } + } + }; +}; 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/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" } 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